Skip to content

Commit

Permalink
Auth routes
Browse files Browse the repository at this point in the history
  • Loading branch information
Tamoziit committed Nov 16, 2024
1 parent af86f28 commit d1a67bd
Show file tree
Hide file tree
Showing 7 changed files with 397 additions and 0 deletions.
87 changes: 87 additions & 0 deletions backend/controllers/auth.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import bcrypt from "bcryptjs";
import User from "../models/user.model.js";

export const signup = async (req, res) => {
try {
const { name, email, password, mobileNo, role } = req.body;

//Validators
if (password.length < 6) {
return res.status(400).json({ error: "Pasword should be atleast 6 characters long" });
}
if (name.length < 2) {
return res.status(400).json({ error: "Name should be atleast 2 characters long" });
}
if (mobileNo.length != 10) {
return res.status(400).json({ error: "Enter a valid Mobile No." });
}

const user = await User.findOne({ email });
if (user) {
return res.status(400).json({ error: "User with this email already exists. Try logging into your account or signup with another email" });
}

const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);

const newUser = new User({
name,
email,
password: hashedPassword,
mobileNo,
role,
});

if (newUser) {
await newUser.save();
return res.status(201).json({
_id: newUser._id,
name: newUser.name,
email: newUser.email,
mobileNo: newUser.mobileNo,
role: newUser.role
});
} else {
return res.status(400).json({ error: "Invalid User Data" });
}

} catch (error) {
console.log("Error in Signup controller", error.message);
return res.status(500).json({ error: "Internal Server Error" });
}
}

export const login = async (req, res) => {
try {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ error: "Cannot find User" });
}

const isPaswordCorrect = await bcrypt.compare(password, user.password || "");
if (!isPaswordCorrect) {
return res.status(400).json({ error: "Invalid Login Credentials" });
}

res.status(200).json({
_id: user._id,
name: user.name,
email: user.email,
mobileNo: user.mobileNo,
role: user.role
});
} catch (error) {
console.log("Error in Login controller", error.message);
res.status(500).json({ error: "Internal Server Error" });
}
}

export const logout = (req, res) => {
try {
res.status(200).json({ message: "Logged out Successfully" });
} catch (error) {
console.log("Error in Logout controller", error.message);
res.status(500).json({ error: "Internal Server Error" });
}
}
12 changes: 12 additions & 0 deletions backend/db/connectToMongoDB.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import mongoose from "mongoose";

const connectToMongoDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI);
console.log("Connected to MongoDB");
} catch (error) {
console.log("Error in connecting to MongoDB");
}
}

export default connectToMongoDB;
33 changes: 33 additions & 0 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,47 @@
import express from "express";
import dotenv from "dotenv";
import bodyParser from "body-parser";
import morgan from "morgan";
import helmet from "helmet";
import cors from "cors";
dotenv.config();

import connectToMongoDB from "./db/connectToMongoDB.js";
import authRoutes from "./routes/auth.routes.js";

const PORT = process.env.PORT || 5000;
const app = express();

const corsConfig = {
origin: "*",
methods: [
'GET',
'POST',
'PATCH',
'DELETE'
],
allowHeaders: [
'Content-Type'
],
credentials: true
};

//middlewares
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan("common"));
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
app.use(cors(corsConfig));

app.get("/api/v1", (req, res) => {
res.send("<h1>Test...All Up & Running!</h1>");
});

app.use("/api/v1/auth", authRoutes);

app.listen(PORT, () => {
console.log(`Server Listening on Port ${PORT}`);
connectToMongoDB();
});
32 changes: 32 additions & 0 deletions backend/models/user.model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import mongoose from "mongoose";

const userSchema = new mongoose.Schema({
name: {
type: String,
min: 2,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
min: 6,
required: true
},
mobileNo: {
type: String,
max: 10,
min: 10,
required: true
},
role: {
type: String,
enum: ["Coach", "Member", "Parent", "Administrator", "Participant"],
required: true
}
}, { timestamps: true });

const User = mongoose.model("User", userSchema);
export default User;
Loading

0 comments on commit d1a67bd

Please sign in to comment.