auth in backend and frontend

This commit is contained in:
echo committed 2025-03-24 02:32:57 +01:00
1 parent 39d2698f28
commit 9857acd4c1
65 files changed
+1632 -3923

No files matched your search

+67
View File
@@ -0,0 +1,67 @@
import {
Body,
Controller,
Post,
UseGuards,
Request,
UnauthorizedException,
HttpCode,
HttpStatus,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { LocalAuthGuard, JwtAuthGuard } from './guards';
import { LoginDto, RegisterDto, RefreshTokenDto } from './dto/auth.dto';
import { User } from '@mono/auth-core';
interface RequestWithUser {
user: User;
}
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@Post('register')
async register(@Body() registerDto: RegisterDto) {
const user = await this.authService.createUser(
registerDto.email,
registerDto.password,
registerDto.name,
);
const tokens = await this.authService.generateTokens(user);
return {
user,
...tokens,
};
}
@UseGuards(LocalAuthGuard)
@Post('login')
@HttpCode(HttpStatus.OK)
async login(@Request() req: RequestWithUser, @Body() _loginDto: LoginDto) {
const tokens = await this.authService.generateTokens(req.user);
return {
user: req.user,
...tokens,
};
}
@Post('refresh')
@HttpCode(HttpStatus.OK)
async refresh(@Body() { refreshToken }: RefreshTokenDto) {
try {
const tokens = await this.authService.refreshTokens(refreshToken);
return tokens;
} catch (error) {
throw new UnauthorizedException('Invalid refresh token');
}
}
@UseGuards(JwtAuthGuard)
@Post('logout')
@HttpCode(HttpStatus.OK)
async logout(@Body() { refreshToken }: RefreshTokenDto) {
await this.authService.logout(refreshToken);
return { message: 'Logged out successfully' };
}
}
+2
View File
@@ -4,6 +4,7 @@ import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { JwtStrategy } from './strategies/jwt.strategy';
import { LocalStrategy } from './strategies/local.strategy';
import { AuthController } from './auth.controller';
export interface AuthModuleOptions {
jwtSecret: string;
@@ -22,6 +23,7 @@ export class AuthModule {
signOptions: { expiresIn: options.jwtExpiresIn || '1h' },
}),
],
controllers: [AuthController],
providers: [
AuthService,
LocalStrategy,
+119 -3
View File
@@ -1,12 +1,54 @@
import { Injectable } from '@nestjs/common';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { User, AuthTokens } from '@mono/auth-core';
import { prisma } from '@mono/database';
import * as bcrypt from 'bcryptjs';
type UserWithPassword = User & { password: string };
interface SessionWithUser {
id: string;
userId: string;
token: string;
expiresAt: Date;
user: {
id: string;
email: string;
name: string | null;
password: string;
};
}
@Injectable()
export class AuthService {
constructor(private jwtService: JwtService) {}
async validateUser(email: string, password: string): Promise<User> {
const user = await prisma.user.findUnique({
where: { email },
select: {
id: true,
email: true,
password: true,
name: true,
}
});
if (!user) {
throw new UnauthorizedException('Invalid credentials');
}
const isPasswordValid = await this.validatePassword(password, user.password);
if (!isPasswordValid) {
throw new UnauthorizedException('Invalid credentials');
}
const { password: _, ...result } = user;
return {
...result,
name: result.name || undefined,
};
}
async validatePassword(password: string, hashedPassword: string): Promise<boolean> {
return bcrypt.compare(password, hashedPassword);
}
@@ -15,16 +57,90 @@ export class AuthService {
return bcrypt.hash(password, 10);
}
async createUser(email: string, password: string, name?: string): Promise<User> {
const existingUser = await prisma.user.findUnique({ where: { email } });
if (existingUser) {
throw new UnauthorizedException('Email already exists');
}
const hashedPassword = await this.hashPassword(password);
const user = await prisma.user.create({
data: {
email,
password: hashedPassword,
name: name || null,
},
select: {
id: true,
email: true,
name: true,
},
});
return {
...user,
name: user.name || undefined,
};
}
async generateTokens(user: User): Promise<AuthTokens> {
const payload = { sub: user.id, email: user.email };
const accessToken = this.jwtService.sign(payload);
const refreshToken = this.jwtService.sign(payload, { expiresIn: '7d' });
// Store refresh token in sessions table
await prisma.session.create({
data: {
userId: user.id,
token: refreshToken,
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7 days
},
});
return {
accessToken: this.jwtService.sign(payload),
refreshToken: this.jwtService.sign(payload, { expiresIn: '7d' }),
accessToken,
refreshToken,
};
}
async verifyToken(token: string): Promise<any> {
return this.jwtService.verify(token);
}
async refreshTokens(refreshToken: string): Promise<AuthTokens> {
const session = await prisma.session.findUnique({
where: { token: refreshToken },
include: {
user: {
select: {
id: true,
email: true,
name: true,
password: true,
}
}
}
});
if (!session || session.expiresAt < new Date()) {
throw new UnauthorizedException('Invalid refresh token');
}
// Delete the old session
await prisma.session.delete({ where: { id: session.id } });
// Convert null to undefined for name and remove password
const { password: _, ...userWithoutPassword } = session.user;
const user: User = {
...userWithoutPassword,
name: userWithoutPassword.name || undefined,
};
// Generate new tokens
return this.generateTokens(user);
}
async logout(refreshToken: string): Promise<void> {
await prisma.session.delete({ where: { token: refreshToken } });
}
}
+28
View File
@@ -0,0 +1,28 @@
import { IsEmail, IsString, MinLength, IsOptional } from 'class-validator';
export class LoginDto {
@IsEmail()
email!: string;
@IsString()
@MinLength(6)
password!: string;
}
export class RegisterDto {
@IsEmail()
email!: string;
@IsString()
@MinLength(6)
password!: string;
@IsString()
@IsOptional()
name?: string;
}
export class RefreshTokenDto {
@IsString()
refreshToken!: string;
}
+2
View File
@@ -0,0 +1,2 @@
export * from './jwt-auth.guard';
export * from './local-auth.guard';
@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {}
@@ -1,10 +1,11 @@
import { Injectable, Inject } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { prisma } from '@mono/database';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(@Inject('JWT_SECRET') jwtSecret: string) {
constructor(@Inject('JWT_SECRET') private jwtSecret: string) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
@@ -13,6 +14,14 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
}
async validate(payload: any) {
return { id: payload.sub, email: payload.email };
const user = await prisma.user.findUnique({
where: { id: payload.sub },
select: {
id: true,
email: true,
name: true,
},
});
return user;
}
}
@@ -1,15 +1,21 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { AuthService } from '../auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor() {
super({ usernameField: 'email' });
constructor(private authService: AuthService) {
super({
usernameField: 'email',
});
}
async validate(email: string, password: string): Promise<any> {
// This method should be overridden in the implementing application
throw new UnauthorizedException('Strategy not implemented');
async validate(email: string, password: string) {
const user = await this.authService.validateUser(email, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}