Add ISAC user operations and access roles
This commit is contained in:
@@ -43,15 +43,23 @@ export async function createSession(cookies: Cookies, userId: string): Promise<v
|
||||
});
|
||||
}
|
||||
|
||||
export async function recordLogin(userId: string | null, provider: 'password' | 'discord', succeeded: boolean): Promise<void> {
|
||||
const database = await getDatabase();
|
||||
await (await database.prepare('INSERT INTO login_events(id,user_id,provider,succeeded,created_at) VALUES(?,?,?,?,?)'))
|
||||
.run(randomUUID(), userId, provider, succeeded ? 1 : 0, new Date().toISOString());
|
||||
}
|
||||
|
||||
export async function getSessionUser(cookies: Cookies): Promise<AuthUser | null> {
|
||||
const token = cookies.get(COOKIE_NAME);
|
||||
if (!token) return null;
|
||||
|
||||
const database = await getDatabase();
|
||||
const statement = await database.prepare(`
|
||||
SELECT users.id, users.username, users.role, users.discord_id
|
||||
SELECT users.id, users.username, users.role, users.discord_id,
|
||||
user_status.last_active_at,user_status.blocked_at,user_status.banned_until
|
||||
FROM sessions
|
||||
JOIN users ON users.id = sessions.user_id
|
||||
LEFT JOIN user_status ON user_status.user_id=users.id
|
||||
WHERE sessions.token_hash = ? AND sessions.expires_at > ?
|
||||
`);
|
||||
const user = await statement.get(hashToken(token), new Date().toISOString());
|
||||
@@ -60,6 +68,18 @@ export async function getSessionUser(cookies: Cookies): Promise<AuthUser | null>
|
||||
cookies.delete(COOKIE_NAME, { path: '/' });
|
||||
return null;
|
||||
}
|
||||
const now = new Date();
|
||||
const banned = typeof user.banned_until === 'string' && new Date(user.banned_until) > now;
|
||||
if (user.blocked_at || banned) {
|
||||
await (await database.prepare('DELETE FROM sessions WHERE token_hash=?')).run(hashToken(token));
|
||||
cookies.delete(COOKIE_NAME, { path: '/' });
|
||||
return null;
|
||||
}
|
||||
if (!user.last_active_at || now.getTime() - new Date(String(user.last_active_at)).getTime() > 5 * 60 * 1000) {
|
||||
await (await database.prepare(`INSERT INTO user_status(user_id,last_active_at,updated_at) VALUES(?,?,?)
|
||||
ON CONFLICT(user_id) DO UPDATE SET last_active_at=excluded.last_active_at,updated_at=excluded.updated_at`))
|
||||
.run(String(user.id), now.toISOString(), now.toISOString());
|
||||
}
|
||||
|
||||
return {
|
||||
id: String(user.id),
|
||||
|
||||
Reference in New Issue
Block a user