Compare commits
3 Commits
d907f425dc
...
16f208480d
| Author | SHA1 | Date | |
|---|---|---|---|
| 16f208480d | |||
| abb8bec0cf | |||
| a0909bfd21 |
@@ -99,7 +99,8 @@ CREATE TABLE
|
||||
user_id uuid NOT NULL,
|
||||
refresh_token_hash text NOT NULL,
|
||||
exp timestamp NOT NULL,
|
||||
PRIMARY KEY (user_id, refresh_token_hash)
|
||||
PRIMARY KEY (user_id, refresh_token_hash),
|
||||
FOREIGN KEY (user_id) REFERENCES users (user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE
|
||||
|
||||
7
backend/nestjs-seshat-api/package-lock.json
generated
7
backend/nestjs-seshat-api/package-lock.json
generated
@@ -17,6 +17,7 @@
|
||||
"@nestjs/platform-express": "^10.0.0",
|
||||
"@nestjs/typeorm": "^11.0.0",
|
||||
"argon2": "^0.41.1",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.1",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"moment": "^2.30.1",
|
||||
@@ -3530,6 +3531,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/class-transformer": {
|
||||
"version": "0.5.1",
|
||||
"resolved": "https://registry.npmjs.org/class-transformer/-/class-transformer-0.5.1.tgz",
|
||||
"integrity": "sha512-SQa1Ws6hUbfC98vKGxZH3KFY0Y1lm5Zm0SY8XX9zbK7FJCyVEac3ATW0RIpwzW+oOfmHE5PMPufDG9hCfoEOMw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/class-validator": {
|
||||
"version": "0.14.1",
|
||||
"resolved": "https://registry.npmjs.org/class-validator/-/class-validator-0.14.1.tgz",
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
"@nestjs/platform-express": "^10.0.0",
|
||||
"@nestjs/typeorm": "^11.0.0",
|
||||
"argon2": "^0.41.1",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.1",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"moment": "^2.30.1",
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import pino from 'pino';
|
||||
import * as path from 'path';
|
||||
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 { ConfigModule, ConfigService } 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';
|
||||
import { LoggerModule } from 'nestjs-pino';
|
||||
import { serialize_token, serialize_user_short, serialize_user_long, serialize_res, serialize_req } from './logging.serializers';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -19,6 +23,36 @@ import { AuthModule } from './auth/auth.module';
|
||||
TypeOrmModule.forFeature([UserEntity]),
|
||||
UsersModule,
|
||||
AuthModule,
|
||||
LoggerModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: async (config: ConfigService) => {
|
||||
return {
|
||||
pinoHttp: {
|
||||
level: config.get('LOG_LEVEL') ?? 'info',
|
||||
autoLogging: true,
|
||||
serializers: config.get('ENVIRONMENT', 'production') == 'development' ? {
|
||||
user: value => serialize_user_long(value),
|
||||
access_token: value => serialize_token(value),
|
||||
refresh_token: value => serialize_token(value),
|
||||
req: value => serialize_req(value),
|
||||
res: value => serialize_res(value),
|
||||
} : {
|
||||
user: value => serialize_user_short(value),
|
||||
access_token: value => serialize_token(value),
|
||||
refresh_token: value => serialize_token(value),
|
||||
req: value => serialize_req(value),
|
||||
res: value => serialize_res(value),
|
||||
},
|
||||
stream: pino.destination({
|
||||
dest: path.join(config.get('LOG_DIRECTORY') ?? 'logs', 'backend.api.log'),
|
||||
minLength: 512,
|
||||
sync: false,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService, UsersService],
|
||||
|
||||
@@ -3,17 +3,19 @@ import { Injectable } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { UserEntity } from 'src/users/users.entity';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PinoLogger } from 'nestjs-pino';
|
||||
|
||||
@Injectable()
|
||||
export class AuthAccessService {
|
||||
constructor(
|
||||
private jwts: JwtService,
|
||||
private config: ConfigService,
|
||||
private logger: PinoLogger,
|
||||
) { }
|
||||
|
||||
async generate(user: UserEntity) {
|
||||
const now = new Date();
|
||||
const limit = parseInt(this.config.getOrThrow('AUTH_JWT_ACCESS_TOKEN_EXPIRATION_MS'));
|
||||
const limit = parseInt(this.config.getOrThrow<string>('AUTH_JWT_ACCESS_TOKEN_EXPIRATION_MS'));
|
||||
const expiration = moment(now).add(limit, 'ms').toDate();
|
||||
|
||||
const token = await this.jwts.signAsync(
|
||||
@@ -25,10 +27,19 @@ export class AuthAccessService {
|
||||
exp: expiration.getTime(),
|
||||
},
|
||||
{
|
||||
secret: this.config.getOrThrow('AUTH_JWT_ACCESS_TOKEN_SECRET'),
|
||||
secret: this.config.getOrThrow<string>('AUTH_JWT_ACCESS_TOKEN_SECRET'),
|
||||
}
|
||||
);
|
||||
|
||||
this.logger.debug({
|
||||
class: AuthAccessService.name,
|
||||
method: this.generate.name,
|
||||
user,
|
||||
access_token: token,
|
||||
exp: expiration,
|
||||
msg: 'User generated an access token.',
|
||||
});
|
||||
|
||||
return {
|
||||
access_token: token,
|
||||
exp: expiration.getTime(),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Controller, Request, Post, UseGuards, Get, Body, Res } from '@nestjs/common';
|
||||
import { Controller, Request, Post, UseGuards, Body, Res } from '@nestjs/common';
|
||||
import { LoginAuthGuard } from './guards/login-auth.guard';
|
||||
import { AuthService } from './auth.service';
|
||||
import { UsersService } from 'src/users/users.service';
|
||||
@@ -6,10 +6,18 @@ import { RegisterUserDto } from './dto/register-user.dto';
|
||||
import { Response } from 'express';
|
||||
import { JwtRefreshGuard } from './guards/jwt-refresh.guard';
|
||||
import { OfflineGuard } from './guards/offline.guard';
|
||||
import { UserEntity } from 'src/users/users.entity';
|
||||
import { QueryFailedError } from 'typeorm';
|
||||
import { PinoLogger } from 'nestjs-pino';
|
||||
import { JwtAccessGuard } from './guards/jwt-access.guard';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private auth: AuthService, private users: UsersService) { }
|
||||
constructor(
|
||||
private auth: AuthService,
|
||||
private users: UsersService,
|
||||
private logger: PinoLogger,
|
||||
) { }
|
||||
|
||||
@UseGuards(LoginAuthGuard)
|
||||
@Post('login')
|
||||
@@ -17,34 +25,75 @@ export class AuthController {
|
||||
@Request() req,
|
||||
@Res({ passthrough: true }) response: Response,
|
||||
) {
|
||||
let data: AuthenticationDto | null;
|
||||
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 };
|
||||
data = await this.auth.login(req.user);
|
||||
if (!data.access_token || !data.refresh_token || !data.refresh_exp) {
|
||||
return {
|
||||
success: false,
|
||||
error_message: 'Something went wrong with tokens while logging in.',
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
this.logger.error({
|
||||
class: AuthController.name,
|
||||
method: this.login.name,
|
||||
user: req.user,
|
||||
msg: 'Failed to login.',
|
||||
error: err,
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
error_message: 'Something went wrong.',
|
||||
}
|
||||
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),
|
||||
});
|
||||
|
||||
this.logger.info({
|
||||
class: AuthController.name,
|
||||
method: this.login.name,
|
||||
user: req.user,
|
||||
access_token: data.access_token,
|
||||
refresh_token: data.refresh_token,
|
||||
msg: 'User logged in.',
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
};
|
||||
}
|
||||
|
||||
@UseGuards(LoginAuthGuard)
|
||||
@UseGuards(JwtAccessGuard)
|
||||
@Post('logout')
|
||||
async logout(@Request() req) {
|
||||
async logout(
|
||||
@Request() req,
|
||||
@Res({ passthrough: true }) response: Response,
|
||||
) {
|
||||
console.log('logout cookie', req.cookies?.Refresh);
|
||||
// TODO: delete refresh token from database.
|
||||
// await this.auth.delete(req.cookies?.Refresh);
|
||||
|
||||
response.clearCookie('Refresh');
|
||||
response.clearCookie('Authentication');
|
||||
|
||||
this.logger.info({
|
||||
class: AuthController.name,
|
||||
method: this.logout.name,
|
||||
user: req.user,
|
||||
msg: 'User logged off',
|
||||
});
|
||||
|
||||
return req.logout();
|
||||
}
|
||||
|
||||
@@ -63,6 +112,13 @@ export class AuthController {
|
||||
secure: true,
|
||||
expires: new Date(data.exp),
|
||||
});
|
||||
this.logger.debug({
|
||||
class: AuthController.name,
|
||||
method: this.refresh.name,
|
||||
user: req.user,
|
||||
access_token: data.access_token,
|
||||
msg: 'Updated Authentication cookie for access token.',
|
||||
});
|
||||
|
||||
if (data.refresh_token != refresh_token) {
|
||||
response.cookie('Refresh', data.refresh_token, {
|
||||
@@ -70,15 +126,28 @@ export class AuthController {
|
||||
secure: true,
|
||||
expires: new Date(data.refresh_exp),
|
||||
});
|
||||
this.logger.debug({
|
||||
class: AuthController.name,
|
||||
method: this.refresh.name,
|
||||
user: req.user,
|
||||
refresh_token: data.refresh_token,
|
||||
msg: 'Updated Refresh cookie for refresh token.',
|
||||
});
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
this.logger.error({
|
||||
class: AuthController.name,
|
||||
method: this.refresh.name,
|
||||
user: req.user,
|
||||
msg: 'Failed to refresh tokens.',
|
||||
error: err,
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
error_message: 'Something went wrong.',
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,67 +158,89 @@ export class AuthController {
|
||||
@Res({ passthrough: true }) response: Response,
|
||||
@Body() body: RegisterUserDto,
|
||||
) {
|
||||
let user: UserEntity | null;
|
||||
let data: AuthenticationDto | null;
|
||||
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),
|
||||
user = await this.users.register(user_login.toLowerCase(), user_name, password, true);
|
||||
this.logger.info({
|
||||
class: AuthController.name,
|
||||
method: this.register.name,
|
||||
user: req.user,
|
||||
msg: 'User registered',
|
||||
});
|
||||
|
||||
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);
|
||||
if (err instanceof QueryFailedError) {
|
||||
if (err.message.includes('duplicate key value violates unique constraint "users_user_login_key"')) {
|
||||
this.logger.warn({
|
||||
class: AuthController.name,
|
||||
method: this.register.name,
|
||||
user: req.user,
|
||||
msg: 'Failed to register due to duplicate userLogin.',
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
error_message: 'Username already exist.',
|
||||
};
|
||||
}
|
||||
}
|
||||
this.logger.error({
|
||||
class: AuthController.name,
|
||||
method: this.register.name,
|
||||
user: req.user,
|
||||
msg: 'Failed to register.',
|
||||
error: err,
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
error_message: 'Something went wrong.',
|
||||
}
|
||||
error_message: 'Something went wrong when creating user.',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
data = await this.auth.login(user);
|
||||
if (!data.access_token || !data.refresh_token || !data.refresh_exp) {
|
||||
this.logger.error({
|
||||
class: AuthController.name,
|
||||
method: this.register.name,
|
||||
user: req.user,
|
||||
access_token: data.access_token,
|
||||
refresh_token: data.refresh_token,
|
||||
msg: 'Failed to generate tokens after registering.',
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
error_message: 'Something went wrong with tokens while logging in.',
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
this.logger.error({
|
||||
class: AuthController.name,
|
||||
method: this.register.name,
|
||||
user: req.user,
|
||||
msg: 'Failed to login after registering.',
|
||||
error: err,
|
||||
});
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { UUID } from 'crypto';
|
||||
import { UserEntity } from 'src/users/users.entity';
|
||||
import { Repository } from 'typeorm';
|
||||
import { AuthRefreshTokenEntity } from './entities/auth.refresh-token.entity';
|
||||
import { PinoLogger } from 'nestjs-pino';
|
||||
|
||||
@Injectable()
|
||||
export class AuthRefreshService {
|
||||
@@ -15,7 +16,8 @@ export class AuthRefreshService {
|
||||
private jwts: JwtService,
|
||||
private config: ConfigService,
|
||||
@InjectRepository(AuthRefreshTokenEntity)
|
||||
private authRefreshTokenRepository: Repository<AuthRefreshTokenEntity>
|
||||
private authRefreshTokenRepository: Repository<AuthRefreshTokenEntity>,
|
||||
private logger: PinoLogger,
|
||||
) { }
|
||||
|
||||
|
||||
@@ -23,7 +25,25 @@ export class AuthRefreshService {
|
||||
let expiration: Date | null = null;
|
||||
if (refreshToken) {
|
||||
const token = await this.get(refreshToken, user.userId);
|
||||
if (!token) {
|
||||
this.logger.warn({
|
||||
class: AuthRefreshService.name,
|
||||
method: this.generate.name,
|
||||
user,
|
||||
refresh_token: refreshToken,
|
||||
msg: 'Refresh token given is invalid.',
|
||||
});
|
||||
throw new UnauthorizedException('Invalid refresh token.');
|
||||
}
|
||||
if (token.exp.getTime() > new Date().getTime()) {
|
||||
this.logger.warn({
|
||||
class: AuthRefreshService.name,
|
||||
method: this.generate.name,
|
||||
user,
|
||||
refresh_token: refreshToken,
|
||||
exp: expiration,
|
||||
msg: 'Refresh token given has expired.',
|
||||
});
|
||||
throw new UnauthorizedException('Invalid refresh token.');
|
||||
}
|
||||
|
||||
@@ -35,9 +55,25 @@ export class AuthRefreshService {
|
||||
// - 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'));
|
||||
const threshhold = parseInt(this.config.getOrThrow<string>('AUTH_JWT_REFRESH_TOKEN_EXPIRATION_THRESHHOLD_MS'));
|
||||
if (!refreshToken || now.getTime() - expiration.getTime() > threshhold) {
|
||||
if (refreshToken) {
|
||||
this.authRefreshTokenRepository.delete({
|
||||
tokenHash: refreshToken,
|
||||
userId: user.userId,
|
||||
});
|
||||
|
||||
this.logger.debug({
|
||||
class: AuthRefreshService.name,
|
||||
method: this.generate.name,
|
||||
user,
|
||||
refresh_token: refreshToken,
|
||||
exp: expiration,
|
||||
msg: 'Deleted previous refresh token.',
|
||||
});
|
||||
}
|
||||
|
||||
const limit = parseInt(this.config.getOrThrow<string>('AUTH_JWT_REFRESH_TOKEN_EXPIRATION_MS'));
|
||||
expiration = moment(now).add(limit, 'ms').toDate();
|
||||
refreshToken = await this.jwts.signAsync(
|
||||
{
|
||||
@@ -48,15 +84,33 @@ export class AuthRefreshService {
|
||||
exp: expiration.getTime(),
|
||||
},
|
||||
{
|
||||
secret: this.config.getOrThrow('AUTH_JWT_REFRESH_TOKEN_SECRET'),
|
||||
secret: this.config.getOrThrow<string>('AUTH_JWT_REFRESH_TOKEN_SECRET'),
|
||||
}
|
||||
);
|
||||
|
||||
this.logger.debug({
|
||||
class: AuthRefreshService.name,
|
||||
method: this.generate.name,
|
||||
user,
|
||||
refresh_token: refreshToken,
|
||||
exp: expiration,
|
||||
msg: 'Generated a new refresh token.',
|
||||
});
|
||||
|
||||
this.authRefreshTokenRepository.insert({
|
||||
tokenHash: refreshToken,
|
||||
userId: user.userId,
|
||||
exp: expiration
|
||||
});
|
||||
|
||||
this.logger.debug({
|
||||
class: AuthRefreshService.name,
|
||||
method: this.generate.name,
|
||||
user,
|
||||
refresh_token: refreshToken,
|
||||
exp: expiration,
|
||||
msg: 'Inserted the new refresh token.',
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -13,7 +13,7 @@ export class AuthService {
|
||||
) { }
|
||||
|
||||
|
||||
async login(user: UserEntity) {
|
||||
async login(user: UserEntity): Promise<AuthenticationDto> {
|
||||
return this.renew(user, null);
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ export class AuthService {
|
||||
async renew(
|
||||
user: UserEntity,
|
||||
refresh_token: string
|
||||
): Promise<{ access_token: string, exp: number, refresh_token: string, refresh_exp: number }> {
|
||||
): Promise<AuthenticationDto> {
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
class AuthenticationDto {
|
||||
access_token: string;
|
||||
exp: number;
|
||||
refresh_token: string | null;
|
||||
refresh_exp: number | null;
|
||||
}
|
||||
@@ -1,12 +1,19 @@
|
||||
import { IsNotEmpty } from 'class-validator';
|
||||
import { IsAlphanumeric, IsNotEmpty, IsString, Length, MaxLength, MinLength } from 'class-validator';
|
||||
|
||||
export class RegisterUserDto {
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@Length(3, 16)
|
||||
@IsAlphanumeric()
|
||||
readonly user_login: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@Length(1, 32)
|
||||
readonly user_name: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@Length(12, 64)
|
||||
@MinLength(12)
|
||||
@MaxLength(64)
|
||||
readonly password: string;
|
||||
}
|
||||
@@ -12,8 +12,8 @@ export class JwtOptions implements JwtOptionsFactory {
|
||||
createJwtOptions(): Promise<JwtModuleOptions> | JwtModuleOptions {
|
||||
return {
|
||||
signOptions: {
|
||||
issuer: this.config.getOrThrow('AUTH_JWT_ISSUER'),
|
||||
audience: this.config.getOrThrow('AUTH_JWT_AUDIENCE'),
|
||||
issuer: this.config.getOrThrow<string>('AUTH_JWT_ISSUER'),
|
||||
audience: this.config.getOrThrow<string>('AUTH_JWT_AUDIENCE'),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -12,9 +12,9 @@ export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'jwt-refresh'
|
||||
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'),
|
||||
secretOrKey: config.get<string>('AUTH_JWT_REFRESH_SECRET'),
|
||||
issuer: config.getOrThrow<string>('AUTH_JWT_ISSUER'),
|
||||
audience: config.getOrThrow<string>('AUTH_JWT_AUDIENCE'),
|
||||
passReqToCallback: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -11,15 +11,14 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
||||
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'),
|
||||
secretOrKey: config.getOrThrow<string>('AUTH_JWT_ACCESS_TOKEN_SECRET'),
|
||||
issuer: config.getOrThrow<string>('AUTH_JWT_ISSUER'),
|
||||
audience: config.getOrThrow<string>('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();
|
||||
|
||||
@@ -12,11 +12,11 @@ export class DatabaseOptions implements TypeOrmOptionsFactory {
|
||||
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'),
|
||||
host: this.config.getOrThrow<string>('DATABASE_HOST'),
|
||||
port: parseInt(this.config.getOrThrow<string>('DATABASE_PORT'), 10),
|
||||
username: this.config.getOrThrow<string>('DATABASE_USERNAME'),
|
||||
password: this.config.getOrThrow<string>('DATABASE_PASSWORD'),
|
||||
database: this.config.getOrThrow<string>('DATABASE_NAME'),
|
||||
|
||||
entities: [__dirname + '/../**/*.entity.js'],
|
||||
logging: true,
|
||||
|
||||
64
backend/nestjs-seshat-api/src/logging.serializers.ts
Normal file
64
backend/nestjs-seshat-api/src/logging.serializers.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { UserEntity } from "./users/users.entity";
|
||||
|
||||
export function serialize_user_short(value: UserEntity) {
|
||||
if (!value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return value.userLogin;
|
||||
}
|
||||
|
||||
export function serialize_user_long(value: UserEntity) {
|
||||
if (!value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
return {
|
||||
user_id: value.userId,
|
||||
user_login: value.userLogin,
|
||||
is_admin: value.isAdmin,
|
||||
}
|
||||
}
|
||||
|
||||
export function serialize_token(value: string) {
|
||||
return '...' + value.substring(Math.max(value.length - 12, value.length / 2) | 0);
|
||||
}
|
||||
|
||||
export function serialize_req(value) {
|
||||
if (!value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
delete value['remoteAddress']
|
||||
delete value['remotePort']
|
||||
|
||||
if (value.headers) {
|
||||
const headers = value.headers;
|
||||
if (headers['Authorization']) {
|
||||
headers['Authorization'] = headers['Authorization'].substring(Math.max(0, headers['Authorization'].length - 12))
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function serialize_res(value) {
|
||||
if (!value || !value.headers) {
|
||||
return value;
|
||||
}
|
||||
|
||||
const headers = value.headers;
|
||||
delete headers['x-powered-by'];
|
||||
|
||||
if (headers['set-cookie']) {
|
||||
const cookies = headers['set-cookie'];
|
||||
for (let i in cookies) {
|
||||
const cookie: string = cookies[i];
|
||||
if (cookie.startsWith('Authentication=')) {
|
||||
cookies[i] = 'Authentication=...' + cookie.substring(Math.max(0, cookie.indexOf(';') - 12));
|
||||
} else if (cookie.startsWith('Refresh=')) {
|
||||
cookies[i] = 'Refresh=...' + cookie.substring(Math.max(0, cookie.indexOf(';') - 12));
|
||||
}
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -1,10 +1,19 @@
|
||||
import * as cookieParser from 'cookie-parser';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { Logger, LoggerErrorInterceptor } from 'nestjs-pino';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
const app = await NestFactory.create(AppModule, { bufferLogs: true });
|
||||
app.use(cookieParser());
|
||||
app.useGlobalPipes(new ValidationPipe({
|
||||
stopAtFirstError: true,
|
||||
whitelist: true,
|
||||
transform: true,
|
||||
}));
|
||||
app.useLogger(app.get(Logger));
|
||||
app.useGlobalInterceptors(new LoggerErrorInterceptor());
|
||||
await app.listen(process.env.PORT ?? 3001);
|
||||
}
|
||||
bootstrap();
|
||||
|
||||
Reference in New Issue
Block a user