Added user login & registration. Added SQL file for postgres database.

This commit is contained in:
Tom
2025-02-11 20:38:37 +00:00
commit d907f425dc
45 changed files with 11487 additions and 0 deletions

View File

@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

View File

@ -0,0 +1,13 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { UsersService } from './users/users.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService, private readonly users: UsersService) {}
@Get()
async getHello(): Promise<string> {
return this.appService.getHello();
}
}

View File

@ -0,0 +1,26 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersService } from './users/users.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from '@nestjs/config';
import { DatabaseOptions } from './database-config/database.options';
import { UsersModule } from './users/users.module';
import { UserEntity } from './users/users.entity';
import { AuthModule } from './auth/auth.module';
@Module({
imports: [
ConfigModule.forRoot(),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useClass: DatabaseOptions
}),
TypeOrmModule.forFeature([UserEntity]),
UsersModule,
AuthModule,
],
controllers: [AppController],
providers: [AppService, UsersService],
})
export class AppModule { }

View File

@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@ -0,0 +1,37 @@
import * as moment from 'moment';
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserEntity } from 'src/users/users.entity';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class AuthAccessService {
constructor(
private jwts: JwtService,
private config: ConfigService,
) { }
async generate(user: UserEntity) {
const now = new Date();
const limit = parseInt(this.config.getOrThrow('AUTH_JWT_ACCESS_TOKEN_EXPIRATION_MS'));
const expiration = moment(now).add(limit, 'ms').toDate();
const token = await this.jwts.signAsync(
{
username: user.userLogin,
sub: user.userId,
iat: now.getTime(),
nbf: now.getTime(),
exp: expiration.getTime(),
},
{
secret: this.config.getOrThrow('AUTH_JWT_ACCESS_TOKEN_SECRET'),
}
);
return {
access_token: token,
exp: expiration.getTime(),
}
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthController } from './auth.controller';
describe('AuthController', () => {
let controller: AuthController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuthController],
}).compile();
controller = module.get<AuthController>(AuthController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,155 @@
import { Controller, Request, Post, UseGuards, Get, Body, Res } from '@nestjs/common';
import { LoginAuthGuard } from './guards/login-auth.guard';
import { AuthService } from './auth.service';
import { UsersService } from 'src/users/users.service';
import { RegisterUserDto } from './dto/register-user.dto';
import { Response } from 'express';
import { JwtRefreshGuard } from './guards/jwt-refresh.guard';
import { OfflineGuard } from './guards/offline.guard';
@Controller('auth')
export class AuthController {
constructor(private auth: AuthService, private users: UsersService) { }
@UseGuards(LoginAuthGuard)
@Post('login')
async login(
@Request() req,
@Res({ passthrough: true }) response: Response,
) {
try {
const data = await this.auth.login(req.user);
response.cookie('Authentication', data.access_token, {
httpOnly: true,
secure: true,
expires: new Date(data.exp),
});
response.cookie('Refresh', data.refresh_token, {
httpOnly: true,
secure: true,
expires: new Date(data.refresh_exp),
});
return { success: true };
} catch (err) {
console.log(err);
return {
success: false,
error_message: 'Something went wrong.',
}
}
}
@UseGuards(LoginAuthGuard)
@Post('logout')
async logout(@Request() req) {
return req.logout();
}
@UseGuards(JwtRefreshGuard)
@Post('refresh')
async refresh(
@Request() req,
@Res({ passthrough: true }) response: Response,
) {
try {
const refresh_token = req.cookies.Refresh;
const data = await this.auth.renew(req.user, refresh_token);
response.cookie('Authentication', data.access_token, {
httpOnly: true,
secure: true,
expires: new Date(data.exp),
});
if (data.refresh_token != refresh_token) {
response.cookie('Refresh', data.refresh_token, {
httpOnly: true,
secure: true,
expires: new Date(data.refresh_exp),
});
}
return { success: true };
} catch (err) {
console.log(err);
return {
success: false,
error_message: 'Something went wrong.',
}
}
}
@UseGuards(OfflineGuard)
@Post('register')
async register(
@Request() req,
@Res({ passthrough: true }) response: Response,
@Body() body: RegisterUserDto,
) {
try {
const { user_login, user_name, password } = body;
if (!user_login) {
return { success: false, error_message: 'No user login found.' };
}
if (!user_name) {
return { success: false, error_message: 'No user name found.' };
}
if (!password) {
return { success: false, error_message: 'No password found.' };
}
if (user_name.length < 1) {
return { success: false, error_message: 'Name is too short.' };
}
if (user_name.length > 32) {
return { success: false, error_message: 'Name is too long.' };
}
if (user_login.length < 3) {
return { success: false, error_message: 'Login is too short.' };
}
if (user_login.length > 12) {
return { success: false, error_message: 'Login is too long.' };
}
if (password.length < 12) {
return { success: false, error_message: 'Password is too short.' };
}
if (password.length > 64) {
return { success: false, error_message: 'Password is too long.' };
}
const user = await this.users.register(user_login.toLowerCase(), user_name, password, true);
if (!user) {
return { success: false, error_message: 'Failed to register' };
}
const data = await this.auth.login(user);
if (!data.access_token || !data.refresh_token || !data.refresh_exp) {
return { success: false, error_message: 'Something went wrong while logging in.' };
}
response.cookie('Authentication', data.access_token, {
httpOnly: true,
secure: true,
expires: new Date(data.exp),
});
response.cookie('Refresh', data.refresh_token, {
httpOnly: true,
secure: true,
expires: new Date(data.refresh_exp),
});
return {
success: true,
}
} catch (err) {
console.log('AuthController', err);
return {
success: false,
error_message: 'Something went wrong.',
}
}
}
}

View File

@ -0,0 +1,42 @@
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';
import { JwtOptions } from './jwt.options';
import { JwtStrategy } from './strategies/jwt.strategy';
import { AuthRefreshService } from './auth.refresh.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthRefreshTokenEntity } from './entities/auth.refresh-token.entity';
import { AuthAccessService } from './auth.access.service';
@Module({
imports: [
TypeOrmModule.forFeature([AuthRefreshTokenEntity]),
ConfigModule,
UsersModule,
PassportModule,
JwtModule.registerAsync({
imports: [ConfigModule],
extraProviders: [ConfigService],
useClass: JwtOptions,
}),
],
exports: [
AuthAccessService,
AuthRefreshService,
AuthService,
],
providers: [
AuthAccessService,
AuthRefreshService,
AuthService,
JwtStrategy,
LoginStrategy,
],
controllers: [AuthController]
})
export class AuthModule { }

View File

@ -0,0 +1,92 @@
import * as crypto from 'crypto';
import * as moment from "moment";
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { UUID } from 'crypto';
import { UserEntity } from 'src/users/users.entity';
import { Repository } from 'typeorm';
import { AuthRefreshTokenEntity } from './entities/auth.refresh-token.entity';
@Injectable()
export class AuthRefreshService {
constructor(
private jwts: JwtService,
private config: ConfigService,
@InjectRepository(AuthRefreshTokenEntity)
private authRefreshTokenRepository: Repository<AuthRefreshTokenEntity>
) { }
async generate(user: UserEntity, refreshToken?: string) {
let expiration: Date | null = null;
if (refreshToken) {
const token = await this.get(refreshToken, user.userId);
if (token.exp.getTime() > new Date().getTime()) {
throw new UnauthorizedException('Invalid refresh token.');
}
expiration = token.exp;
}
// Generate new refresh token if either:
// - no previous token exists;
// - token has reached expiration threshold;
// - token has expired.
const now = new Date();
const threshhold = parseInt(this.config.getOrThrow('AUTH_JWT_REFRESH_TOKEN_EXPIRATION_THRESHHOLD_MS'));
if (!refreshToken || !expiration || now.getTime() - expiration.getTime() > threshhold) {
const limit = parseInt(this.config.getOrThrow('AUTH_JWT_REFRESH_TOKEN_EXPIRATION_MS'));
expiration = moment(now).add(limit, 'ms').toDate();
refreshToken = await this.jwts.signAsync(
{
username: user.userLogin,
sub: user.userId,
iat: now.getTime(),
nbf: now.getTime(),
exp: expiration.getTime(),
},
{
secret: this.config.getOrThrow('AUTH_JWT_REFRESH_TOKEN_SECRET'),
}
);
this.authRefreshTokenRepository.insert({
tokenHash: refreshToken,
userId: user.userId,
exp: expiration
});
}
return {
refresh_token: refreshToken,
exp: expiration.getTime(),
}
}
async get(
refreshToken: string,
userId: UUID,
): Promise<{ tokenHash: string, userId: UUID, exp: Date }> {
if (!refreshToken || !userId) {
return null;
}
const buffer = Buffer.from(refreshToken, 'utf8');
const hash = crypto.createHash('sha256').update(buffer).digest('base64');
return await this.authRefreshTokenRepository.findOneBy({
tokenHash: hash,
userId: userId,
});
}
async validate(
refreshToken: string,
userId: UUID,
): Promise<boolean> {
const refresh = await this.get(refreshToken, userId);
return refresh && refresh.exp.getTime() > new Date().getTime();
}
}

View File

@ -0,0 +1,42 @@
import { Injectable } from '@nestjs/common';
import { UserEntity } from 'src/users/users.entity';
import { UsersService } from 'src/users/users.service';
import { AuthRefreshService } from './auth.refresh.service';
import { AuthAccessService } from './auth.access.service';
@Injectable()
export class AuthService {
constructor(
private accessTokens: AuthAccessService,
private refreshTokens: AuthRefreshService,
private users: UsersService,
) { }
async login(user: UserEntity) {
return this.renew(user, null);
}
async validate(
username: string,
password: string,
): Promise<UserEntity | null> {
return await this.users.findOne({ username, password });
}
async renew(
user: UserEntity,
refresh_token: string
): Promise<{ access_token: string, exp: number, refresh_token: string, refresh_exp: number }> {
const new_refresh_data = await this.refreshTokens.generate(user, refresh_token);
const new_refresh_token = new_refresh_data.refresh_token;
const new_refresh_exp = new_refresh_data.exp;
const access_token = await this.accessTokens.generate(user);
return {
...access_token,
refresh_token: new_refresh_token,
refresh_exp: new_refresh_exp,
}
}
}

View File

@ -0,0 +1,12 @@
import { IsNotEmpty } from 'class-validator';
export class RegisterUserDto {
@IsNotEmpty()
readonly user_login: string;
@IsNotEmpty()
readonly user_name: string;
@IsNotEmpty()
readonly password: string;
}

View File

@ -0,0 +1,26 @@
import * as crypto from 'crypto';
import { IsNotEmpty } from 'class-validator';
import { UUID } from 'crypto';
import { BeforeInsert, Column, Entity, PrimaryColumn } from 'typeorm';
@Entity("refresh_tokens")
export class AuthRefreshTokenEntity {
@PrimaryColumn({ name: 'user_id' })
@IsNotEmpty()
readonly userId: UUID;
@PrimaryColumn({ name: 'refresh_token_hash' })
@IsNotEmpty()
tokenHash: string;
@Column()
@IsNotEmpty()
exp: Date;
@BeforeInsert()
async hashRefreshToken() {
const buffer = Buffer.from(this.tokenHash, 'utf8');
const hash = crypto.createHash('sha256').update(buffer).digest('base64');
this.tokenHash = hash;
}
}

View File

@ -0,0 +1,20 @@
import { ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class JwtAccessAdminGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
// Add your custom authentication logic here
// for example, call super.logIn(request) to establish a session.
return super.canActivate(context);
}
handleRequest(err, user, info) {
// You can throw an exception based on either "info" or "err" arguments
if (err || !user || !user.isAdmin) {
throw err || new UnauthorizedException();
}
return user;
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,13 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable()
export class OfflineGuard implements CanActivate {
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest();
return !request.user;
}
}

View File

@ -0,0 +1,20 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtModuleOptions, JwtOptionsFactory } from '@nestjs/jwt';
@Injectable()
export class JwtOptions implements JwtOptionsFactory {
constructor(
private config: ConfigService,
) { }
createJwtOptions(): Promise<JwtModuleOptions> | JwtModuleOptions {
return {
signOptions: {
issuer: this.config.getOrThrow('AUTH_JWT_ISSUER'),
audience: this.config.getOrThrow('AUTH_JWT_AUDIENCE'),
},
};
}
}

