Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat#82: Google Authentication, Login and Signup backend #241

Merged
merged 2 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
VITE_BACKEND_URL=http://localhost:7000/api/v1
VITE_GOOGLE_CLIENT_ID=430349486581-523p7m5mlh1mjjne5h3h3q2t0hd0okeg.apps.googleusercontent.com
3 changes: 2 additions & 1 deletion config.env
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@

./package-lock.json
./package-lock.json

76 changes: 61 additions & 15 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@
"@mui/icons-material": "^5.15.18",
"@mui/material": "^5.15.17",
"@react-icons/all-files": "^4.1.0",
"@react-oauth/google": "^0.12.1",
"@stripe/react-stripe-js": "^2.7.1",
"@stripe/stripe-js": "^3.4.0",
"axios": "^1.6.7",
"axios": "^1.7.2",
"dotenv": "^16.4.5",
"jwt-decode": "^4.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^5.2.1",
Expand Down
2 changes: 1 addition & 1 deletion server/config/DBconnect.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ const connectDB = async () => {
}
};

export default connectDB;
export {connectDB};
48 changes: 48 additions & 0 deletions server/controllers/loginController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import {userModel} from "../models/userModel.js";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";

const postLogin=async (req,res)=>{
try {
if(req.body.authType===true){
const user=await userModel.findOne({ email: req.body.email });
if(!user){
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const pass= req.body.password;
req.body.password = hashedPassword;
const data = await userModel.create({
email:req.body.email,
password:req.body.password
});
req.body.password=pass
}
}
const currentUser = await userModel.findOne({ email: req.body.email });
if (currentUser) {
const isPasswordCorrect = bcrypt.compareSync(
req.body.password,
currentUser.password
);
if (isPasswordCorrect) {
const token = jwt.sign(
{ id: currentUser._id },
process.env.JWT_SECRET
);
res.cookie('jwttoken', token, {
httpOnly: false,
maxAge: 24 * 60 * 60 * 10
});
return res.status(200).json({ message: "Login Successfully"});
} else {
return res.status(400).json({ message: "Password is Incorrect" });
}
}
else {
return res.status(400).json({ message: "User not found" });
}
}
catch (err) {
res.status(500).json({ message:"server error" });
}
}
export { postLogin };
17 changes: 17 additions & 0 deletions server/controllers/signupController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import {userModel} from "../models/userModel.js";
import bcrypt from "bcrypt";
const postRegister = async (req, res, next) => {
try {
const hashedPassword = await bcrypt.hash(req.body.password, 10);
req.body.password = hashedPassword;
const data = await userModel.create({
...req.body,
});
console.log(data);
res.status(201).json({message: "User Created"});
} catch (err) {
// console.log(err);
res.status(400).json({ message: err.message });
}
};
export { postRegister };
13 changes: 8 additions & 5 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ import dotenv from 'dotenv';
import cors from 'cors';
import morgan from 'morgan';
import { MensRouter } from './routes/mens-route.js';
import connectDB from './config/DBconnect.js';
import {connectDB} from './config/DBconnect.js';
import { WomensRouter } from './routes/womens-route.js';
import {LoginRouter} from "./routes/loginRoute.js";
import {SignupRouter} from './routes/signupRoute.js';
import { KidsRouter } from './routes/kids-route.js';
import StripeRouter from './routes/Stripe-route.js';
import cookieParser from 'cookie-parser';

const app=express();

Expand All @@ -15,7 +18,7 @@ dotenv.config({path:'./config.env'})
connectDB();

app.use(express.json());

app.use(cookieParser());
app.use(morgan('dev'))

app.use(cors({
Expand All @@ -24,14 +27,14 @@ app.use(cors({
credentials:true,
}))


app.use(express.urlencoded({extended:false}));

app.use('/api/v1/mens',MensRouter);
app.use('/api/v1/womens',WomensRouter);
app.use('/api/v1/kids',KidsRouter);
app.use('/api/v1/signup',SignupRouter);
app.use('/api/v1/login',LoginRouter);
app.use('/api',StripeRouter);


const port=process.env.PORT||7000;
app.listen(port,()=>{
console.log(`Server is running on port ${port}`);
Expand Down
22 changes: 22 additions & 0 deletions server/middlewares/auth-helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import jwt from "jsonwebtoken";
import { userModel } from "../models/userModel.js";
import bcrypt from "bcrypt";

const authLogin = async (req, res, next) => {
try {
const token = req.cookies.jwttoken;
const verifyToken = jwt.verify(token, process.env.jwt_secret);
const user = await userModel.findOne({ _id: verifyToken.id });
if(!user){
return res.status(401).json({ message: "User not found" });
}
else{
next();
}
}
catch (err) {
res.status(501).json({ message: "Internal Server Error" });
}
}

export { authLogin };
37 changes: 37 additions & 0 deletions server/models/userModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Importing mongoose
import mongoose from "mongoose";
// Importing email-validator
import emailValidator from "email-validator";
// Importing bcrypt
import bcrypt from "bcrypt";
const userSchema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true,
validate: function () {
return emailValidator.validate(this.email);
},
},
password: {
type: String,
required: true,
minLength: 6,
}
});
userSchema.pre("save", async function (next) {
try {
const existingUser = await userModel.findOne({ email: this.email });
if (existingUser) {
const err = new Error("Email already exists");
err.status = 400;
return next(err);
}

next();
} catch (error) {
next(error);
}
});
const userModel = new mongoose.model("user", userSchema);
export { userModel };
3 changes: 3 additions & 0 deletions server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.1.1",
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"email-validator": "^2.0.4",
"express": "^4.19.2",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.3.5",
Expand Down
8 changes: 8 additions & 0 deletions server/routes/loginRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import {postLogin} from '../controllers/loginController.js';
import express from "express"
import { authLogin } from '../middlewares/auth-helper.js';
const LoginRouter = express.Router();

LoginRouter.route('/').post(postLogin);

export {LoginRouter};
8 changes: 8 additions & 0 deletions server/routes/signupRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { postRegister } from "../controllers/signupController.js";

import express from "express";
const SignupRouter = express.Router();

SignupRouter.route("/").post(postRegister);

export { SignupRouter };
Loading