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,140 @@
CREATE SCHEMA IF NOT EXISTS seshat;
SET
search_path TO seshat;
DROP TABLE IF EXISTS api_keys;
DROP TABLE IF EXISTS book_statuses;
DROP TABLE IF EXISTS book_origins;
DROP TABLE IF EXISTS refresh_tokens;
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS books;
DROP TABLE IF EXISTS series;
CREATE TABLE
series (
series_id uuid DEFAULT gen_random_uuid (),
-- 3rd party used to fetch the data for this series.
provider varchar(6) NOT NULL,
provider_series_id text,
series_title text NOT NULL,
date_added timestamp default NULL,
PRIMARY KEY (series_id)
);
ALTER TABLE series
ALTER COLUMN date_added
SET DEFAULT now ();
CREATE INDEX series_series_title_idx ON series USING HASH (series_title);
CREATE TABLE
books (
book_id uuid DEFAULT gen_random_uuid (),
series_id uuid,
provider_book_id text NOT NULL,
isbn varchar(16),
book_title text NOT NULL,
book_desc text NOT NULL,
book_volume integer,
date_released timestamp default NULL,
date_added timestamp default NULL,
PRIMARY KEY (book_id),
FOREIGN KEY (series_id) REFERENCES series (series_id)
);
ALTER TABLE books
ALTER COLUMN date_released
SET DEFAULT now ();
ALTER TABLE books
ALTER COLUMN date_added
SET DEFAULT now ();
CREATE INDEX books_series_id_idx ON books USING HASH (series_id);
CREATE INDEX books_isbn_idx ON books USING HASH (isbn);
CREATE INDEX books_book_title_idx ON books USING HASH (book_title);
CREATE TABLE
book_origins (
book_id uuid,
origin_type varchar(8),
origin_value text,
PRIMARY KEY (book_id, origin_type, origin_value)
);
CREATE INDEX book_origins_book_id_idx ON book_origins USING HASH (book_id);
CREATE INDEX book_origins_type_value_idx ON book_origins (origin_type, origin_value);
CREATE TABLE
users (
user_id uuid DEFAULT gen_random_uuid (),
user_login varchar(24),
user_name varchar(64),
password text NOT NULL,
salt bigint NOT NULL,
is_admin boolean NOT NULL,
date_joined timestamp default NULL,
PRIMARY KEY (user_id),
UNIQUE (user_login)
);
ALTER TABLE users
ALTER COLUMN date_joined
SET DEFAULT now ();
CREATE INDEX users_user_login_idx ON users USING HASH (user_login);
CREATE TABLE
refresh_tokens (
user_id uuid NOT NULL,
refresh_token_hash text NOT NULL,
exp timestamp NOT NULL,
PRIMARY KEY (user_id, refresh_token_hash)
);
CREATE TABLE
book_statuses (
user_id uuid,
book_id uuid,
state varchar(12),
date_added timestamp default NULL,
date_modified timestamp default NULL,
PRIMARY KEY (user_id, book_id),
FOREIGN KEY (user_id) REFERENCES users (user_id),
FOREIGN KEY (book_id) REFERENCES books (book_id)
);
ALTER TABLE book_statuses
ALTER COLUMN date_added
SET DEFAULT now ();
ALTER TABLE book_statuses
ALTER COLUMN date_modified
SET DEFAULT now ();
CREATE INDEX book_statuses_user_id_login_idx ON users USING HASH (user_id);
CREATE TABLE
api_keys (
user_id uuid,
api_key char(64),
date_added timestamp default NULL,
PRIMARY KEY (user_id, api_key),
FOREIGN KEY (user_id) REFERENCES users (user_id)
);
ALTER TABLE api_keys
ALTER COLUMN date_added
SET DEFAULT now ();
CREATE INDEX api_keys_api_key_idx ON api_keys USING HASH (api_key);

View File

@ -0,0 +1,25 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

56
backend/nestjs-seshat-api/.gitignore vendored Normal file
View File

@ -0,0 +1,56 @@
# compiled output
/dist
/node_modules
/build
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# temp directory
.temp
.tmp
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

View File

@ -0,0 +1,99 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Project setup
```bash
$ npm install
```
## Compile and run the project
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Run tests
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Deployment
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
```bash
$ npm install -g mau
$ mau deploy
```
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
## Resources
Check out a few resources that may come in handy when working with NestJS:
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).

View File

@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

10114
backend/nestjs-seshat-api/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,86 @@
{
"name": "nestjs-seshat-api",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^4.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/jwt": "^11.0.0",
"@nestjs/passport": "^11.0.5",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/typeorm": "^11.0.0",
"argon2": "^0.41.1",
"class-validator": "^0.14.1",
"cookie-parser": "^1.4.7",
"moment": "^2.30.1",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"passport-local": "^1.0.0",
"pg": "^8.13.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
"typeorm": "^0.3.20",
"typeorm-naming-strategies": "^4.1.0"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
"@nestjs/schematics": "^10.0.0",
"@nestjs/testing": "^10.0.0",
"@types/cookie-parser": "^1.4.8",
"@types/express": "^5.0.0",
"@types/jest": "^29.5.2",
"@types/node": "^20.3.1",
"@types/passport-jwt": "^4.0.1",
"@types/passport-local": "^1.0.38",
"@types/supertest": "^6.0.0",
"@typescript-eslint/eslint-plugin": "^8.0.0",
"@typescript-eslint/parser": "^8.0.0",
"eslint": "^8.0.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"jest": "^29.5.0",
"prettier": "^3.0.0",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.1.0",
"ts-loader": "^9.4.3",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.1.3"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

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

View File

@ -0,0 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

View File

@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

View File

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}