From 7edce8ba9ee93b0e6cd50e218a146a61b619e289 Mon Sep 17 00:00:00 2001 From: Gabriel Matte Date: Tue, 8 Oct 2024 15:45:18 -0400 Subject: [PATCH] centralise login/register methods --- server/auth/auth-manager.js | 22 ++++--- .../auth/modules/passport-providers/oauth.js | 22 +++---- .../auth/modules/passport-providers/oidc.js | 19 +++--- server/auth/modules/passportjs.js | 9 ++- server/auth/modules/simpleauth.js | 59 +++++++------------ server/models/users.js | 9 +-- 6 files changed, 61 insertions(+), 79 deletions(-) diff --git a/server/auth/auth-manager.js b/server/auth/auth-manager.js index 306c07f..f44ef04 100644 --- a/server/auth/auth-manager.js +++ b/server/auth/auth-manager.js @@ -1,5 +1,8 @@ const fs = require('fs'); const AuthConfig = require('../config/auth.js'); +const jwt = require('../middleware/jwtToken.js'); +const emailer = require('../config/email.js'); +const model = require('../models/users.js'); class AuthManager{ constructor(expressapp,configs=null){ @@ -39,18 +42,19 @@ class AuthManager{ } } - async login(userInfos){ - // TODO global user login method - console.log(userInfos) + async login(userInfo,req,res,next){ + const tokenToSave = jwt.create(userInfo.email, userInfo._id); + res.redirect(`/oauth/callback?user=${tokenToSave}`); + console.info(`L'utilisateur '${userInfo.name}' vient de se connecter`) } async register(userInfos){ - // TODO global user register method - console.log(userInfos) - } - - async logout(){ - // TODO global user logout method + if (!userInfos.email || !userInfos.password) { + throw new AppError(MISSING_REQUIRED_PARAMETER); + } + const user = await model.register(userInfos); + emailer.registerConfirmation(user.email) + return user } } diff --git a/server/auth/modules/passport-providers/oauth.js b/server/auth/modules/passport-providers/oauth.js index 5490eb9..5730eb5 100644 --- a/server/auth/modules/passport-providers/oauth.js +++ b/server/auth/modules/passport-providers/oauth.js @@ -39,22 +39,26 @@ class PassportOAuth { if(hasNestedValue(userInfo,provider.OAUTH_ROLE_TEACHER_VALUE)) received_user.roles.push('teacher') if(hasNestedValue(userInfo,provider.OAUTH_ROLE_STUDENT_VALUE)) received_user.roles.push('student') - const user_association = await authUserAssoc.find_user_association(self.auth_name._id,received_user.auth_id) + const user_association = await authUserAssoc.find_user_association(self.auth_name,received_user.auth_id) - let user_account = null + let user_account if(user_association){ user_account = await users.getById(user_association.user_id) } else { let user_id = await users.getId(received_user.email) - user_account = user_id ? await users.getById(user_id) : await users.register(received_user.email,"") + if(user_id){ + user_account = await users.getById(user_id); + } else { + received_user.password = users.generatePassword() + user_account = await self.passportjs.register(received_user) + } await authUserAssoc.link(self.auth_name,received_user.auth_id,user_account._id) } user_account.name = received_user.name user_account.roles = received_user.roles await users.editUser(user_account) - self.passportjs.authenticate(user_account) // Store the tokens in the session req.session.oauth2Tokens = { @@ -83,15 +87,7 @@ class PassportOAuth { }, (req, res) => { if (req.user) { - // res.json(req.user) - - //const redirectUrl = `http://your-frontend-url.com/oauth/callback?user=${encodeURIComponent(req.user)}`; - //res.redirect(redirectUrl); - - const tokenToSave = jwt.create(req.user.email, req.user._id); - res.redirect('/oauth/callback?user=' + tokenToSave); - - console.info(`L'utilisateur '${req.user.name}' vient de se connecter`) + self.passportjs.authenticate(req.user,req,res) } else { res.status(401).json({ error: "L'authentification a échoué" }); } diff --git a/server/auth/modules/passport-providers/oidc.js b/server/auth/modules/passport-providers/oidc.js index 6a10d9d..65997b9 100644 --- a/server/auth/modules/passport-providers/oidc.js +++ b/server/auth/modules/passport-providers/oidc.js @@ -49,22 +49,26 @@ class PassportOpenIDConnect { if(hasNestedValue(profile,provider.OIDC_ROLE_TEACHER_VALUE)) received_user.roles.push('teacher') if(hasNestedValue(profile,provider.OIDC_ROLE_STUDENT_VALUE)) received_user.roles.push('student') - const user_association = await authUserAssoc.find_user_association(self.auth_name._id,received_user.auth_id) + const user_association = await authUserAssoc.find_user_association(self.auth_name,received_user.auth_id) - let user_account = null + let user_account if(user_association){ user_account = await users.getById(user_association.user_id) } else { let user_id = await users.getId(received_user.email) - user_account = user_id ? await users.getById(user_id) : await users.register(received_user.email,"") + if(user_id){ + user_account = await users.getById(user_id); + } else { + received_user.password = users.generatePassword() + user_account = await self.passportjs.register(received_user) + } await authUserAssoc.link(self.auth_name,received_user.auth_id,user_account._id) } user_account.name = received_user.name user_account.roles = received_user.roles await users.editUser(user_account) - self.passportjs.authenticate(user_account) return done(null, user_account); } catch (error) { @@ -84,12 +88,7 @@ class PassportOpenIDConnect { }, (req, res) => { if (req.user) { - // res.json(req.user) - - const tokenToSave = jwt.create(req.user.email, req.user._id); - res.redirect('/oauth/callback?user=' + tokenToSave); - - console.info(`L'utilisateur '${req.user.name}' vient de se connecter`) + self.passportjs.authenticate(req.user,req,res) } else { res.status(401).json({ error: "L'authentification a échoué" }); } diff --git a/server/auth/modules/passportjs.js b/server/auth/modules/passportjs.js index 865f66b..3d2d46c 100644 --- a/server/auth/modules/passportjs.js +++ b/server/auth/modules/passportjs.js @@ -1,4 +1,3 @@ -const fs = require('fs'); var passport = require('passport') var authprovider = require('../../models/authProvider') @@ -51,12 +50,12 @@ class PassportJs{ } - register(userinfos){ - return this.authmanager.register(userinfos) + register(userInfos){ + return this.authmanager.register(userInfos) } - authenticate(userinfos){ - return this.authmanager.login(userinfos) + authenticate(userInfo,req,res,next){ + return this.authmanager.login(userInfo,req,res,next) } } diff --git a/server/auth/modules/simpleauth.js b/server/auth/modules/simpleauth.js index 56f7b93..1911b91 100644 --- a/server/auth/modules/simpleauth.js +++ b/server/auth/modules/simpleauth.js @@ -1,53 +1,41 @@ -var authprovider = require('../../models/authProvider.js') -var users = require('../../app.js') const jwt = require('../../middleware/jwtToken.js'); const emailer = require('../../config/email.js'); const model = require('../../models/users.js'); const AppError = require('../../middleware/AppError.js'); -const { MISSING_REQUIRED_PARAMETER, LOGIN_CREDENTIALS_ERROR, GENERATE_PASSWORD_ERROR, UPDATE_PASSWORD_ERROR, DELETE_USER_ERROR } = require('../../constants/errorCodes'); +const { MISSING_REQUIRED_PARAMETER, LOGIN_CREDENTIALS_ERROR, GENERATE_PASSWORD_ERROR, UPDATE_PASSWORD_ERROR } = require('../../constants/errorCodes'); +const { name } = require('../../models/authProvider.js'); class SimpleAuth{ constructor(authmanager,settings){ this.authmanager = authmanager this.providers = settings - this.endpoint = "/api/users" + this.endpoint = "/api/auth/simple-auth" } async registerAuth(expressapp){ try{ - expressapp.post(`${this.endpoint}/register`, this.register); - expressapp.post(`${this.endpoint}/login`, this.authenticate); - expressapp.post(`${this.endpoint}/reset-password`, this.resetPassword); - expressapp.post(`${this.endpoint}/change-password`, jwt.authenticate, this.changePassword); + expressapp.post(`${this.endpoint}/register`, (req,res,next)=>this.register(this,req,res)); + expressapp.post(`${this.endpoint}/login`, (req,res,next)=>this.authenticate(this,req,res)); + expressapp.post(`${this.endpoint}/reset-password`, (req,res,next)=>this.resetPassword(this,req,res)); + expressapp.post(`${this.endpoint}/change-password`, jwt.authenticate, (req,res,next)=>this.changePassword(this,req,res)); } catch(error){ console.error(`La connexion ${name} de type ${provider.type} n'as pu être chargé.`) } } - async register(req, res, next) { - try { - const { email, password } = req.body; - - if (!email || !password) { - throw new AppError(MISSING_REQUIRED_PARAMETER); - } - - await model.register(email, password); - - emailer.registerConfirmation(email) - - return res.status(200).json({ - message: 'Utilisateur créé avec succès.' - }); - - } - catch (error) { - return next(error); + async register(self,req, res) { + let userInfos = { + name: req.body.email, + email: req.body.email, + password: req.body.password, } + let user = await self.authmanager.register(userInfos) + if(user) res.redirect("/") + else res.redirect("/login") } - async authenticate(req, res, next) { + async authenticate(self,req, res, next) { try { const { email, password } = req.body; @@ -60,21 +48,16 @@ class SimpleAuth{ if (!user) { throw new AppError(LOGIN_CREDENTIALS_ERROR); } - - const token = jwt.create(user.email, user._id); - - return res.status(200).json({ - token: token, - id: user.email - }); - + + user.name = user.name ?? user.email + self.authmanager.login(user,req,res,next) } catch (error) { return next(error); } } - async resetPassword(req, res, next) { + async resetPassword(self,req, res, next) { try { const { email } = req.body; @@ -99,7 +82,7 @@ class SimpleAuth{ } } - async changePassword(req, res, next) { + async changePassword(self,req, res, next) { try { const { email, oldPassword, newPassword } = req.body; diff --git a/server/models/users.js b/server/models/users.js index 58a1563..8e16758 100644 --- a/server/models/users.js +++ b/server/models/users.js @@ -18,21 +18,22 @@ class Users { return await bcrypt.compare(password, hash); } - async register(email, password) { + async register(userInfos) { await db.connect(); const conn = db.getConnection(); const userCollection = conn.collection("users"); - const existingUser = await userCollection.findOne({ email: email }); + const existingUser = await userCollection.findOne({ email: userInfos.email }); if (existingUser) { throw new AppError(USER_ALREADY_EXISTS); } const newUser = { - email: email, - password: await this.hashPassword(password), + name: userInfos.name ?? userInfos.email, + email: userInfos.email, + password: await this.hashPassword(userInfos.password), created_at: new Date(), };