centralise login/register methods

This commit is contained in:
Gabriel Matte 2024-10-08 15:45:18 -04:00
parent 3d219d068f
commit 7edce8ba9e
6 changed files with 61 additions and 79 deletions

View file

@ -1,5 +1,8 @@
const fs = require('fs'); const fs = require('fs');
const AuthConfig = require('../config/auth.js'); 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{ class AuthManager{
constructor(expressapp,configs=null){ constructor(expressapp,configs=null){
@ -39,18 +42,19 @@ class AuthManager{
} }
} }
async login(userInfos){ async login(userInfo,req,res,next){
// TODO global user login method const tokenToSave = jwt.create(userInfo.email, userInfo._id);
console.log(userInfos) res.redirect(`/oauth/callback?user=${tokenToSave}`);
console.info(`L'utilisateur '${userInfo.name}' vient de se connecter`)
} }
async register(userInfos){ async register(userInfos){
// TODO global user register method if (!userInfos.email || !userInfos.password) {
console.log(userInfos) throw new AppError(MISSING_REQUIRED_PARAMETER);
} }
const user = await model.register(userInfos);
async logout(){ emailer.registerConfirmation(user.email)
// TODO global user logout method return user
} }
} }

View file

@ -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_TEACHER_VALUE)) received_user.roles.push('teacher')
if(hasNestedValue(userInfo,provider.OAUTH_ROLE_STUDENT_VALUE)) received_user.roles.push('student') 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){ if(user_association){
user_account = await users.getById(user_association.user_id) user_account = await users.getById(user_association.user_id)
} }
else { else {
let user_id = await users.getId(received_user.email) 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) await authUserAssoc.link(self.auth_name,received_user.auth_id,user_account._id)
} }
user_account.name = received_user.name user_account.name = received_user.name
user_account.roles = received_user.roles user_account.roles = received_user.roles
await users.editUser(user_account) await users.editUser(user_account)
self.passportjs.authenticate(user_account)
// Store the tokens in the session // Store the tokens in the session
req.session.oauth2Tokens = { req.session.oauth2Tokens = {
@ -83,15 +87,7 @@ class PassportOAuth {
}, },
(req, res) => { (req, res) => {
if (req.user) { if (req.user) {
// res.json(req.user) self.passportjs.authenticate(req.user,req,res)
//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`)
} else { } else {
res.status(401).json({ error: "L'authentification a échoué" }); res.status(401).json({ error: "L'authentification a échoué" });
} }

View file

@ -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_TEACHER_VALUE)) received_user.roles.push('teacher')
if(hasNestedValue(profile,provider.OIDC_ROLE_STUDENT_VALUE)) received_user.roles.push('student') 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){ if(user_association){
user_account = await users.getById(user_association.user_id) user_account = await users.getById(user_association.user_id)
} }
else { else {
let user_id = await users.getId(received_user.email) 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) await authUserAssoc.link(self.auth_name,received_user.auth_id,user_account._id)
} }
user_account.name = received_user.name user_account.name = received_user.name
user_account.roles = received_user.roles user_account.roles = received_user.roles
await users.editUser(user_account) await users.editUser(user_account)
self.passportjs.authenticate(user_account)
return done(null, user_account); return done(null, user_account);
} catch (error) { } catch (error) {
@ -84,12 +88,7 @@ class PassportOpenIDConnect {
}, },
(req, res) => { (req, res) => {
if (req.user) { if (req.user) {
// res.json(req.user) self.passportjs.authenticate(req.user,req,res)
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`)
} else { } else {
res.status(401).json({ error: "L'authentification a échoué" }); res.status(401).json({ error: "L'authentification a échoué" });
} }

View file

@ -1,4 +1,3 @@
const fs = require('fs');
var passport = require('passport') var passport = require('passport')
var authprovider = require('../../models/authProvider') var authprovider = require('../../models/authProvider')
@ -51,12 +50,12 @@ class PassportJs{
} }
register(userinfos){ register(userInfos){
return this.authmanager.register(userinfos) return this.authmanager.register(userInfos)
} }
authenticate(userinfos){ authenticate(userInfo,req,res,next){
return this.authmanager.login(userinfos) return this.authmanager.login(userInfo,req,res,next)
} }
} }

View file

@ -1,53 +1,41 @@
var authprovider = require('../../models/authProvider.js')
var users = require('../../app.js')
const jwt = require('../../middleware/jwtToken.js'); const jwt = require('../../middleware/jwtToken.js');
const emailer = require('../../config/email.js'); const emailer = require('../../config/email.js');
const model = require('../../models/users.js'); const model = require('../../models/users.js');
const AppError = require('../../middleware/AppError.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{ class SimpleAuth{
constructor(authmanager,settings){ constructor(authmanager,settings){
this.authmanager = authmanager this.authmanager = authmanager
this.providers = settings this.providers = settings
this.endpoint = "/api/users" this.endpoint = "/api/auth/simple-auth"
} }
async registerAuth(expressapp){ async registerAuth(expressapp){
try{ try{
expressapp.post(`${this.endpoint}/register`, this.register); expressapp.post(`${this.endpoint}/register`, (req,res,next)=>this.register(this,req,res));
expressapp.post(`${this.endpoint}/login`, this.authenticate); expressapp.post(`${this.endpoint}/login`, (req,res,next)=>this.authenticate(this,req,res));
expressapp.post(`${this.endpoint}/reset-password`, this.resetPassword); expressapp.post(`${this.endpoint}/reset-password`, (req,res,next)=>this.resetPassword(this,req,res));
expressapp.post(`${this.endpoint}/change-password`, jwt.authenticate, this.changePassword); expressapp.post(`${this.endpoint}/change-password`, jwt.authenticate, (req,res,next)=>this.changePassword(this,req,res));
} catch(error){ } catch(error){
console.error(`La connexion ${name} de type ${provider.type} n'as pu être chargé.`) console.error(`La connexion ${name} de type ${provider.type} n'as pu être chargé.`)
} }
} }
async register(req, res, next) { async register(self,req, res) {
try { let userInfos = {
const { email, password } = req.body; name: req.body.email,
email: req.body.email,
if (!email || !password) { password: req.body.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);
} }
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 { try {
const { email, password } = req.body; const { email, password } = req.body;
@ -61,20 +49,15 @@ class SimpleAuth{
throw new AppError(LOGIN_CREDENTIALS_ERROR); throw new AppError(LOGIN_CREDENTIALS_ERROR);
} }
const token = jwt.create(user.email, user._id); user.name = user.name ?? user.email
self.authmanager.login(user,req,res,next)
return res.status(200).json({
token: token,
id: user.email
});
} }
catch (error) { catch (error) {
return next(error); return next(error);
} }
} }
async resetPassword(req, res, next) { async resetPassword(self,req, res, next) {
try { try {
const { email } = req.body; const { email } = req.body;
@ -99,7 +82,7 @@ class SimpleAuth{
} }
} }
async changePassword(req, res, next) { async changePassword(self,req, res, next) {
try { try {
const { email, oldPassword, newPassword } = req.body; const { email, oldPassword, newPassword } = req.body;

View file

@ -18,21 +18,22 @@ class Users {
return await bcrypt.compare(password, hash); return await bcrypt.compare(password, hash);
} }
async register(email, password) { async register(userInfos) {
await db.connect(); await db.connect();
const conn = db.getConnection(); const conn = db.getConnection();
const userCollection = conn.collection("users"); const userCollection = conn.collection("users");
const existingUser = await userCollection.findOne({ email: email }); const existingUser = await userCollection.findOne({ email: userInfos.email });
if (existingUser) { if (existingUser) {
throw new AppError(USER_ALREADY_EXISTS); throw new AppError(USER_ALREADY_EXISTS);
} }
const newUser = { const newUser = {
email: email, name: userInfos.name ?? userInfos.email,
password: await this.hashPassword(password), email: userInfos.email,
password: await this.hashPassword(userInfos.password),
created_at: new Date(), created_at: new Date(),
}; };