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

Mohamed mahmoud/feat/google login #47

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
58 changes: 58 additions & 0 deletions backend/controllers/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import jwt from 'jsonwebtoken';
import User from '../models/User.js';
import asyncHandler from '../middleware/asyncHandler.js';
import { OAuth2Client } from 'google-auth-library';

const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);

// Login route
export const login = asyncHandler(async (req, res) => {
const { token } = req.body;
const ticket = await client.verifyIdToken({
idToken: token,
audience: process.env.GOOGLE_CLIENT_ID,
});
const payload = ticket.getPayload();
const { email, given_name, family_name, picture } = payload;

let user = await User.findOne({ email });

if (!user) {
// Creating new user with Google data
user = new User({
email,
firstName: given_name,
lastName: family_name,
picture: picture || null,
});
await user.save();
}

const accessToken = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, {
expiresIn: '6d',
});

res
.cookie('access_token', accessToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
})
.sendStatus(200);
});

// Get current user route
export const current_user = asyncHandler(async (req, res) => {
const token = req.cookies.access_token;
if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}

const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);

if (!user) {
return res.status(404).json({ error: 'User not found' });
}

res.json({ user });
});
26 changes: 26 additions & 0 deletions backend/middleware/authMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import jwt from 'jsonwebtoken';
import User from '../models/User';

const authMiddleware = async (req, res, next) => {
const token = req.cookies.access_token;

if (!token) {
return res.status(401).json({ error: 'Unauthorized - Token missing' });
}

try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(decoded.userId);

if (!user) {
return res.status(401).json({ error: 'Unauthorized - Invalid token' });
}

req.user = user;
next();
} catch (error) {
return res.status(401).json({ error: 'Unauthorized - Invalid token' });
}
};

export default authMiddleware;
29 changes: 29 additions & 0 deletions backend/models/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import mongoose from 'mongoose';

const Schema = mongoose.Schema;

const userSchema = new Schema({
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
picture: {
type: String,
required: false,
},
email: {
type: String,
required: true,
unique: true,
},
savedMovies: [{ type: String }],
savedQueries: [{ type: String }],
});

const User = mongoose.model('User', userSchema);

export default User;
Loading