batman
This commit is contained in:
@@ -0,0 +1,189 @@
|
||||
import { Injectable, UnauthorizedException, ConflictException, NotFoundException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import * as crypto from 'crypto';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { TOKEN_EXPIRY_DAYS, TOKEN_BYTE_LENGTH, TOKEN_PREFIX_LENGTH } from '@kooltab/shared';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private prisma: PrismaService,
|
||||
private jwtService: JwtService,
|
||||
private auditService: AuditService,
|
||||
) {}
|
||||
|
||||
async login(email: string, password: string) {
|
||||
const user = await this.prisma.clientUser.findUnique({ where: { email } });
|
||||
if (!user) {
|
||||
throw new UnauthorizedException({ code: 'invalid_credentials', message: 'Invalid email or password' });
|
||||
}
|
||||
|
||||
const valid = await bcrypt.compare(password, user.passwordHash);
|
||||
if (!valid) {
|
||||
throw new UnauthorizedException({ code: 'invalid_credentials', message: 'Invalid email or password' });
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, email: user.email, role: user.role, venueId: user.venueId };
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
|
||||
const refreshToken = crypto.randomBytes(32).toString('hex');
|
||||
const refreshHash = crypto.createHash('sha256').update(refreshToken).digest('hex');
|
||||
const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 30 days
|
||||
|
||||
await this.prisma.refreshToken.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
tokenHash: refreshHash,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.role,
|
||||
venueId: user.venueId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async refresh(refreshToken: string) {
|
||||
const hash = crypto.createHash('sha256').update(refreshToken).digest('hex');
|
||||
const stored = await this.prisma.refreshToken.findUnique({ where: { tokenHash: hash } });
|
||||
|
||||
if (!stored || stored.revokedAt || stored.expiresAt < new Date()) {
|
||||
throw new UnauthorizedException({ code: 'invalid_refresh_token', message: 'Invalid or expired refresh token' });
|
||||
}
|
||||
|
||||
const user = await this.prisma.clientUser.findUnique({ where: { id: stored.userId } });
|
||||
if (!user) {
|
||||
throw new UnauthorizedException({ code: 'user_not_found', message: 'User not found' });
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, email: user.email, role: user.role, venueId: user.venueId };
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
|
||||
const newRefreshToken = crypto.randomBytes(32).toString('hex');
|
||||
const newHash = crypto.createHash('sha256').update(newRefreshToken).digest('hex');
|
||||
const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
|
||||
|
||||
await this.prisma.refreshToken.update({
|
||||
where: { id: stored.id },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
|
||||
await this.prisma.refreshToken.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
tokenHash: newHash,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken: newRefreshToken,
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.role,
|
||||
venueId: user.venueId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async logout(refreshToken: string) {
|
||||
const hash = crypto.createHash('sha256').update(refreshToken).digest('hex');
|
||||
await this.prisma.refreshToken.updateMany({
|
||||
where: { tokenHash: hash, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
async generateDeviceToken(): Promise<{ rawToken: string; hash: string; prefix: string; expiresAt: Date }> {
|
||||
const rawBytes = crypto.randomBytes(TOKEN_BYTE_LENGTH);
|
||||
const rawToken = 'dev_' + rawBytes.toString('base64url');
|
||||
const hash = crypto.createHash('sha256').update(rawToken).digest('hex');
|
||||
const prefix = rawToken.substring(0, TOKEN_PREFIX_LENGTH);
|
||||
const expiresAt = new Date(Date.now() + TOKEN_EXPIRY_DAYS * 24 * 60 * 60 * 1000);
|
||||
|
||||
return { rawToken, hash, prefix, expiresAt };
|
||||
}
|
||||
|
||||
async registerDevice(venueId: string, name: string, registrationCode: string) {
|
||||
const code = await this.prisma.registrationCode.findUnique({ where: { code: registrationCode } });
|
||||
|
||||
if (!code || code.usedAt || code.expiresAt < new Date()) {
|
||||
throw new UnauthorizedException({ code: 'invalid_registration_code', message: 'Invalid or expired registration code' });
|
||||
}
|
||||
|
||||
if (code.venueId !== venueId) {
|
||||
throw new UnauthorizedException({ code: 'venue_mismatch', message: 'Registration code does not match venue' });
|
||||
}
|
||||
|
||||
const { rawToken, hash, prefix, expiresAt } = await this.generateDeviceToken();
|
||||
const deviceId = uuidv4();
|
||||
|
||||
await this.prisma.device.create({
|
||||
data: {
|
||||
id: deviceId,
|
||||
venueId,
|
||||
name,
|
||||
tokenHash: hash,
|
||||
tokenPrefix: prefix,
|
||||
tokenExpiresAt: expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
await this.prisma.registrationCode.update({
|
||||
where: { id: code.id },
|
||||
data: { usedAt: new Date() },
|
||||
});
|
||||
|
||||
await this.auditService.log(venueId, 'device', deviceId, 'device_registered', { deviceName: name });
|
||||
|
||||
return { deviceId, token: rawToken, tokenExpiresAt: expiresAt };
|
||||
}
|
||||
|
||||
async validateDevice(deviceId: string, token: string): Promise<any> {
|
||||
const hash = crypto.createHash('sha256').update(token).digest('hex');
|
||||
const device = await this.prisma.device.findUnique({ where: { id: deviceId } });
|
||||
|
||||
if (!device || device.tokenHash !== hash) {
|
||||
throw new UnauthorizedException({ code: 'invalid_device_token', message: 'Invalid device token' });
|
||||
}
|
||||
|
||||
if (device.revokedAt) {
|
||||
throw new UnauthorizedException({ code: 'device_revoked', message: 'Device has been revoked' });
|
||||
}
|
||||
|
||||
if (device.tokenExpiresAt < new Date()) {
|
||||
throw new UnauthorizedException({ code: 'token_expired', message: 'Device token has expired' });
|
||||
}
|
||||
|
||||
return device;
|
||||
}
|
||||
|
||||
async generateRegistrationCode(venueId: string): Promise<{ code: string; expiresAt: Date }> {
|
||||
const code = crypto.randomBytes(3).toString('hex').toUpperCase();
|
||||
const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes
|
||||
|
||||
await this.prisma.registrationCode.create({
|
||||
data: {
|
||||
venueId,
|
||||
code,
|
||||
expiresAt,
|
||||
},
|
||||
});
|
||||
|
||||
return { code, expiresAt };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user