Denied access to login & register while logged in. Fixed regular user auth for requiring admin.

This commit is contained in:
Tom
2025-06-18 13:50:38 +00:00
parent 6b010f66ba
commit 6ac9a2f1ec
11 changed files with 65 additions and 70 deletions

View File

@ -74,7 +74,8 @@ import { BullModule } from '@nestjs/bullmq';
BooksModule,
ProvidersModule,
SeriesModule,
LibraryModule
LibraryModule,
ConfigModule,
],
controllers: [AppController],
providers: [AppService, UsersService],

View File

@ -1,5 +1,4 @@
import { Controller, Request, Post, UseGuards, Body, Res, Delete, Patch } from '@nestjs/common';
import { LoginAuthGuard } from './guards/login-auth.guard';
import { Controller, Request, Post, UseGuards, Body, Res, Delete, Patch, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
import { UsersService } from 'src/users/users.service';
import { RegisterUserDto } from './dto/register-user.dto';
@ -21,7 +20,7 @@ export class AuthController {
private logger: PinoLogger,
) { }
@UseGuards(LoginAuthGuard)
@UseGuards(OfflineGuard)
@Post('login')
async login(
@Request() req,
@ -30,7 +29,7 @@ export class AuthController {
) {
let data: AuthenticationDto | null;
try {
data = await this.auth.login(req.user, body.remember_me);
data = await this.auth.login(body);
if (!data.access_token || body.remember_me && (!data.refresh_token || !data.refresh_exp)) {
response.statusCode = 500;
return {
@ -47,6 +46,14 @@ export class AuthController {
error: err,
});
if (err instanceof UnauthorizedException) {
response.statusCode = 401;
return {
success: false,
error_message: 'Invalid credentials.',
};
}
response.statusCode = 500;
return {
success: false,
@ -224,7 +231,11 @@ export class AuthController {
}
try {
data = await this.auth.login(user, false);
data = await this.auth.login({
user_login: body.user_login,
password: body.password,
remember_me: false,
});
if (!data.access_token) {
this.logger.error({
class: AuthController.name,
@ -250,6 +261,15 @@ export class AuthController {
error: err,
});
// This should never happen...
if (err instanceof UnauthorizedException) {
response.statusCode = 401;
return {
success: false,
error_message: 'Invalid credentials.',
};
}
response.statusCode = 500;
return {
success: false,
@ -264,13 +284,6 @@ export class AuthController {
sameSite: 'strict',
});
response.cookie('Refresh', data.refresh_token, {
httpOnly: true,
secure: true,
expires: new Date(data.refresh_exp),
sameSite: 'strict',
});
return {
success: true,
};

View File

@ -2,7 +2,6 @@ import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { UsersModule } from 'src/users/users.module';
import { PassportModule } from '@nestjs/passport';
import { LoginStrategy } from './strategies/login.strategy';
import { AuthController } from './auth.controller';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
@ -37,7 +36,6 @@ import { JwtRefreshStrategy } from './strategies/jwt-refresh.strategy';
AuthService,
JwtStrategy,
JwtRefreshStrategy,
LoginStrategy,
],
controllers: [AuthController]
})

View File

@ -1,9 +1,11 @@
import { Injectable } from '@nestjs/common';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UserEntity } from 'src/users/entities/users.entity';
import { UsersService } from 'src/users/users.service';
import { AuthRefreshService } from './auth.refresh.service';
import { AuthAccessService } from './auth.access.service';
import { UUID } from 'crypto';
import { AuthenticationDto } from './dto/authentication.dto';
import { LoginDto } from './dto/login.dto';
@Injectable()
export class AuthService {
@ -15,10 +17,14 @@ export class AuthService {
async login(
user: UserEntity,
withRefresh: boolean
): Promise<AuthenticationDto> {
if (withRefresh) {
loginDetails: LoginDto
): Promise<AuthenticationDto | null> {
const user = await this.users.findOne(loginDetails);
if (!user) {
throw new UnauthorizedException();
}
if (loginDetails.remember_me) {
return this.renew(user);
}
@ -47,7 +53,7 @@ export class AuthService {
username: string,
password: string,
): Promise<UserEntity | null> {
return await this.users.findOne({ username, password });
return await this.users.findOne({ user_login: username, password, remember_me: false });
}
async verify(

View File

@ -1,6 +1,18 @@
import { IsBoolean, IsOptional } from 'class-validator';
import { IsBoolean, IsNotEmpty, IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
export class LoginDto {
@IsString()
@IsNotEmpty()
@MinLength(3)
@MaxLength(24)
readonly user_login: string;
@IsString()
@IsNotEmpty()
@MinLength(8)
@MaxLength(128)
readonly password: string;
@IsBoolean()
@IsOptional()
readonly remember_me: boolean;

View File

@ -5,7 +5,7 @@ import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAccessGuard extends AuthGuard('jwt-access') {
handleRequest(err, user, info) {
if (err || !user || !user.isAdmin) {
if (err || !user) {
throw err || new UnauthorizedException();
}
return user;

View File

@ -1,6 +0,0 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class LoginAuthGuard extends AuthGuard('login') { }

View File

@ -1,13 +1,13 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { ForbiddenException, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class OfflineGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest();
return !request.user;
export class OfflineGuard extends AuthGuard('jwt-access') {
handleRequest(err, user, info) {
if (err || user) {
throw err || new ForbiddenException();
}
return null;
}
}

View File

@ -1,20 +0,0 @@
import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from '../auth.service';
@Injectable()
export class LoginStrategy extends PassportStrategy(Strategy, 'login') {
constructor(private authService: AuthService) {
super();
}
async validate(username: string, password: string): Promise<any> {
const user = await this.authService.validate(username, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}

View File

@ -1,9 +0,0 @@
import { IsNotEmpty } from 'class-validator';
export class LoginUserDto {
@IsNotEmpty()
readonly username: string;
@IsNotEmpty()
readonly password: string;
}

View File

@ -3,8 +3,8 @@ import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from './entities/users.entity';
import { LoginUserDto } from './dto/login-user.dto';
import { UUID } from 'crypto';
import { LoginDto } from 'src/auth/dto/login.dto';
class UserDto {
userId: UUID;
@ -32,15 +32,15 @@ export class UsersService {
}));
}
async findOne({ username, password }: LoginUserDto): Promise<UserEntity> {
const user = await this.userRepository.findOneBy({ userLogin: username });
async findOne(loginDetails: LoginDto): Promise<UserEntity> {
const user = await this.userRepository.findOneBy({ userLogin: loginDetails.user_login });
if (!user) {
// TODO: force an argon2.verify() to occur here.
return null;
}
const buffer = Buffer.concat([
Buffer.from(password, 'utf8'),
Buffer.from(loginDetails.password, 'utf8'),
Buffer.from(user.salt.toString(16), 'hex'),
]);