Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: user auth #6

Merged
merged 19 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
da13ad3
feat: implement user authentication and authorization
typeWolffo Jul 9, 2024
d899d9c
feat: add user management and access control
typeWolffo Jul 9, 2024
a16c5f9
feat: implement user data management
typeWolffo Jul 9, 2024
69c28c6
feat: improve error handling and remove unnecessary logs
typeWolffo Jul 9, 2024
a43add0
feat: add uuid dependency and setup validation
typeWolffo Jul 9, 2024
78b96df
feat: add credentials table and user_id foreign key
typeWolffo Jul 10, 2024
a9b5a7a
refactor: update JwtModule configuration
typeWolffo Jul 10, 2024
7ec41b7
fix: update route endpoints in users controller
typeWolffo Jul 10, 2024
0755a18
feat: add token service for setting and clearing cookies
typeWolffo Jul 10, 2024
a2039e0
feat: add JwtAuthGuard to AppModule and use Public decorator
typeWolffo Jul 10, 2024
083da80
refactor: remove JwtAuthGuard usage from controllers
typeWolffo Jul 10, 2024
28b97ca
refactor: remove JwtAuthGuard usage from UsersController methods
typeWolffo Jul 10, 2024
ff805e4
refactor: update JwtAuthGuard constructor and canActivate method
typeWolffo Jul 10, 2024
2c40cbe
feat: implement JWT secret configuration
typeWolffo Jul 11, 2024
5eac8cc
refactor: update response schemas in AuthController
typeWolffo Jul 11, 2024
50c440f
chore: remove unused code and imports
typeWolffo Jul 11, 2024
086bf94
fix: update user deletion logic in UsersService
typeWolffo Jul 11, 2024
26173dc
feat: add Bearer support
typeWolffo Jul 11, 2024
03fcabb
feat: tests (unit, e2e) (#7)
typeWolffo Jul 18, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/common_nestjs_remix/apps/api/.env.example
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
DATABASE_URL="postgres://postgres:guidebook@localhost:5432/guidebook"
JWT_SECRET=
REFRESH_SECRET=
26 changes: 15 additions & 11 deletions examples/common_nestjs_remix/apps/api/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,29 @@
module.exports = {
parser: '@typescript-eslint/parser',
parser: "@typescript-eslint/parser",
parserOptions: {
project: 'tsconfig.json',
project: "tsconfig.json",
tsconfigRootDir: __dirname,
sourceType: 'module',
sourceType: "module",
},
plugins: ['@typescript-eslint/eslint-plugin'],
plugins: ["@typescript-eslint/eslint-plugin"],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended",
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
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',
"@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",
"@typescript-eslint/no-unused-vars": [
"error",
{ argsIgnorePattern: "^_", varsIgnorePattern: "^_" },
],
},
};
18 changes: 17 additions & 1 deletion examples/common_nestjs_remix/apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,41 @@
"@nestjs/config": "^3.2.3",
"@nestjs/core": "^10.0.0",
"@nestjs/cqrs": "^10.2.7",
"@nestjs/jwt": "^10.2.0",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/swagger": "^7.4.0",
"@sinclair/typebox": "^0.32.34",
"add": "^2.0.6",
"bcrypt": "^5.1.1",
"cookie-parser": "^1.4.6",
"drizzle-kit": "^0.22.8",
"drizzle-orm": "^0.31.2",
"drizzle-typebox": "^0.1.1",
"lodash": "^4.17.21",
"nestjs-typebox": "3.0.0-next.8",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"passport-local": "^1.0.0",
"postgres": "^3.4.4",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
"rxjs": "^7.8.1",
"uuid": "^10.0.0"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
"@nestjs/schematics": "^10.0.0",
"@nestjs/testing": "^10.0.0",
"@types/bcrypt": "^5.0.2",
"@types/cookie-parser": "^1.4.7",
"@types/express": "^4.17.17",
"@types/jest": "^29.5.2",
"@types/lodash": "^4.17.6",
"@types/node": "^20.3.1",
"@types/passport-jwt": "^4.0.1",
"@types/passport-local": "^1.0.38",
"@types/supertest": "^6.0.0",
"@types/uuid": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"eslint": "^8.42.0",
Expand Down
34 changes: 30 additions & 4 deletions examples/common_nestjs_remix/apps/api/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@ import { DrizzlePostgresModule } from "@knaadh/nestjs-drizzle-postgres";
import database from "./common/configuration/database";
import { ConfigModule, ConfigService } from "@nestjs/config";
import * as schema from "./storage/schema";
import { ManagementModule } from "./management/management.module";
import { AuthModule } from "./auth/auth.module";
import { UsersModule } from "./users/users.module";
import { JwtModule } from "@nestjs/jwt";
import jwtConfig from "./common/configuration/jwt";
import { APP_GUARD } from "@nestjs/core";
import { JwtAuthGuard } from "./utils/guards/jwt-auth-guard";

