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,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;
}
}