-
Couldn't load subscription status.
- Fork 0
feat: auth and Keycloak integration #1
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
Open
chawinkn
wants to merge
8
commits into
dev
Choose a base branch
from
feat/auth
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
8b6dfb7
feat: errorHandler
chawinkn c9f7335
feat: sample user schema
chawinkn cb3252e
feat: add jwt
chawinkn 75cdc46
feat: auth
chawinkn c8367fc
Update src/lib/api.ts
chawinkn e383950
Update src/middleware/errorHandler.ts
chawinkn 0df6908
remove db password and fix env
chawinkn 6aef1ca
Update src/controller/auth/authController.ts
chawinkn 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 hidden or 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,4 +1,6 @@ | ||
| DATABASE_URL="postgresql://postgres:postgres@localhost:5432/cucm25" | ||
| NODE_ENV="development" | ||
| JWT_SECRET="secret_jing_pa" | ||
| KEYCLOAK_API_BASE_URL="http://localhost:3000/realms/cucm25" | ||
| KEYCLOAK_CLIENT_ID="mango" | ||
| KEYCLOAK_CLIENT_SECRET="watermelon" |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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,40 @@ | ||
| import { AppError } from "@/types/error/AppError" | ||
| import { AuthUsecase } from "@/usecase/auth/authUsecase" | ||
| import type { Request, Response } from "express" | ||
|
|
||
| export class AuthController { | ||
| private authUsecase: AuthUsecase | ||
|
|
||
| constructor(authUsecase: AuthUsecase) { | ||
| this.authUsecase = authUsecase | ||
| } | ||
|
|
||
| async login(req: Request, res: Response): Promise<void> { | ||
| try { | ||
| const keycloakUser = await this.authUsecase.getKeycloakUser( | ||
| req.body | ||
| ) | ||
| const user = this.authUsecase.parseKeycloakUser(keycloakUser) | ||
| await this.authUsecase.register(user) | ||
|
|
||
| const token = await this.authUsecase.login(user) | ||
| res.cookie("token", token, { | ||
| maxAge: 3 * 24 * 60 * 60 * 1000, | ||
chawinkn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| httpOnly: true, | ||
| secure: process.env.NODE_ENV != "development" | ||
chawinkn marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
chawinkn marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| }) | ||
| res.status(200).json({ token }) | ||
| } catch (error) { | ||
| if (error instanceof AppError) { | ||
| res.status(error.statusCode).json({ | ||
| message: error.message, | ||
| }) | ||
| return | ||
| } | ||
| console.error("Login error:", error) | ||
| res.status(500).json({ | ||
| message: "An unexpected error occurred", | ||
| }) | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or 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,57 @@ | ||
| import { KeycloakTokenResponse, LoginRequest } from "@/types/auth/POST" | ||
| import { ApiError } from "@/types/error/ApiError" | ||
| import { AppError } from "@/types/error/AppError" | ||
|
|
||
| const KEYCLOAK_API_BASE_URL = | ||
| process.env.KEYCLOAK_API_BASE_URL || "http://localhost:3000/realms/cucm25" | ||
|
|
||
| interface ApiResponseRaw { | ||
| message?: string | ||
| error?: string | ||
| } | ||
|
|
||
| export async function getKeycloakToken(body: LoginRequest): Promise<string> { | ||
| const url = `${KEYCLOAK_API_BASE_URL}/protocol/openid-connect/token` | ||
|
|
||
| try { | ||
| const response = await fetch(url, { | ||
| method: "POST", | ||
| headers: { | ||
| "Content-Type": "application/x-www-form-urlencoded", | ||
| }, | ||
| body: new URLSearchParams({ | ||
| client_id: process.env.KEYCLOAK_CLIENT_ID!, | ||
| client_secret: process.env.KEYCLOAK_CLIENT_SECRET!, | ||
chawinkn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| username: body.username, | ||
| password: body.password, | ||
| grant_type: "password", | ||
| scope: "openid profile email", | ||
| }), | ||
| }) | ||
| if (!response.ok) { | ||
| let errorMsg = "Request failed" | ||
| if (response.body) { | ||
| try { | ||
| const responseText = await response.text() | ||
| const raw: ApiResponseRaw = JSON.parse(responseText) | ||
| errorMsg = raw.error || raw.message || errorMsg | ||
| } catch { | ||
| errorMsg = "Request failed" | ||
| } | ||
| } | ||
| throw new ApiError(errorMsg, response.status) | ||
| } | ||
|
|
||
| const data: KeycloakTokenResponse = await response.json() | ||
| return data.access_token | ||
| } catch (error) { | ||
| if (error instanceof ApiError) { | ||
| throw new AppError(error.message, error.status || 500) | ||
| } | ||
| console.error("Get Keycloak token error:", error) | ||
| throw new AppError( | ||
| error instanceof Error ? error.message : "Unknown error", | ||
| 500 | ||
| ) | ||
| } | ||
| } | ||
This file contains hidden or 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,36 @@ | ||
| import { jwtUser, verifyJwt } from "@/utils/jwt" | ||
| import { NextFunction, Request, Response } from "express" | ||
|
|
||
| declare module "express" { | ||
| interface Request { | ||
| user?: jwtUser | ||
| } | ||
| } | ||
|
|
||
| export function authMiddleware( | ||
| req: Request, | ||
| res: Response, | ||
| next: NextFunction | ||
| ): void { | ||
| const authHeader = req.headers.authorization | ||
|
|
||
| if (!authHeader || !authHeader.startsWith("Bearer ")) { | ||
| res.status(401).json({ message: "Unauthorized: Token not provided" }) | ||
| return | ||
| } | ||
|
|
||
| const token = authHeader.split(" ")[1] | ||
| if (!token) { | ||
| res.status(401).json({ message: "Unauthorized: Token not provided" }) | ||
| return | ||
| } | ||
chawinkn marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| try { | ||
| const decoded = verifyJwt(token) | ||
| req.user = decoded | ||
| next() | ||
| } catch (error) { | ||
| console.log("JWT verification error: ", error) | ||
| res.status(401).json({ message: "Unauthorized: Invalid token" }) | ||
| } | ||
| } | ||
This file contains hidden or 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,20 @@ | ||
| import { AppError } from "@/types/error/AppError" | ||
| import { NextFunction, Request, Response } from "express" | ||
|
|
||
| export function errorHandler( | ||
| err: unknown, | ||
| _req: Request, | ||
| res: Response, | ||
| _next: NextFunction | ||
| ): void { | ||
| if (err instanceof AppError) { | ||
| res.status(err.statusCode).json({ | ||
| message: err.message, | ||
| }) | ||
| return | ||
| } | ||
| console.error("Unexpected error occurred:", err) | ||
| res.status(500).json({ | ||
| message: "An unexpected error occurred", | ||
| }) | ||
| } |
This file contains hidden or 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,50 @@ | ||
| import { prisma } from "@/lib/prisma" | ||
| import { EducationLevel, RoleType, User } from "@prisma/client" | ||
|
|
||
| export interface parsedUser { | ||
| id: string | ||
| studentId: string | ||
| username: string | ||
| nickname: string | ||
| firstname: string | ||
| lastname: string | ||
| role: RoleType | ||
| educationLevel?: EducationLevel | ||
| school?: string | ||
| } | ||
|
|
||
| export class UserRepository { | ||
| async create(user: parsedUser): Promise<User> { | ||
| return await prisma.$transaction(async (tx) => { | ||
| const newUser = await tx.user.create({ | ||
| data: { | ||
| id: user.id, | ||
| studentId: user.studentId, | ||
| username: user.username, | ||
| nickname: user.nickname, | ||
| firstname: user.firstname, | ||
| lastname: user.lastname, | ||
| role: user.role, | ||
| educationLevel: user.educationLevel || null, | ||
| school: user.school || null, | ||
| }, | ||
| }) | ||
|
|
||
| return newUser | ||
| }) | ||
| } | ||
|
|
||
| async findExists( | ||
| user: Pick<parsedUser, "id" | "username"> | ||
| ): Promise<boolean> { | ||
| const existingUser = await prisma.user.findFirst({ | ||
| where: { | ||
| AND: [{ id: user.id }, { username: user.username }], | ||
| }, | ||
| }) | ||
| if (existingUser) { | ||
| return true | ||
| } | ||
| return false | ||
| } | ||
| } |
This file contains hidden or 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 { AuthController } from "@/controller/auth/authController" | ||
| import { UserRepository } from "@/repository/user/userRepository" | ||
| import { AuthUsecase } from "@/usecase/auth/authUsecase" | ||
| import { Router } from "express" | ||
|
|
||
| export default function authRouter() { | ||
| const router = Router() | ||
| const userRepository = new UserRepository() | ||
| const authUsecase = new AuthUsecase(userRepository) | ||
| const authController = new AuthController(authUsecase) | ||
|
|
||
| router.post("/login", authController.login.bind(authController)) | ||
|
|
||
| return router | ||
| } |
This file contains hidden or 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,10 +1,12 @@ | ||
| import { Router } from "express" | ||
| import mockRouter from "@/router/mock" | ||
| import authRouter from "@/router/authRouter" | ||
|
|
||
| export default function routerManager() { | ||
| const router = Router() | ||
|
|
||
| router.use("/mock", mockRouter()) | ||
| router.use("/auth", authRouter()) | ||
|
|
||
| return router | ||
| } |
This file contains hidden or 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,16 @@ | ||
| export interface LoginRequest { | ||
| username: string | ||
| password: string | ||
| } | ||
|
|
||
| export interface KeycloakTokenResponse { | ||
| access_token: string | ||
| expires_in: number | ||
| refresh_expires_in: number | ||
| refresh_token: string | ||
| token_type: string | ||
| id_token: string | ||
| "not-before-policy": number | ||
| session_state: string | ||
| scope: string | ||
| } |
This file contains hidden or 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,10 @@ | ||
| export class ApiError extends Error { | ||
| constructor( | ||
| message: string, | ||
| public status?: number, | ||
| public response?: Response | ||
| ) { | ||
| super(message) | ||
| this.name = "ApiError" | ||
| } | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.