@Module({
imports: [
ConfigModule.forRoot({
load: [database],
load: [database, jwtConfig],
isGlobal: true,
}),
DrizzlePostgresModule.registerAsync({
Expand All @@ -25,9 +30,30 @@ import { ManagementModule } from "./management/management.module";
},
inject: [ConfigService],
}),
ManagementModule,
JwtModule.registerAsync({
useFactory(configService: ConfigService) {
return {
secret: configService.get<string>("jwt.secret")!,
signOptions: {
expiresIn: configService.get<string>(
"JWT_EXPIRATION_TIME",
"15min",
),
},
};
},
inject: [ConfigService],
global: true,
}),
AuthModule,
UsersModule,
],
controllers: [],
providers: [],
providers: [
{
provide: APP_GUARD,
useClass: JwtAuthGuard,
},
],
})
export class AppModule {}
112 changes: 112 additions & 0 deletions examples/common_nestjs_remix/apps/api/src/auth/api/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import {
Body,
Controller,
Post,
Req,
Res,
UnauthorizedException,
UseGuards,
} from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
import { Static, Type } from "@sinclair/typebox";
import { Request, Response } from "express";
import { Validate } from "nestjs-typebox";
import {
baseResponse,
BaseResponse,
nullResponse,
UUIDSchema,
} from "src/common";
import { CurrentUser } from "src/utils/decorators/user.decorator";
import { RefreshTokenGuard } from "src/utils/guards/refresh-token-guard";
import { AuthService } from "../auth.service";
import { accountSchema } from "../schemas/account.schema";
import {
CreateAccountBody,
createAccountSchema,
} from "../schemas/create-account.schema";
import { LoginBody, loginSchema } from "../schemas/login.schema";
import { RefreshTokenBody } from "../schemas/refresh-token.schema";
import { TokenService } from "../token.service";
import { Public } from "src/utils/decorators/public.decorator";

@Controller("auth")
export class AuthController {
constructor(
private readonly authService: AuthService,
private readonly tokenService: TokenService,
) {}

@Public()
@Post("register")
@Validate({
request: [{ type: "body", schema: createAccountSchema }],
response: baseResponse(accountSchema),
})
async register(
data: CreateAccountBody,
): Promise<BaseResponse<Static<typeof accountSchema>>> {
const account = await this.authService.register(data.email, data.password);

return new BaseResponse(account);
}

@Public()
@UseGuards(AuthGuard("local"))
@Post("login")
Comment on lines +48 to +50
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mikoscz is this global jwt auth guard properly implemented and @Public can it be used together with @UseGuards(AuthGuard("local"))?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Write some tests and we will see :D

@Validate({
request: [{ type: "body", schema: loginSchema }],
response: baseResponse(accountSchema),
})
async login(
@Body() data: LoginBody,
@Res({ passthrough: true }) response: Response,
): Promise<BaseResponse<Static<typeof accountSchema>>> {
const { accessToken, refreshToken, ...account } =
await this.authService.login(data);

this.tokenService.setTokenCookies(response, accessToken, refreshToken);

return new BaseResponse(account);
}

@Post("logout")
@Validate({
response: nullResponse(),
})
async logout(
@Res({ passthrough: true }) response: Response,
@CurrentUser() currentUser: { userId: string },
): Promise<null> {
await this.authService.logout(currentUser.userId);
this.tokenService.clearTokenCookies(response);

return null;
}

@Public()
@UseGuards(RefreshTokenGuard)
@Post("refresh")
@Validate({
request: [{ type: "body", schema: Type.Object({ id: UUIDSchema }) }],
response: nullResponse(),
})
async refreshTokens(
@Body() data: RefreshTokenBody,
@Res({ passthrough: true }) response: Response,
@Req() request: Request,
): Promise<null> {
const refreshToken = request.cookies["refresh_token"];

if (!refreshToken) {
throw new UnauthorizedException("Refresh token not found");
}

const { accessToken, refreshToken: newRefreshToken } =
await this.authService.refreshTokens(data.id, refreshToken);

this.tokenService.setTokenCookies(response, accessToken, newRefreshToken);

return null;
}
}
15 changes: 15 additions & 0 deletions examples/common_nestjs_remix/apps/api/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Module } from "@nestjs/common";
import { PassportModule } from "@nestjs/passport";
import { AuthController } from "./api/auth.controller";
import { AuthService } from "./auth.service";
import { JwtStrategy } from "./strategy/jwt.strategy";
import { LocalStrategy } from "./strategy/local.strategy";
import { TokenService } from "./token.service";

@Module({
imports: [PassportModule],
controllers: [AuthController],
providers: [AuthService, TokenService, JwtStrategy, LocalStrategy],
exports: [],
})
export class AuthModule {}
Loading