View File

@ -0,0 +1,25 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AuthRefreshService } from '../auth.refresh.service';
import { Request } from 'express';
@Injectable()
export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'jwt-refresh') {
constructor(private auth: AuthRefreshService, private config: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: config.get('AUTH_JWT_REFRESH_SECRET'),
issuer: config.getOrThrow('AUTH_JWT_ISSUER'),
audience: config.getOrThrow('AUTH_JWT_AUDIENCE'),
passReqToCallback: true,
});
}
async validate(request: Request, payload: any) {
return this.auth.validate(request.cookies?.Refresh, payload.sub);
}
}

View File

@ -0,0 +1,29 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { UsersService } from 'src/users/users.service';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(private users: UsersService, private config: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: config.getOrThrow('AUTH_JWT_ACCESS_TOKEN_SECRET'),
issuer: config.getOrThrow('AUTH_JWT_ISSUER'),
audience: config.getOrThrow('AUTH_JWT_AUDIENCE'),
passReqToCallback: true,
});
}
async validate(req: Request, payload: any) {
console.log('jwt payload', payload);
const user = await this.users.findById(payload.sub);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}

View File

@ -0,0 +1,20 @@
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

@ -0,0 +1,7 @@
import { Module } from '@nestjs/common';
import { DatabaseOptions } from './database.options';
@Module({
providers: [DatabaseOptions]
})
export class DatabaseConfigModule {}

