2022-01-24 19:01:18 +01:00
|
|
|
import { Request, Response } from "express";
|
2022-01-23 14:54:40 +01:00
|
|
|
import { FindOneResult } from "monk";
|
|
|
|
import { db } from ".";
|
|
|
|
|
|
|
|
class Session {
|
|
|
|
user: string;
|
|
|
|
token: string;
|
|
|
|
nonce: string;
|
|
|
|
expires: number;
|
|
|
|
invalid: boolean;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param req
|
|
|
|
* @returns false if not authenticated, otherwise the (Revolt) user ID
|
|
|
|
*/
|
2022-01-24 19:01:18 +01:00
|
|
|
async function isAuthenticated(req: Request, res?: Response, send401?: boolean): Promise<string|false> {
|
2022-01-23 14:54:40 +01:00
|
|
|
const user = req.header('x-auth-user');
|
|
|
|
const token = req.header('x-auth-token');
|
|
|
|
|
|
|
|
if (!user || !token) return false;
|
|
|
|
|
|
|
|
const info = await getSessionInfo(user, token);
|
2022-01-24 19:01:18 +01:00
|
|
|
if (res && send401 && !info.valid) {
|
|
|
|
res.status(401).send({ error: 'Unauthorized' });
|
|
|
|
}
|
2022-01-23 14:54:40 +01:00
|
|
|
return info.valid ? user : false;
|
|
|
|
}
|
|
|
|
|
|
|
|
type SessionInfo = { exists: boolean, valid: boolean, nonce?: string }
|
|
|
|
|
|
|
|
async function getSessionInfo(user: string, token: string): Promise<SessionInfo> {
|
|
|
|
const session: FindOneResult<Session> = await db.get('sessions').findOne({ user, token });
|
|
|
|
|
|
|
|
return { exists: !!session, valid: !!(session && !session.invalid && session.expires > Date.now()), nonce: session?.nonce }
|
|
|
|
}
|
|
|
|
|
|
|
|
export { isAuthenticated, getSessionInfo }
|