refactor: organize source web and tests by business module
This commit is contained in:
1 parent
9854d2d5c2
commit
2aed328774
113 files changed
+189
-183
No files matched your search
@@ -1,32 +0,0 @@
|
||||
const fs=require('node:fs');
|
||||
const path=require('node:path');
|
||||
const crypto=require('node:crypto');
|
||||
const {DatabaseSync}=require('node:sqlite');
|
||||
const DAY=86400000;
|
||||
const SESSION_MS=30*DAY;
|
||||
const digest=token=>crypto.createHash('sha256').update(token).digest('hex');
|
||||
class SessionStore {
|
||||
constructor(dir){
|
||||
fs.mkdirSync(dir,{recursive:true});this.db=new DatabaseSync(path.join(dir,'auth.sqlite'));
|
||||
this.db.exec('PRAGMA busy_timeout=5000; CREATE TABLE IF NOT EXISTS sessions(hash TEXT PRIMARY KEY,userId TEXT NOT NULL,expires INTEGER NOT NULL,renewedAt INTEGER NOT NULL);');
|
||||
}
|
||||
issue(userId,now=Date.now()){
|
||||
this.db.prepare('DELETE FROM sessions WHERE expires<=?').run(now);
|
||||
this.db.exec('DELETE FROM sessions WHERE hash IN (SELECT hash FROM sessions ORDER BY renewedAt DESC LIMIT -1 OFFSET 999)');
|
||||
const token=crypto.randomBytes(32).toString('hex'),expires=now+SESSION_MS;
|
||||
this.db.prepare('INSERT INTO sessions(hash,userId,expires,renewedAt) VALUES(?,?,?,?)').run(digest(token),userId,expires,now);
|
||||
return {token,expires};
|
||||
}
|
||||
lookup(token,now=Date.now()){
|
||||
if(typeof token!=='string' || !/^[a-f0-9]{64}$/.test(token))return null;
|
||||
const hash=digest(token),row=this.db.prepare('SELECT userId,expires,renewedAt FROM sessions WHERE hash=?').get(hash);
|
||||
if(!row)return null;
|
||||
if(row.expires<=now){this.db.prepare('DELETE FROM sessions WHERE hash=?').run(hash);return null;}
|
||||
const renewed=now-row.renewedAt>=DAY;
|
||||
if(renewed){row.expires=now+SESSION_MS;this.db.prepare('UPDATE sessions SET expires=?,renewedAt=? WHERE hash=?').run(row.expires,now,hash);}
|
||||
return {userId:row.userId,expires:row.expires,renewed};
|
||||
}
|
||||
revoke(token){if(typeof token==='string' && /^[a-f0-9]{64}$/.test(token))this.db.prepare('DELETE FROM sessions WHERE hash=?').run(digest(token));}
|
||||
close(){if(this.db){this.db.close();this.db=null;}}
|
||||
}
|
||||
module.exports={SessionStore,SESSION_MS};
|
||||
Reference in new issue
Block a user