|
| 1 | +import { |
| 2 | + Injectable, |
| 3 | + ConflictException, |
| 4 | + UnauthorizedException, |
| 5 | +} from '@nestjs/common'; |
| 6 | +import { JwtService } from '@nestjs/jwt'; |
| 7 | +import { ConfigService } from '@nestjs/config'; |
| 8 | +import * as bcrypt from 'bcrypt'; |
| 9 | +import { UsersService } from '../users/users.service'; |
| 10 | +import { RegisterDto } from './dto/register.dto'; |
| 11 | +import { LoginDto } from './dto/login.dto'; |
| 12 | +import { User } from '../users/user.entity'; |
| 13 | + |
| 14 | +export interface AuthTokens { |
| 15 | + accessToken: string; |
| 16 | + refreshToken: string; |
| 17 | +} |
| 18 | + |
| 19 | +@Injectable() |
| 20 | +export class AuthService { |
| 21 | + constructor( |
| 22 | + private readonly usersService: UsersService, |
| 23 | + private readonly jwtService: JwtService, |
| 24 | + private readonly configService: ConfigService, |
| 25 | + ) {} |
| 26 | + |
| 27 | + async register(dto: RegisterDto): Promise<{ user: User; tokens: AuthTokens }> { |
| 28 | + const existing = await this.usersService.findByEmail(dto.email); |
| 29 | + if (existing) { |
| 30 | + throw new ConflictException('An account with this email already exists'); |
| 31 | + } |
| 32 | + |
| 33 | + const hashedPassword = await bcrypt.hash(dto.password, 12); |
| 34 | + const user = await this.usersService.create({ |
| 35 | + email: dto.email.toLowerCase(), |
| 36 | + firstName: dto.firstName, |
| 37 | + lastName: dto.lastName, |
| 38 | + password: hashedPassword, |
| 39 | + }); |
| 40 | + |
| 41 | + const tokens = await this.signTokens(user); |
| 42 | + await this.storeRefreshToken(user.id, tokens.refreshToken); |
| 43 | + |
| 44 | + return { user, tokens }; |
| 45 | + } |
| 46 | + |
| 47 | + async login(dto: LoginDto): Promise<{ user: User; tokens: AuthTokens }> { |
| 48 | + const user = await this.usersService.findByEmail(dto.email.toLowerCase()); |
| 49 | + if (!user) { |
| 50 | + throw new UnauthorizedException('Invalid email or password'); |
| 51 | + } |
| 52 | + |
| 53 | + const passwordMatch = await bcrypt.compare(dto.password, user.password); |
| 54 | + if (!passwordMatch) { |
| 55 | + throw new UnauthorizedException('Invalid email or password'); |
| 56 | + } |
| 57 | + |
| 58 | + const tokens = await this.signTokens(user); |
| 59 | + await this.storeRefreshToken(user.id, tokens.refreshToken); |
| 60 | + |
| 61 | + return { user, tokens }; |
| 62 | + } |
| 63 | + |
| 64 | + async refresh(userId: string, incomingRefreshToken: string): Promise<AuthTokens> { |
| 65 | + const user = await this.usersService.findByRefreshToken(userId); |
| 66 | + if (!user || !user.refreshToken) { |
| 67 | + throw new UnauthorizedException('Session expired. Please log in again.'); |
| 68 | + } |
| 69 | + |
| 70 | + const tokenMatch = await bcrypt.compare(incomingRefreshToken, user.refreshToken); |
| 71 | + if (!tokenMatch) { |
| 72 | + throw new UnauthorizedException('Session expired. Please log in again.'); |
| 73 | + } |
| 74 | + |
| 75 | + const tokens = await this.signTokens(user); |
| 76 | + await this.storeRefreshToken(user.id, tokens.refreshToken); |
| 77 | + return tokens; |
| 78 | + } |
| 79 | + |
| 80 | + async logout(userId: string): Promise<void> { |
| 81 | + await this.usersService.updateRefreshToken(userId, null); |
| 82 | + } |
| 83 | + |
| 84 | + private async signTokens(user: User): Promise<AuthTokens> { |
| 85 | + const payload = { sub: user.id, email: user.email, role: user.role }; |
| 86 | + |
| 87 | + const [accessToken, refreshToken] = await Promise.all([ |
| 88 | + this.jwtService.signAsync(payload, { |
| 89 | + secret: this.configService.get<string>('JWT_SECRET', 'change-me-in-env'), |
| 90 | + expiresIn: '15m', |
| 91 | + }), |
| 92 | + this.jwtService.signAsync(payload, { |
| 93 | + secret: this.configService.get<string>('JWT_REFRESH_SECRET', 'change-me-refresh'), |
| 94 | + expiresIn: '7d', |
| 95 | + }), |
| 96 | + ]); |
| 97 | + |
| 98 | + return { accessToken, refreshToken }; |
| 99 | + } |
| 100 | + |
| 101 | + private async storeRefreshToken(userId: string, token: string): Promise<void> { |
| 102 | + const hashed = await bcrypt.hash(token, 10); |
| 103 | + await this.usersService.updateRefreshToken(userId, hashed); |
| 104 | + } |
| 105 | +} |
0 commit comments