This commit is contained in:
STEINNI
2025-09-11 20:39:52 +00:00
parent d4243685b6
commit 8cfa7f41e4
3 changed files with 155 additions and 26 deletions
+70
View File
@@ -0,0 +1,70 @@
import mysql from 'mysql2/promise'
export class MySQLClient {
constructor(db, kal = 0) {
this.db = db
this.lastInsertedId = -1
this.kalIntervalId = null
if(kal > 0){
this.kalIntervalId = setInterval(() => {
this.db.query('SELECT 1')
}, 1000 * kal);
}
}
async close(){
if(this.db) await this.db.end()
if(this.kalIntervalId) clearInterval(this.kalIntervalId)
this.db = null
}
escape(x) { return(mysql.escape(x)) }
async execute(query, values = []){
if(!this.db) return([])
if(query.search(RegExp('(^|;) *(INSERT|REPLACE) +INTO','i'))>-1) this.lastInsertedId = -1
const [result] = await this.db.execute(query, values)
if('insertId' in result) {
this.lastInsertedId = result.insertId
}
return(result)
}
/* Makes a multi-line VALUES insert, with values for an array of objects { columns:value }
*/
async InsertObjectsStatement(table, rows){
this.lastInsertedId = -1
if((!this.db) || (rows.length==0)) return([])
const keys = Object.keys(rows[0]).map((key) => `\`${key}\``).join(', ')
let valuesArr = []
for(let row of rows){
valuesArr.push(Object.values(row))
}
const query = `INSERT INTO ${table} (${keys}) VALUES ?`
const [result] = await this.db.query(query, [valuesArr]) //Note the wierd array in array of arrays, also, query, not execute
if('insertId' in result) {
this.lastInsertedId = result.insertId
}
return(result)
}
/* Makes a multi-line VALUES insert, with values for an array of objects { columns:value }
*/
async ReplaceObjectsStatement(table, rows){
this.lastInsertedId = -1
if((!this.db) || (rows.length==0)) return([])
const keys = Object.keys(rows[0]).map((key) => `\`${key}\``).join(', ')
let valuesArr = []
for(let row of rows){
valuesArr.push(Object.values(row))
}
const query = `REPLACE INTO ${table} (${keys}) VALUES ?`
const [result] = await this.db.query(query, [valuesArr]) //Note the wierd array in array of arrays, also, query, not execute
if('insertId' in result) {
this.lastInsertedId = result.insertId
}
return(result)
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
const argon2 = require('argon2') import argon2 from 'argon2'
// --- Hash a password (e.g. at signup) --- // --- Hash a password (e.g. at signup) ---
export async function hashPassword(plainPassword) { export async function hashPassword(plainPassword) {
+90 -31
View File
@@ -1,20 +1,20 @@
import { Utils } from './helpers/utils.js' import { Utils } from './helpers/utils.js'
import { verifyPassword } from './helpers/pwd.js'
import { MySQLClient } from './helpers/mysqlClient.js'
export class P42ApiEndpoints{ export class P42ApiEndpoints{
constructor(app, db) { constructor(app, db) {
this.db = db this.db = new MySQLClient(db, 60)
this.app = app this.app = app
this.userinfos = null this.userinfos = null
this.utils = new Utils() this.utils = new Utils()
this.registerPaths() this.registerPaths()
setInterval(() => {
this.db.query('SELECT 1');
}, 5000);
} }
registerPaths(){ registerPaths(){
this.app.get('/hw', this.hw.bind(this)) this.app.get('/hw', this.hw.bind(this))
this.app.get('/checkauth', this.checkauth.bind(this)) this.app.get('/checkauth', this.checkauth.bind(this))
this.app.post('/login', this.login.bind(this)) this.app.post('/login', this.login.bind(this))
this.app.get('/logout', this.logout.bind(this))
} }
@@ -47,17 +47,6 @@ export class P42ApiEndpoints{
this.ok(req, res, {}) this.ok(req, res, {})
} }
getSession(req, res) {
if((!req.session.userinfo) || (!req.session.userinfo.isAuthenticated)) {
this.userinfos = null
return(false)
} else {
req.session.touch()
this.userinfos = req.session.userinfo
return(true)
}
}
hasRole(roles) { hasRole(roles) {
if(!this.userinfos.userRoles) return(false) if(!this.userinfos.userRoles) return(false)
if(typeof(roles) == 'string') return(this.userinfos.userRoles.includes(roles)) if(typeof(roles) == 'string') return(this.userinfos.userRoles.includes(roles))
@@ -74,51 +63,121 @@ export class P42ApiEndpoints{
this.ok(req, res, {hello:'world'}) this.ok(req, res, {hello:'world'})
} }
async checkauth(req, res) async checkauth(req, res) {
if(req.session.userInfos && req.session.userInfos.authenticated && req.session.userInfos.username) { if(req.session.userInfos && req.session.authenticated && req.session.userInfos.username) {
this.ok(req, res, { this.ok(req, res, {
authenticated: true, authenticated: true,
userInfos: this.userInfos, userInfos: this.userInfos,
trials: 3,
locked: false,
}) })
} else { } else {
let trials = 3
let locked = false
if(req.session.userInfos && req.session.userInfos.username) {
const results = await this.db.execute('SELECT usr_trials, usr_locked FROM users WHERE usr_name = ?', [req.session.userInfos.username])
if(results.length==1){
trials = results[0].usr_trials
locked = results[0].usr_locked
}
}
this.ok(req, res, { this.ok(req, res, {
authenticated: false, authenticated: false,
userInfos: null, userInfos: null,
trials: trials,
locked: locked,
}) })
} }
} }
async setUserLock(username, locked, trials){
await this.db.execute('UPDATE users SET usr_locked=?, usr_trials=? WHERE usr_name = ?', [locked, trials, username])
}
async login(req, res) { async login(req, res) {
let [isValid, payload, errors] = this.utils.validateMapObject(req.body, { let [isValid, payload, errors] = this.utils.validateMapObject(req.body, {
username: ((val, obj) => (typeof(val)=='string') && (val.length>3) ), username: ((val, obj) => (typeof(val)=='string') && (val.length>0) && (/^\w+$/.test(val))),
passwd: ((val, obj) => (typeof(val)=='string') && (val.length>7) ), passwd: ((val, obj) => (typeof(val)=='string') && (val.length>0) ),
},{ },{
'username': 'username', 'username': 'username',
'passwd': 'passwd', 'passwd': 'passwd',
}) })
if((!isValid)){ if((!isValid)){
this.err(req, res, `Invalid request', 'Invalid login payload:: ${errors}`, 401) this.err(req, res, `Invalid request`, `Invalid login payload:: ${errors}`, 401)
return return
} }
if((payload.username=='toto') && (payload.passwd=='azertyuiop')){ const results = await this.db.execute('SELECT * FROM users WHERE usr_name = ?', [payload.username])
req.session.userInfos = { let pwdCheck = false
authenticated: true, let userLocked = false
username: payload.username, let trials = 3
roles: ['admin'] if(results.length==1){
} userLocked = results[0].usr_locked
this.ok(req, res, { trials = results[0].usr_trials
authenticated: true, if(userLocked) {
userInfos: req.session.userInfos,
})
} else {
this.ok(req, res, { this.ok(req, res, {
authenticated: false, authenticated: false,
userInfos: null, userInfos: null,
trials: 0,
locked: true,
})
return
}
}
pwdCheck = await verifyPassword(payload.passwd, results[0].usr_pwd)
if(pwdCheck){
req.session.userInfos = {
username: payload.username,
roles: ['admin'],
}
req.session.authenticated = true
await this.setUserLock(payload.username, false, 3)
this.ok(req, res, {
authenticated: true,
userInfos: req.session.userInfos,
trials: 3,
locked: false,
})
} else {
let newtrials = (trials>0) ? trials-1 : 0
if(newtrials == 0){
await this.setUserLock(payload.username, true, 0)
this.ok(req, res, {
authenticated: false,
userInfos: null,
trials: 0,
locked: true,
})
return
} else {
await this.setUserLock(payload.username, false, newtrials)
}
req.session.authenticated = false
req.session.userInfos = null
this.ok(req, res, {
authenticated: false,
userInfos: null,
trials: newtrials,
locked: false,
}) })
} }
} }
async logout(req, res) {
if(req.session.userInfos && req.session.authenticated) {
req.session.authenticated = false
this.ok(req, res, {
authenticated: false,
userInfos: null,
trials: 3,
locked: false,
})
}
}
} }