Compare commits
3 Commits
d907f425dc
...
16f208480d
| Author | SHA1 | Date | |
|---|---|---|---|
| 16f208480d | |||
| abb8bec0cf | |||
| a0909bfd21 |
@@ -99,7 +99,8 @@ CREATE TABLE
|
|||||||
user_id uuid NOT NULL,
|
user_id uuid NOT NULL,
|
||||||
refresh_token_hash text NOT NULL,
|
refresh_token_hash text NOT NULL,
|
||||||
exp timestamp 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
|
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/platform-express": "^10.0.0",
|
||||||
"@nestjs/typeorm": "^11.0.0",
|
"@nestjs/typeorm": "^11.0.0",
|
||||||
"argon2": "^0.41.1",
|
"argon2": "^0.41.1",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.1",
|
"class-validator": "^0.14.1",
|
||||||
"cookie-parser": "^1.4.7",
|
"cookie-parser": "^1.4.7",
|
||||||
"moment": "^2.30.1",
|
"moment": "^2.30.1",
|
||||||
@@ -3530,6 +3531,12 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"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": {
|
"node_modules/class-validator": {
|
||||||
"version": "0.14.1",
|
"version": "0.14.1",
|
||||||
"resolved": "https://registry.npmjs.org/class-validator/-/class-validator-0.14.1.tgz",
|
"resolved": "https://registry.npmjs.org/class-validator/-/class-validator-0.14.1.tgz",
|
||||||
|
|||||||
@@ -28,6 +28,7 @@
|
|||||||
"@nestjs/platform-express": "^10.0.0",
|
"@nestjs/platform-express": "^10.0.0",
|
||||||
"@nestjs/typeorm": "^11.0.0",
|
"@nestjs/typeorm": "^11.0.0",
|
||||||
"argon2": "^0.41.1",
|
"argon2": "^0.41.1",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.1",
|
"class-validator": "^0.14.1",
|
||||||
"cookie-parser": "^1.4.7",
|
"cookie-parser": "^1.4.7",
|
||||||
"moment": "^2.30.1",
|
"moment": "^2.30.1",
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
|
import pino from 'pino';
|
||||||
|
import * as path from 'path';
|
||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { AppController } from './app.controller';
|
import { AppController } from './app.controller';
|
||||||
import { AppService } from './app.service';
|
import { AppService } from './app.service';
|
||||||
import { UsersService } from './users/users.service';
|
import { UsersService } from './users/users.service';
|
||||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||||
import { ConfigModule } from '@nestjs/config';
|
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||||
import { DatabaseOptions } from './database-config/database.options';
|
import { DatabaseOptions } from './database-config/database.options';
|
||||||
import { UsersModule } from './users/users.module';
|
import { UsersModule } from './users/users.module';
|
||||||
import { UserEntity } from './users/users.entity';
|
import { UserEntity } from './users/users.entity';
|
||||||
import { AuthModule } from './auth/auth.module';
|
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({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -19,6 +23,36 @@ import { AuthModule } from './auth/auth.module';
|
|||||||
TypeOrmModule.forFeature([UserEntity]),
|
TypeOrmModule.forFeature([UserEntity]),
|
||||||
UsersModule,
|
UsersModule,
|
||||||
AuthModule,
|
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],
|
controllers: [AppController],
|
||||||
providers: [AppService, UsersService],
|
providers: [AppService, UsersService],
|
||||||
|
|||||||
@@ -3,17 +3,19 @@ import { Injectable } from '@nestjs/common';
|
|||||||
import { JwtService } from '@nestjs/jwt';
|
import { JwtService } from '@nestjs/jwt';
|
||||||
import { UserEntity } from 'src/users/users.entity';
|
import { UserEntity } from 'src/users/users.entity';
|
||||||
import { ConfigService } from '@nestjs/config';
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { PinoLogger } from 'nestjs-pino';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthAccessService {
|
export class AuthAccessService {
|
||||||
constructor(
|
constructor(
|
||||||
private jwts: JwtService,
|
private jwts: JwtService,
|
||||||
private config: ConfigService,
|
private config: ConfigService,
|
||||||
|
private logger: PinoLogger,
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
async generate(user: UserEntity) {
|
async generate(user: UserEntity) {
|
||||||
const now = new Date();
|
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 expiration = moment(now).add(limit, 'ms').toDate();
|
||||||
|
|
||||||
const token = await this.jwts.signAsync(
|
const token = await this.jwts.signAsync(
|
||||||
@@ -25,10 +27,19 @@ export class AuthAccessService {
|
|||||||
exp: expiration.getTime(),
|
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 {
|
return {
|
||||||
access_token: token,
|
access_token: token,
|
||||||
exp: expiration.getTime(),
|
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 { LoginAuthGuard } from './guards/login-auth.guard';
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
import { UsersService } from 'src/users/users.service';
|
import { UsersService } from 'src/users/users.service';
|
||||||
@@ -6,10 +6,18 @@ import { RegisterUserDto } from './dto/register-user.dto';
|
|||||||
import { Response } from 'express';
|
import { Response } from 'express';
|
||||||
import { JwtRefreshGuard } from './guards/jwt-refresh.guard';
|
import { JwtRefreshGuard } from './guards/jwt-refresh.guard';
|
||||||
import { OfflineGuard } from './guards/offline.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')
|
@Controller('auth')
|
||||||
export class AuthController {
|
export class AuthController {
|
||||||
constructor(private auth: AuthService, private users: UsersService) { }
|
constructor(
|
||||||
|
private auth: AuthService,
|
||||||
|
private users: UsersService,
|
||||||
|
private logger: PinoLogger,
|
||||||
|
) { }
|
||||||
|
|
||||||
@UseGuards(LoginAuthGuard)
|
@UseGuards(LoginAuthGuard)
|
||||||
@Post('login')
|
@Post('login')
|
||||||
@@ -17,8 +25,28 @@ export class AuthController {
|
|||||||
@Request() req,
|
@Request() req,
|
||||||
@Res({ passthrough: true }) response: Response,
|
@Res({ passthrough: true }) response: Response,
|
||||||
) {
|
) {
|
||||||
|
let data: AuthenticationDto | null;
|
||||||
try {
|
try {
|
||||||
const data = await this.auth.login(req.user);
|
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) {
|
||||||
|
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 while logging in.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
response.cookie('Authentication', data.access_token, {
|
response.cookie('Authentication', data.access_token, {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
@@ -32,19 +60,40 @@ export class AuthController {
|
|||||||
expires: new Date(data.refresh_exp),
|
expires: new Date(data.refresh_exp),
|
||||||
});
|
});
|
||||||
|
|
||||||
return { success: true };
|
this.logger.info({
|
||||||
} catch (err) {
|
class: AuthController.name,
|
||||||
console.log(err);
|
method: this.login.name,
|
||||||
|
user: req.user,
|
||||||
|
access_token: data.access_token,
|
||||||
|
refresh_token: data.refresh_token,
|
||||||
|
msg: 'User logged in.',
|
||||||
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: true,
|
||||||
error_message: 'Something went wrong.',
|
};
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@UseGuards(LoginAuthGuard)
|
@UseGuards(JwtAccessGuard)
|
||||||
@Post('logout')
|
@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();
|
return req.logout();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,6 +112,13 @@ export class AuthController {
|
|||||||
secure: true,
|
secure: true,
|
||||||
expires: new Date(data.exp),
|
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) {
|
if (data.refresh_token != refresh_token) {
|
||||||
response.cookie('Refresh', data.refresh_token, {
|
response.cookie('Refresh', data.refresh_token, {
|
||||||
@@ -70,15 +126,28 @@ export class AuthController {
|
|||||||
secure: true,
|
secure: true,
|
||||||
expires: new Date(data.refresh_exp),
|
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 };
|
return { success: true };
|
||||||
} catch (err) {
|
} 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 {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error_message: 'Something went wrong.',
|
error_message: 'Something went wrong.',
|
||||||
}
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,44 +158,73 @@ export class AuthController {
|
|||||||
@Res({ passthrough: true }) response: Response,
|
@Res({ passthrough: true }) response: Response,
|
||||||
@Body() body: RegisterUserDto,
|
@Body() body: RegisterUserDto,
|
||||||
) {
|
) {
|
||||||
|
let user: UserEntity | null;
|
||||||
|
let data: AuthenticationDto | null;
|
||||||
try {
|
try {
|
||||||
const { user_login, user_name, password } = body;
|
const { user_login, user_name, password } = body;
|
||||||
if (!user_login) {
|
user = await this.users.register(user_login.toLowerCase(), user_name, password, true);
|
||||||
return { success: false, error_message: 'No user login found.' };
|
this.logger.info({
|
||||||
|
class: AuthController.name,
|
||||||
|
method: this.register.name,
|
||||||
|
user: req.user,
|
||||||
|
msg: 'User registered',
|
||||||
|
});
|
||||||
|
} catch (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.',
|
||||||
|
};
|
||||||
}
|
}
|
||||||
if (!user_name) {
|
|
||||||
return { success: false, error_message: 'No user name found.' };
|
|
||||||
}
|
}
|
||||||
if (!password) {
|
this.logger.error({
|
||||||
return { success: false, error_message: 'No password found.' };
|
class: AuthController.name,
|
||||||
}
|
method: this.register.name,
|
||||||
if (user_name.length < 1) {
|
user: req.user,
|
||||||
return { success: false, error_message: 'Name is too short.' };
|
msg: 'Failed to register.',
|
||||||
}
|
error: err,
|
||||||
if (user_name.length > 32) {
|
});
|
||||||
return { success: false, error_message: 'Name is too long.' };
|
return {
|
||||||
}
|
success: false,
|
||||||
if (user_login.length < 3) {
|
error_message: 'Something went wrong when creating user.',
|
||||||
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);
|
try {
|
||||||
if (!user) {
|
data = await this.auth.login(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) {
|
if (!data.access_token || !data.refresh_token || !data.refresh_exp) {
|
||||||
return { success: false, error_message: 'Something went wrong while logging in.' };
|
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, {
|
response.cookie('Authentication', data.access_token, {
|
||||||
@@ -143,13 +241,6 @@ export class AuthController {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
}
|
};
|
||||||
} catch (err) {
|
|
||||||
console.log('AuthController', err);
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
error_message: 'Something went wrong.',
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -8,6 +8,7 @@ import { UUID } from 'crypto';
|
|||||||
import { UserEntity } from 'src/users/users.entity';
|
import { UserEntity } from 'src/users/users.entity';
|
||||||
import { Repository } from 'typeorm';
|
import { Repository } from 'typeorm';
|
||||||
import { AuthRefreshTokenEntity } from './entities/auth.refresh-token.entity';
|
import { AuthRefreshTokenEntity } from './entities/auth.refresh-token.entity';
|
||||||
|
import { PinoLogger } from 'nestjs-pino';
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AuthRefreshService {
|
export class AuthRefreshService {
|
||||||
@@ -15,7 +16,8 @@ export class AuthRefreshService {
|
|||||||
private jwts: JwtService,
|
private jwts: JwtService,
|
||||||
private config: ConfigService,
|
private config: ConfigService,
|
||||||
@InjectRepository(AuthRefreshTokenEntity)
|
@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;
|
let expiration: Date | null = null;
|
||||||
if (refreshToken) {
|
if (refreshToken) {
|
||||||
const token = await this.get(refreshToken, user.userId);
|
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()) {
|
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.');
|
throw new UnauthorizedException('Invalid refresh token.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,9 +55,25 @@ export class AuthRefreshService {
|
|||||||
// - token has reached expiration threshold;
|
// - token has reached expiration threshold;
|
||||||
// - token has expired.
|
// - token has expired.
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const threshhold = parseInt(this.config.getOrThrow('AUTH_JWT_REFRESH_TOKEN_EXPIRATION_THRESHHOLD_MS'));
|
const threshhold = parseInt(this.config.getOrThrow<string>('AUTH_JWT_REFRESH_TOKEN_EXPIRATION_THRESHHOLD_MS'));
|
||||||
if (!refreshToken || !expiration || now.getTime() - expiration.getTime() > threshhold) {
|
if (!refreshToken || now.getTime() - expiration.getTime() > threshhold) {
|
||||||
const limit = parseInt(this.config.getOrThrow('AUTH_JWT_REFRESH_TOKEN_EXPIRATION_MS'));
|
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();
|
expiration = moment(now).add(limit, 'ms').toDate();
|
||||||
refreshToken = await this.jwts.signAsync(
|
refreshToken = await this.jwts.signAsync(
|
||||||
{
|
{
|
||||||
@@ -48,15 +84,33 @@ export class AuthRefreshService {
|
|||||||
exp: expiration.getTime(),
|
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({
|
this.authRefreshTokenRepository.insert({
|
||||||
tokenHash: refreshToken,
|
tokenHash: refreshToken,
|
||||||
userId: user.userId,
|
userId: user.userId,
|
||||||
exp: expiration
|
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 {
|
return {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export class AuthService {
|
|||||||
) { }
|
) { }
|
||||||
|
|
||||||
|
|
||||||
async login(user: UserEntity) {
|
async login(user: UserEntity): Promise<AuthenticationDto> {
|
||||||
return this.renew(user, null);
|
return this.renew(user, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -27,7 +27,7 @@ export class AuthService {
|
|||||||
async renew(
|
async renew(
|
||||||
user: UserEntity,
|
user: UserEntity,
|
||||||
refresh_token: string
|
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_data = await this.refreshTokens.generate(user, refresh_token);
|
||||||
const new_refresh_token = new_refresh_data.refresh_token;
|
const new_refresh_token = new_refresh_data.refresh_token;
|
||||||
const new_refresh_exp = new_refresh_data.exp;
|
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 {
|
export class RegisterUserDto {
|
||||||
@IsNotEmpty()
|
@IsString()
|
||||||
|
@Length(3, 16)
|
||||||
|
@IsAlphanumeric()
|
||||||
readonly user_login: string;
|
readonly user_login: string;
|
||||||
|
|
||||||
@IsNotEmpty()
|
@IsString()
|
||||||
|
@Length(1, 32)
|
||||||
readonly user_name: string;
|
readonly user_name: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
|
@Length(12, 64)
|
||||||
|
@MinLength(12)
|
||||||
|
@MaxLength(64)
|
||||||
readonly password: string;
|
readonly password: string;
|
||||||
}
|
}
|
||||||
@@ -12,8 +12,8 @@ export class JwtOptions implements JwtOptionsFactory {
|
|||||||
createJwtOptions(): Promise<JwtModuleOptions> | JwtModuleOptions {
|
createJwtOptions(): Promise<JwtModuleOptions> | JwtModuleOptions {
|
||||||
return {
|
return {
|
||||||
signOptions: {
|
signOptions: {
|
||||||
issuer: this.config.getOrThrow('AUTH_JWT_ISSUER'),
|
issuer: this.config.getOrThrow<string>('AUTH_JWT_ISSUER'),
|
||||||
audience: this.config.getOrThrow('AUTH_JWT_AUDIENCE'),
|
audience: this.config.getOrThrow<string>('AUTH_JWT_AUDIENCE'),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,9 +12,9 @@ export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'jwt-refresh'
|
|||||||
super({
|
super({
|
||||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||||
ignoreExpiration: false,
|
ignoreExpiration: false,
|
||||||
secretOrKey: config.get('AUTH_JWT_REFRESH_SECRET'),
|
secretOrKey: config.get<string>('AUTH_JWT_REFRESH_SECRET'),
|
||||||
issuer: config.getOrThrow('AUTH_JWT_ISSUER'),
|
issuer: config.getOrThrow<string>('AUTH_JWT_ISSUER'),
|
||||||
audience: config.getOrThrow('AUTH_JWT_AUDIENCE'),
|
audience: config.getOrThrow<string>('AUTH_JWT_AUDIENCE'),
|
||||||
passReqToCallback: true,
|
passReqToCallback: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,15 +11,14 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
|||||||
super({
|
super({
|
||||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||||
ignoreExpiration: false,
|
ignoreExpiration: false,
|
||||||
secretOrKey: config.getOrThrow('AUTH_JWT_ACCESS_TOKEN_SECRET'),
|
secretOrKey: config.getOrThrow<string>('AUTH_JWT_ACCESS_TOKEN_SECRET'),
|
||||||
issuer: config.getOrThrow('AUTH_JWT_ISSUER'),
|
issuer: config.getOrThrow<string>('AUTH_JWT_ISSUER'),
|
||||||
audience: config.getOrThrow('AUTH_JWT_AUDIENCE'),
|
audience: config.getOrThrow<string>('AUTH_JWT_AUDIENCE'),
|
||||||
passReqToCallback: true,
|
passReqToCallback: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async validate(req: Request, payload: any) {
|
async validate(req: Request, payload: any) {
|
||||||
console.log('jwt payload', payload);
|
|
||||||
const user = await this.users.findById(payload.sub);
|
const user = await this.users.findById(payload.sub);
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new UnauthorizedException();
|
throw new UnauthorizedException();
|
||||||
|
|||||||
@@ -12,11 +12,11 @@ export class DatabaseOptions implements TypeOrmOptionsFactory {
|
|||||||
createTypeOrmOptions(): TypeOrmModuleOptions | Promise<TypeOrmModuleOptions> {
|
createTypeOrmOptions(): TypeOrmModuleOptions | Promise<TypeOrmModuleOptions> {
|
||||||
return {
|
return {
|
||||||
type: "postgres",
|
type: "postgres",
|
||||||
host: this.config.getOrThrow('DATABASE_HOST'),
|
host: this.config.getOrThrow<string>('DATABASE_HOST'),
|
||||||
port: parseInt(this.config.getOrThrow('DATABASE_PORT'), 10),
|
port: parseInt(this.config.getOrThrow<string>('DATABASE_PORT'), 10),
|
||||||
username: this.config.getOrThrow('DATABASE_USERNAME'),
|
username: this.config.getOrThrow<string>('DATABASE_USERNAME'),
|
||||||
password: this.config.getOrThrow('DATABASE_PASSWORD'),
|
password: this.config.getOrThrow<string>('DATABASE_PASSWORD'),
|
||||||
database: this.config.getOrThrow('DATABASE_NAME'),
|
database: this.config.getOrThrow<string>('DATABASE_NAME'),
|
||||||
|
|
||||||
entities: [__dirname + '/../**/*.entity.js'],
|
entities: [__dirname + '/../**/*.entity.js'],
|
||||||
logging: true,
|
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 * as cookieParser from 'cookie-parser';
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
|
import { Logger, LoggerErrorInterceptor } from 'nestjs-pino';
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule);
|
const app = await NestFactory.create(AppModule, { bufferLogs: true });
|
||||||
app.use(cookieParser());
|
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);
|
await app.listen(process.env.PORT ?? 3001);
|
||||||
}
|
}
|
||||||
bootstrap();
|
bootstrap();
|
||||||
|
|||||||
Reference in New Issue
Block a user