Files
mtusi2026lab2/src/services/auth.service.ts
T
Антон Архипов f77e500ccf
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / application (pull_request) Canceled after 0s
[+] Completed lab 2
2026-11-16 16:01:24 +03:00

87 lines
3.5 KiB
TypeScript

import { createHash, randomBytes } from 'node:crypto';
import type { Session, User } from '../domain/models';
import { unauthorized } from '../errors/api-error';
import { env } from '../config/env';
import { db } from '../repositories/postgres';
import { passwordSchema, usernameSchema } from '../validation/schemas';
import { verifyPassword } from './password.service';
interface Account extends User {
password_hash: string;
}
export interface AuthenticatedSession {
user: User;
tokenHash: string;
}
const hashToken = (token: string): string =>
createHash('sha256').update(token, 'ascii').digest('hex');
function basicCredentials(authorization: string | undefined): { username: string; password: string } {
const encoded = /^Basic +([A-Za-z0-9+/]+={0,2})$/i.exec(authorization ?? '')?.[1];
if (!encoded || encoded.length > 800) throw unauthorized('Basic');
const bytes = Buffer.from(encoded, 'base64');
if (bytes.toString('base64') !== encoded) throw unauthorized('Basic');
let value: string;
try {
value = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
} catch {
throw unauthorized('Basic');
}
const separator = value.indexOf(':');
const username = value.slice(0, separator);
const password = value.slice(separator + 1);
if (separator < 0 || !usernameSchema.safeParse(username).success || !passwordSchema.safeParse(password).success) {
throw unauthorized('Basic');
}
return { username, password };
}
export async function createSession(authorization: string | undefined): Promise<Session> {
const { username, password } = basicCredentials(authorization);
const result = await db.query<Account>(
'SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1',
[username],
);
const account = result.rows[0];
if (!(await verifyPassword(password, account?.password_hash)) || !account) throw unauthorized('Basic');
const token = randomBytes(32).toString('base64url');
const { rows } = await db.query<{ expires_at: string }>(
`INSERT INTO sessions (token_hash, user_id, expires_at)
VALUES ($1, $2, clock_timestamp() + $3::int * interval '1 second') RETURNING expires_at`,
[hashToken(token), account.id, env.SESSION_TTL_SECONDS],
);
const session = rows[0];
if (!session) throw new Error('Session not returned');
const { id, display_name, created_at } = account;
return { token, token_type: 'Bearer', expires_at: session.expires_at,
user: { id, username, display_name, created_at } };
}
export async function requireSession(authorization: string | undefined): Promise<AuthenticatedSession> {
const token = /^Bearer +([A-Za-z0-9_-]{43})$/i.exec(authorization ?? '')?.[1];
if (!token) throw unauthorized('Bearer');
const tokenHash = hashToken(token);
const { rows } = await db.query<User>(
`SELECT u.id, u.username, u.display_name, u.created_at
FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.token_hash = $1 AND s.expires_at > clock_timestamp()`,
[tokenHash],
);
const user = rows[0];
if (!user) throw unauthorized('Bearer');
return { user, tokenHash };
}
export async function revokeSession(session: AuthenticatedSession): Promise<void> {
const result = await db.query(
'DELETE FROM sessions WHERE token_hash = $1 AND expires_at > clock_timestamp()',
[session.tokenHash],
);
if (result.rowCount !== 1) throw unauthorized('Bearer');
}