const asyncHandler = require('express-async-handler'); const user = require('../models/user'); const sendToken = require('../utils/jwtToken'); 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(); res.status(200).json(users); }); // Create new user => POST api/users/create const createUser = asyncHandler(async (req, res) => { try { const { username, password, email, isGoogleAccount } = req.body; const newUser = await user.create({ username, password, email, isGoogleAccount }); // Respond with the newly created user res.status(201).json(newUser); } catch (err) { // Handle validation errors if (err.name === 'ValidationError') { console.error(err); return res.status(400).json({ error: err.message }); } console.error(err); res.status(500).json({ error: 'An error occurred while creating the user.' }); } }); // Delete user => api/users/delete/:id const deleteUser = asyncHandler(async (req, res) => { try { const userId = req.params.id; const deleteUserId = await user.findById(userId); if(!deleteUserId) { return res.status(404).send('User ID not found!'); } await user.findByIdAndDelete(userId); res.status(200).send({ message: `Deleted ${userId} from database` }); } catch(err) { console.log(err); } }); // Update user => api/users/update/:id const updateUser = asyncHandler(async (req, res) => { let users = await user.findById(req.params.id); if(!users) { return res.status(404).send('User not found!'); } users = await user.findByIdAndUpdate(req.params.id, req.body, { new: true, }) res.status(200).json(users) }); // Login user => api/users/login const loginUser = asyncHandler(async (req, res) => { try { const { email, password } = req.body; if(!email || !password) { return res.status(400).send('Please enter email & password'); } const users = await user.findOne({ email }).select('+password'); if(!users) { return res.status(400).send('Invalid Email'); } const isPasswordMatched = await users.comparePassword(password); if(!isPasswordMatched) { return res.status(401).send('Invalid Password'); } sendToken(users, 200, res); } catch(err){ console.log(err); } }); // Logout user => api/users/logout const logoutUser = asyncHandler(async (req, res) => { res.cookie('token', null, { expires: new Date(Date.now()), httpOnly: true }); res.status(200).json({ success: true, message: 'Logged out' }); }); 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};