View File

@ -0,0 +1,31 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm';
import { SnakeNamingStrategy } from "typeorm-naming-strategies"
@Injectable()
export class DatabaseOptions implements TypeOrmOptionsFactory {
constructor(private config: ConfigService) { }
createTypeOrmOptions(): TypeOrmModuleOptions | Promise<TypeOrmModuleOptions> {
return {
type: "postgres",
host: this.config.getOrThrow('DATABASE_HOST'),
port: parseInt(this.config.getOrThrow('DATABASE_PORT'), 10),
username: this.config.getOrThrow('DATABASE_USERNAME'),
password: this.config.getOrThrow('DATABASE_PASSWORD'),
database: this.config.getOrThrow('DATABASE_NAME'),
entities: [__dirname + '/../**/*.entity.js'],
logging: true,
synchronize: false,
//migrations: ['dist/migrations/*.ts'],
// cli: {
// migrationsDir: process.env.TYPEORM_MIGRATIONS_DIR,
// },
namingStrategy: new SnakeNamingStrategy(),
};
}
}

View File

@ -0,0 +1,10 @@
import * as cookieParser from 'cookie-parser';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(cookieParser());
await app.listen(process.env.PORT ?? 3001);
}
bootstrap();

View File

@ -0,0 +1,6 @@
import { ValueTransformer } from "typeorm";
export const BigIntTransformer: ValueTransformer = {
to: (entityValue: bigint) => entityValue.toString(),
from: (databaseValue: string): bigint => BigInt(databaseValue),
};

