-
Notifications
You must be signed in to change notification settings - Fork 0
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
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 d899d9c
feat: add user management and access control
typeWolffo a16c5f9
feat: implement user data management
typeWolffo 69c28c6
feat: improve error handling and remove unnecessary logs
typeWolffo a43add0
feat: add uuid dependency and setup validation
typeWolffo 78b96df
feat: add credentials table and user_id foreign key
typeWolffo a9b5a7a
refactor: update JwtModule configuration
typeWolffo 7ec41b7
fix: update route endpoints in users controller
typeWolffo 0755a18
feat: add token service for setting and clearing cookies
typeWolffo a2039e0
feat: add JwtAuthGuard to AppModule and use Public decorator
typeWolffo 083da80
refactor: remove JwtAuthGuard usage from controllers
typeWolffo 28b97ca
refactor: remove JwtAuthGuard usage from UsersController methods
typeWolffo ff805e4
refactor: update JwtAuthGuard constructor and canActivate method
typeWolffo 2c40cbe
feat: implement JWT secret configuration
typeWolffo 5eac8cc
refactor: update response schemas in AuthController
typeWolffo 50c440f
chore: remove unused code and imports
typeWolffo 086bf94
fix: update user deletion logic in UsersService
typeWolffo 26173dc
feat: add Bearer support
typeWolffo 03fcabb
feat: tests (unit, e2e) (#7)
typeWolffo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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= |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: "^_" }, | ||
], | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
112 changes: 112 additions & 0 deletions
112
examples/common_nestjs_remix/apps/api/src/auth/api/auth.controller.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | ||
@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
15
examples/common_nestjs_remix/apps/api/src/auth/auth.module.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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"))
?There was a problem hiding this comment.
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