Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import { Inject, Injectable } from '@nestjs/common';import { randomBytes } from 'node:crypto';import type { PublicUser, Session, User } from '../domain/models';import { SESSION_REPOSITORY, USER_REPOSITORY, type SessionRepository, type UserRepository,} from '../domain/ports';import { sessionTtlDays } from './auth.constants';
// Owns the server-side session lifecycle. The cookie carries only the opaque// id; everything authoritative (which user, expiry) lives in the sessions// table, so a logout or expiry can't be undone client-side.@Injectable()export class SessionService { constructor( @Inject(SESSION_REPOSITORY) private readonly sessions: SessionRepository, @Inject(USER_REPOSITORY) private readonly users: UserRepository, ) {}
// Strip the hash before anything leaves the service boundary. static toPublicUser(u: User): PublicUser { return { id: u.id, username: u.username, role: u.role, provider: u.provider }; }
async create(userId: string): Promise<Session> { // 256 bits of entropy, url-safe. Opportunistically prune expired rows so // the table doesn't grow without bound (no separate cron needed). await this.sessions.deleteExpired(); const id = randomBytes(32).toString('base64url'); const expires = new Date(Date.now() + sessionTtlDays() * 24 * 60 * 60 * 1000); // UTC text format, matching the stored expires_at. const expiresAt = expires.toISOString().replace('T', ' ').slice(0, 19); return this.sessions.create({ id, user_id: userId, expires_at: expiresAt }); }
// Resolves a session id to its user, or null if the session is missing, // expired, or its user was deleted. async resolve(sessionId: string | undefined): Promise<PublicUser | null> { if (!sessionId) return null; const session = await this.sessions.findValid(sessionId); if (!session) return null; const user = await this.users.findById(session.user_id); return user ? SessionService.toPublicUser(user) : null; }
async destroy(sessionId: string | undefined): Promise<void> { if (sessionId) await this.sessions.delete(sessionId); }
// Revoke every session of a user - after a password change or an operator // reset, any session in unknown hands must die with the old password. async destroyAllForUser(userId: string): Promise<void> { await this.sessions.deleteByUser(userId); }}