mirror of
https://gitlab.com/little-lines/backend.git
synced 2025-07-07 13:31:05 +00:00
Merge branch 'main' of https://gitlab.com/openKMITL/little-lines/backend
This commit is contained in:
commit
3ff828d9c9
4 changed files with 135 additions and 2 deletions
|
@ -1,7 +1,12 @@
|
|||
const asyncHandler = require('express-async-handler');
|
||||
const sendToken = require('../utils/jwtToken');
|
||||
|
||||
const user = require('../models/user');
|
||||
|
||||
const axios = require('axios');
|
||||
const dotenv = require("dotenv").config();
|
||||
|
||||
|
||||
// Get all users => GET api/users
|
||||
const getAllUser = asyncHandler(async (req, res) => {
|
||||
const users = await user.find();
|
||||
|
@ -109,4 +114,56 @@ const logoutUser = asyncHandler(async (req, res) => {
|
|||
});
|
||||
});
|
||||
|
||||
module.exports = { getAllUser, createUser, deleteUser, updateUser, loginUser, logoutUser };
|
||||
const googleAuth = asyncHandler(async (req, res) => {
|
||||
try {
|
||||
// get the code from frontend
|
||||
const code = req.headers.authorization;
|
||||
console.log('Authorization Code:', code);
|
||||
|
||||
// Exchange the authorization code for an access token
|
||||
const response = await axios.post(
|
||||
'https://oauth2.googleapis.com/token',
|
||||
{
|
||||
code,
|
||||
client_id: process.env.CLIENT_ID,
|
||||
client_secret: process.env.CLIENT_SECRET,
|
||||
redirect_uri: 'postmessage',
|
||||
grant_type: 'authorization_code'
|
||||
}
|
||||
);
|
||||
const accessToken = response.data.access_token;
|
||||
console.log('Access Token:', accessToken);
|
||||
|
||||
// Fetch user details using the access token
|
||||
const userResponse = await axios.get(
|
||||
'https://www.googleapis.com/oauth2/v3/userinfo',
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`
|
||||
}
|
||||
}
|
||||
);
|
||||
const userDetails = userResponse.data;
|
||||
console.log('User Details:', userDetails);
|
||||
|
||||
// Process user details and perform necessary actions
|
||||
|
||||
const users = await user.findOne({ email: userDetails.email })
|
||||
|
||||
if(!users){
|
||||
const newUser = await user.create({
|
||||
username: userDetails.name,
|
||||
password:"nothing",
|
||||
email: userDetails.email,
|
||||
isGoogleAccount: userDetails.email_verified
|
||||
});
|
||||
}
|
||||
|
||||
sendToken(users, 200, res);
|
||||
} catch (error) {
|
||||
console.error('Error saving code:', error);
|
||||
res.status(500).json({ message: 'Failed to save code' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = { getAllUser, createUser, deleteUser, updateUser, loginUser, logoutUser , googleAuth};
|
Loading…
Add table
Add a link
Reference in a new issue