EvalueTonSavoir/server/auth/auth-manager.js

61 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-09-24 17:24:32 -04:00
const fs = require('fs');
2024-09-28 17:08:11 -04:00
const AuthConfig = require('../config/auth.js');
2024-10-08 15:45:18 -04:00
const jwt = require('../middleware/jwtToken.js');
const emailer = require('../config/email.js');
const model = require('../models/users.js');
2024-09-24 17:24:32 -04:00
class AuthManager{
2024-09-28 17:08:11 -04:00
constructor(expressapp,configs=null){
2024-09-24 17:24:32 -04:00
this.modules = []
this.app = expressapp
2024-09-28 17:08:11 -04:00
this.configs = configs ?? (new AuthConfig()).loadConfig()
this.addModules()
this.registerAuths()
}
async addModules(){
for(const module in this.configs.auth){
this.addModule(module)
}
2024-09-24 17:24:32 -04:00
}
async addModule(name){
const modulePath = `${process.cwd()}/auth/modules/${name}.js`
if(fs.existsSync(modulePath)){
const Module = require(modulePath);
2024-09-28 17:08:11 -04:00
this.modules.push(new Module(this,this.configs.auth[name]));
console.info(`Module d'authentification '${name}' ajouté`)
} else{
console.error(`Le module d'authentification ${name} n'as pas été chargé car il est introuvable`)
2024-09-24 17:24:32 -04:00
}
}
async registerAuths(){
for(const module of this.modules){
2024-09-28 17:08:11 -04:00
try{
module.registerAuth(this.app)
} catch(error){
console.error(`L'enregistrement du module ${module} a échoué.`)
}
2024-09-24 17:24:32 -04:00
}
}
2024-10-08 15:45:18 -04:00
async login(userInfo,req,res,next){
2024-10-19 13:13:16 -04:00
const tokenToSave = jwt.create(userInfo.email, userInfo._id,userInfo.roles);
res.redirect(`/auth/callback?user=${tokenToSave}&username=${userInfo.name}`);
2024-10-08 15:45:18 -04:00
console.info(`L'utilisateur '${userInfo.name}' vient de se connecter`)
2024-09-24 17:24:32 -04:00
}
async register(userInfos){
2024-10-08 15:45:18 -04:00
if (!userInfos.email || !userInfos.password) {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
const user = await model.register(userInfos);
emailer.registerConfirmation(user.email)
return user
2024-09-24 17:24:32 -04:00
}
}
module.exports = AuthManager;