View File

@ -0,0 +1,6 @@
import { ValueTransformer } from "typeorm";
export const StringToLowerCaseTransformer: ValueTransformer = {
to: (entityValue: string) => entityValue.toLowerCase(),
from: (databaseValue: string): string => databaseValue,
};

View File

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

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersController } from './users.controller';
describe('UsersController', () => {
let controller: UsersController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UsersController],
}).compile();
controller = module.get<UsersController>(UsersController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { UsersService } from './users.service';
@Controller('users')
export class UsersController {
constructor(private users: UsersService) { }
@Get()
async anything(): Promise<any[]> {
return this.users.findAll();
}
}

View File

@ -0,0 +1,48 @@
import * as argon2 from 'argon2';
import * as crypto from 'crypto';
import { UUID } from "crypto";
import { BigIntTransformer } from 'src/shared/transformers/bigint';
import { StringToLowerCaseTransformer } from 'src/shared/transformers/string';
import { BeforeInsert, Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity({
name: 'users'
})
export class UserEntity {
@PrimaryGeneratedColumn("uuid", { name: 'user_id' })
userId: UUID;
@Column({ name: 'user_login', unique: true, transformer: StringToLowerCaseTransformer })
userLogin: string;
@Column({ name: 'user_name', nullable: false })
userName: string;
@Column({ nullable: false })
password: string;
@Column({ type: 'bigint', nullable: false, transformer: BigIntTransformer })
salt: BigInt;
@Column({ name: 'is_admin', nullable: false })
isAdmin: boolean;
@Column({ name: 'date_joined', type: 'timestamptz', nullable: false })
dateJoined: Date;
@BeforeInsert()
async hashPassword() {
const saltBuf = crypto.randomBytes(8);
// Remove first bit to only have positive, signed 63-bit values.
saltBuf[0] |= 0b10000000;
saltBuf[0] ^= 0b10000000;
this.salt = BigInt("0x" + saltBuf.toString('hex'));
const buffer = Buffer.concat([
Buffer.from(this.password, 'utf8'),
Buffer.from(this.salt.toString(16), 'hex'),
]);
this.password = await argon2.hash(buffer, { raw: false });
}
}

View File

@ -0,0 +1,22 @@
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { UserEntity } from './users.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersController } from './users.controller';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
TypeOrmModule.forFeature([UserEntity]),
ConfigModule,
],
exports: [
UsersService,
],
providers: [
UserEntity,
UsersService,
],
controllers: [UsersController],
})
export class UsersModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from './users.service';
describe('UsersService', () => {
let service: UsersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UsersService],
}).compile();
service = module.get<UsersService>(UsersService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,72 @@
import * as argon2 from 'argon2';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from './users.entity';
import { LoginUserDto } from './dto/login-user.dto';
import { UUID } from 'crypto';
class UserDto {
userId: string;
userLogin: string;
userName: string;
isAdmin: boolean;
dateJoined: Date;
}
@Injectable()
export class UsersService {
constructor(
@InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
) { }
async findAll(): Promise<UserDto[]> {
const result = await this.userRepository.find();
return result.map((u: UserEntity) => ({
userId: u.userId,
userLogin: u.userLogin,
userName: u.userName,
isAdmin: u.isAdmin,
dateJoined: u.dateJoined,
}));
}
async findOne({ username, password }: LoginUserDto): Promise<UserEntity> {
const user = await this.userRepository.findOneBy({ userLogin: username });
if (!user) {
// TODO: force an argon2.verify() to occur here.
return null;
}
const buffer = Buffer.concat([
Buffer.from(password, 'utf8'),
Buffer.from(user.salt.toString(16), 'hex'),
]);
if (await argon2.verify(user.password, buffer)) {
return user;
}
return null;
}
async findById(userId: UUID): Promise<UserEntity> {
const user = await this.userRepository.findOneBy({ userId });
if (!user) {
return null;
}
return user;
}
async register(userLogin: string, userName: string, password: string, isAdmin: boolean) {
const result = await this.userRepository.create({
userLogin,
userName,
password,
salt: 0,
isAdmin,
});
return await this.userRepository.save(result);
}
}