Feat/auth#13
Open
itssimmons wants to merge 15 commits intomainfrom
Open
Conversation
… refresh token Agent-Logs-Url: https://github.com/dojoh-dev/api/sessions/e51ba94d-b8f5-4c51-8fb6-1f6c2da7b64f Co-authored-by: itssimmons <62354548+itssimmons@users.noreply.github.com>
…on native login Agent-Logs-Url: https://github.com/dojoh-dev/api/sessions/f56905a4-f168-4cf2-9242-dd5ea3a6ad28 Co-authored-by: itssimmons <62354548+itssimmons@users.noreply.github.com>
Agent-Logs-Url: https://github.com/dojoh-dev/api/sessions/2b746871-9486-4932-89f8-036a9433bb65 Co-authored-by: itssimmons <62354548+itssimmons@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
This PR introduces a revamped authentication system, adding local signup/login with Redis-backed JWT sessions and new OAuth flows (Google/GitHub/Discord), plus related infra/config updates (cookies, CORS, Prisma schema, env/compose).
Changes:
- Added JWT session middleware, cookie handling, and custom CORS handling.
- Implemented local auth endpoints (signup/local login/refresh/revoke/logout) and OAuth routes/controllers for Google/GitHub/Discord.
- Extended Prisma schema/migration to support OAuth accounts, updated i18n namespaces, and added dev Docker compose/Dockerfile.
Reviewed changes
Copilot reviewed 43 out of 51 changed files in this pull request and generated 18 comments.
Show a summary per file
| File | Description |
|---|---|
| shared/utils/crypto.ts | Adds PKCE helper utilities for OAuth flows. |
| routes/v1.ts | Registers new OAuth router under v1. |
| plugins/jwt.ts | Adds JWT session validation middleware backed by Redis. |
| plugins/i18n.ts | Extends request decorations (t/language) and tweaks plugin wrapper. |
| plugins/cors.ts | Adds custom CORS preHandler with allowlist. |
| package.json | Adds deps for cookies, bcrypt, and Google APIs. |
| bun.lock | Locks newly added dependencies. |
| modules/users/models/User.d.ts | Introduces a shared User interface used by sessions. |
| modules/auth/types/jwt.d.ts | Updates JWT subject/payload typing for access/refresh tokens. |
| modules/auth/serivces/jwt.service.ts | Adds centralized access/refresh token creation. |
| modules/auth/serivces/google.service.ts | Adds placeholder Google OAuth service namespace. |
| modules/auth/schemas/signup.schema.ts | Adds signup validation (nickname rules + i18n errors). |
| modules/auth/schemas/signin.schema.ts | Adds sign-in schema (currently unused). |
| modules/auth/schemas/refresh-token.schema.ts | Exports refresh token schema as named export. |
| modules/auth/schemas/index.schema.ts | Centralizes auth schema exports. |
| modules/auth/schemas/google-user.schema.ts | Adds Google user payload validation. |
| modules/auth/schemas/github-user.schema.ts | Adds GitHub user payload validation. |
| modules/auth/schemas/discord-user.schema.ts | Adds Discord user payload validation. |
| modules/auth/schemas/credential.schema.ts | Updates credential schema to accept email or nickname (i18n rules). |
| modules/auth/routes/oauth.router.ts | Adds OAuth endpoints for providers. |
| modules/auth/routes/index.router.ts | Reworks auth routes and introduces protected scope via JWT plugin. |
| modules/auth/models/Session.d.ts | Defines Redis-stored session shape (including provider tokens). |
| modules/auth/exceptions/unauthorized.exception.ts | Removes module-local UnauthorizedError (moved to shared exceptions). |
| modules/auth/exceptions/notfound.exception.ts | Removes module-local NotFoundError (moved to shared exceptions). |
| modules/auth/controllers/index.controller.ts | Implements signup/login/refresh/logout/revoke using Prisma + Redis sessions. |
| modules/auth/controllers/google-oauth.controller.ts | Implements Google OAuth redirect/callback and session creation. |
| modules/auth/controllers/github-oauth.controller.ts | Implements GitHub OAuth redirect/callback with PKCE and session creation. |
| modules/auth/controllers/discord-oauth.controller.ts | Implements Discord OAuth redirect/callback and session creation. |
| locales/pt-BR/zod.json | Adds zod namespace file (empty). |
| locales/fr-FR/zod.json | Adds zod namespace file (empty). |
| locales/es-ES/zod.json | Adds ES translation for nickname validation rules. |
| locales/es-ES/errors.json | Adds ES error translation entry. |
| locales/en-US/zod.json | Adds EN translation for nickname validation rules. |
| index.ts | Registers CORS + cookies and mounts v1 routes under /1. |
| exceptions/unauthorized.exception.ts | Adds shared UnauthorizedError with statusCode. |
| exceptions/notfound.exception.ts | Adds shared NotFoundError with statusCode. |
| exceptions/index.exception.ts | Adds shared exception barrel exports. |
| exceptions/conflict.exception.ts | Adds shared ConflictError with statusCode. |
| database/redis/client.ts | Renames/normalizes Redis client/config extraction. |
| database/prisma/schema.prisma | Adds OAuthAccount relations/fields and adjusts image/user relations. |
| database/prisma/migrations/20260507020539/migration.sql | Updates migration for new OAuth fields/constraints and onDelete behavior. |
| config/jwt.ts | Fixes JWT expirations to be relative seconds. |
| config/i18n.ts | Adds zod namespace and types the init config. |
| config/database.ts | Changes default DB/Redis env defaults (empty strings). |
| compose.yml | Adds dev compose stack (API + Postgres + Redis). |
| ci/Dockerfile.dev | Adds dev Dockerfile including Prisma generate step. |
| @types/i18next.d.ts | Adds lightweight i18next type shim for schema factories. |
| .env.example | Updates env example with Postgres/Redis and OAuth vars. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
+12
to
+17
| const origin = req.headers.origin; | ||
| const envName = env("NODE_ENV", "development"); | ||
|
|
||
| // Allow browser origins | ||
| if (origin && allowedDomains[envName].includes(origin)) { | ||
| reply.header("Access-Control-Allow-Origin", origin); |
Comment on lines
+10
to
+14
|
|
||
| // Protected routes | ||
| await f.register((f) => { | ||
| f.register(jwtPlugin); | ||
| f.post("/refresh", AuthController.refresh); |
Comment on lines
+14
to
+24
| const authHeader = req.headers.authorization; | ||
|
|
||
| if (!authHeader) { | ||
| throw new jwt.JsonWebTokenError(req.t("Header missing")); | ||
| } | ||
|
|
||
| const token = authHeader.split(" ")[1]; | ||
|
|
||
| if (!token) { | ||
| throw new jwt.JsonWebTokenError(req.t("No token provided")); | ||
| } |
Comment on lines
+47
to
+50
| if (e instanceof jwt.JsonWebTokenError) { | ||
| return reply | ||
| .status(403) | ||
| .send({ error: req.t("Unauthorized"), details: e.message }); |
Comment on lines
+103
to
+120
| avatar: { | ||
| upsert: { | ||
| update: { | ||
| original_url: googleUser.picture as string, | ||
| mime_type: "image/jpeg", | ||
| file_size: 0, | ||
| height_original: 0, | ||
| width_original: 0, | ||
| }, | ||
| create: { | ||
| original_url: googleUser.picture as string, | ||
| mime_type: "image/jpeg", | ||
| file_size: 0, | ||
| height_original: 0, | ||
| width_original: 0, | ||
| }, | ||
| }, | ||
| }, |
Comment on lines
+20
to
+28
| GOOGLE_REDIRECT_URI=https://example.com/auth/google/callback | ||
|
|
||
| GITHUB_CLIENT_ID= | ||
| GITHUB_CLIENT_SECRET= | ||
| GITHUB_REDIRECT_URI=https://example.com/auth/google/callback | ||
|
|
||
| DISCORD_CLIENT_ID= | ||
| DISCORD_CLIENT_SECRET= | ||
| DISCORD_REDIRECT_URI=https://example.com/auth/github/callback |
| networks: | ||
| - dojoh-net | ||
| volumes: | ||
| - pg_data:/var/lib/postgresql/18/docker |
| throw new UnauthorizedError(req.t("Unauthorized")); | ||
| } | ||
|
|
||
| // TODO: revoke thrid party sessions if the user logged in with OAuth provider (google, github, discord, etc) |
| : null, | ||
| provider_metadata: { | ||
| email: discordEmail, | ||
| lng: discordUser.locale, |
| "Invalid credentials": "Credenciales inválidas", | ||
| "Server error": "Error del servidor" | ||
| "Server error": "Error del servidor", | ||
| "Email already in use": "El correo electrónico ya está en uso" |
|
🚀 Preview deployed: https://api-preview-13-nnratsflva-uc.a.run.app |
|
🚀 Preview deployed: https://api-preview-13-nnratsflva-uc.a.run.app |
Comment on lines
+10
to
+14
|
|
||
| // Protected routes | ||
| await f.register((f) => { | ||
| f.register(jwtPlugin); | ||
| f.post("/refresh", AuthController.refresh); |
Comment on lines
+14
to
+24
| const authHeader = req.headers.authorization; | ||
|
|
||
| if (!authHeader) { | ||
| throw new jwt.JsonWebTokenError(req.t("Header missing")); | ||
| } | ||
|
|
||
| const token = authHeader.split(" ")[1]; | ||
|
|
||
| if (!token) { | ||
| throw new jwt.JsonWebTokenError(req.t("No token provided")); | ||
| } |
Comment on lines
+47
to
+51
| if (e instanceof jwt.JsonWebTokenError) { | ||
| return reply | ||
| .status(403) | ||
| .send({ error: req.t("Unauthorized"), details: e.message }); | ||
| } |
Comment on lines
+19
to
+31
| const origin = req.headers.origin; | ||
| const envName = env("NODE_ENV", "development"); | ||
|
|
||
| // Allow browser origins | ||
| const allowed = | ||
| origin && | ||
| allowedDomains[envName].some((entry) => { | ||
| if (entry instanceof RegExp) { | ||
| return entry.test(origin); | ||
| } | ||
|
|
||
| return entry === origin; | ||
| }); |
|
|
||
| refresh: { | ||
| expiresIn: Math.floor(Date.now() / 1000) + 7 * 24 * 60 * 60, // 7 days in seconds | ||
| expiresIn: 60 * 60 * 24, // 1 day in seconds |
Comment on lines
+24
to
+28
| GITHUB_REDIRECT_URI=https://example.com/auth/google/callback | ||
|
|
||
| DISCORD_CLIENT_ID= | ||
| DISCORD_CLIENT_SECRET= | ||
| DISCORD_REDIRECT_URI=https://example.com/auth/github/callback |
| networks: | ||
| - dojoh-net | ||
| volumes: | ||
| - pg_data:/var/lib/postgresql/18/docker |
Comment on lines
+1
to
+7
| import crypto from "node:crypto"; | ||
|
|
||
| import jwt from "jsonwebtoken"; | ||
|
|
||
| import jwtConfig from "@/config/jwt"; | ||
|
|
||
| export const createTokens = (sub: unknown, version: number = 1) => { |
Comment on lines
+141
to
+144
| if (!user.password) { | ||
| throw new UnauthorizedError(req.t("Invalid credentials")); | ||
| } | ||
|
|
| throw new UnauthorizedError(req.t("Unauthorized")); | ||
| } | ||
|
|
||
| // TODO: revoke thrid party sessions if the user logged in with OAuth provider (google, github, discord, etc) |
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Pull Request Template
📌 Description
Provide a clear and concise description of what this PR does.
🔧 Type of Change
Select all that apply:
🧪 How Has This Been Tested?
Describe the testing strategy:
Steps to reproduce/test:
1.
2.
3.
📂 Related Issues
Link any related issues:
If yes, describe the impact and migration steps:
📸 Screenshots / Logs (if applicable)
Add screenshots, request/response examples, or logs if helpful.
✅ Checklist
Ensure your PR meets the following:
💬 Additional Notes
Anything else reviewers should know.