Files
mtusi2026lab2/src/Auth/auth.service.ts
T

183 lines
6.1 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { createHash, randomBytes } from 'node:crypto';
import { TextDecoder } from 'node:util';
import { PrismaService } from '../prisma/prisma.service';
import { Prisma } from '../generated/prisma/client';
import { UserService } from '../User/user.service';
import type { User } from '../User/user.schema';
import { invalidRequest, uuid, uuidPattern } from '../common/validation';
import { ApiException } from '../common/exceptions/api.exception';
import { AuthException } from './auth.exception';
import { PasswordService, validPassword } from './password.service';
import type { Session } from './auth.schema';
export interface ChatAccess {
chatId: string;
userId: string;
messagesEpoch: string;
}
@Injectable()
export class AuthService {
private readonly ttlSeconds: number;
constructor(
private readonly prisma: PrismaService,
private readonly users: UserService,
private readonly passwords: PasswordService,
) {
this.ttlSeconds = Number(process.env.SESSION_TTL_SECONDS ?? 3600);
if (
!Number.isSafeInteger(this.ttlSeconds) ||
this.ttlSeconds <= 0 ||
Number.isNaN(new Date(Date.now() + this.ttlSeconds * 1000).getTime())
) {
throw new Error(
'SESSION_TTL_SECONDS must be a positive integer representing a valid expiry',
);
}
}
async login(authorization: unknown, body: unknown): Promise<Session> {
const { username, password } = this.basicCredentials(authorization);
const user = await this.prisma.user.findUnique({ where: { username } });
const verified = await this.passwords.verify(
password,
user?.passwordHash ?? null,
);
if (!user || !verified) throw new AuthException('Basic');
if (body !== undefined)
return invalidRequest('Вход через Basic не принимает тело запроса');
const token = randomBytes(32).toString('base64url');
const session = await this.prisma.session.create({
data: {
userId: user.id,
tokenHash: this.tokenHash(token),
expiresAt: new Date(Date.now() + this.ttlSeconds * 1000),
},
});
return {
token,
token_type: 'Bearer',
expires_at: session.expiresAt.toISOString(),
user: this.users.serialize(user),
};
}
async authenticate(
authorization: unknown,
chatId?: unknown,
): Promise<{
user: User;
sessionId: string;
chatsEpoch: string;
chatAccess?: ChatAccess;
}> {
const match =
typeof authorization === 'string' &&
/^Bearer +([A-Za-z0-9_-]{43})$/i.exec(authorization);
if (!match) throw new AuthException('Bearer');
const requestedChat =
typeof chatId === 'string' && uuidPattern.test(chatId)
? chatId.toLowerCase()
: null;
const [session] = await this.prisma.$queryRaw<
{
id: string;
userId: string;
username: string;
displayName: string;
createdAt: Date;
chatsEpoch: bigint;
chatId: string | null;
messagesEpoch: bigint | null;
}[]
>(Prisma.sql`
SELECT s.id, s.user_id AS "userId", u.chats_epoch AS "chatsEpoch",
u.username, u.display_name AS "displayName", u.created_at AS "createdAt",
${
chatId === undefined
? Prisma.sql`NULL::uuid AS "chatId", NULL::bigint AS "messagesEpoch"`
: Prisma.sql`c.id AS "chatId", COALESCE((SELECT SUM(e.epoch) FROM "public"."chat_message_epochs" AS e WHERE e.chat_id = c.id), 0)::bigint AS "messagesEpoch"`
}
FROM sessions AS s
JOIN users AS u ON u.id = s.user_id
${
chatId === undefined
? Prisma.empty
: Prisma.sql`
LEFT JOIN chat_members AS cm
ON cm.user_id = s.user_id AND cm.chat_id = ${requestedChat}::uuid
LEFT JOIN chats AS c ON c.id = cm.chat_id
`
}
WHERE s.token_hash = ${this.tokenHash(match[1])}
AND s.revoked_at IS NULL AND s.expires_at > ${new Date()}
LIMIT 1
`);
if (!session) throw new AuthException('Bearer');
if (chatId !== undefined) {
uuid(chatId, 'chat_id');
if (session.chatId === null || session.messagesEpoch === null)
throw new ApiException(404, 'not_found', 'Объект не найден');
}
return {
user: this.users.serialize({ ...session, id: session.userId }),
sessionId: session.id,
chatsEpoch: session.chatsEpoch.toString(),
chatAccess:
session.chatId !== null && session.messagesEpoch !== null
? {
chatId: session.chatId,
userId: session.userId,
messagesEpoch: session.messagesEpoch.toString(),
}
: undefined,
};
}
async logout(sessionId: string): Promise<void> {
const now = new Date();
const result = await this.prisma.session.updateMany({
where: { id: sessionId, revokedAt: null, expiresAt: { gt: now } },
data: { revokedAt: now },
});
if (result.count !== 1) throw new AuthException('Bearer');
}
private tokenHash(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
private basicCredentials(authorization: unknown): {
username: string;
password: string;
} {
const match =
typeof authorization === 'string' &&
/^Basic +([A-Za-z0-9+/]+={0,2})$/i.exec(authorization);
if (!match) throw new AuthException('Basic');
try {
const bytes = Buffer.from(match[1], 'base64');
if (
bytes.toString('base64').replace(/=+$/, '') !==
match[1].replace(/=+$/, '')
)
throw new AuthException('Basic');
const value = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
const colon = value.indexOf(':');
const username = value.slice(0, colon);
const password = value.slice(colon + 1);
if (
colon < 0 ||
!/^[a-z0-9_]{3,32}$/.test(username) ||
!validPassword(password)
)
throw new AuthException('Basic');
return { username, password };
} catch {
throw new AuthException('Basic');
}
}
}