Skip to content

refactor auth service and db id types#52

Merged
iamkabelomoobi merged 1 commit into
mainfrom
feat/refactor-auth
Jun 6, 2026
Merged

refactor auth service and db id types#52
iamkabelomoobi merged 1 commit into
mainfrom
feat/refactor-auth

Conversation

@iamkabelomoobi

@iamkabelomoobi iamkabelomoobi commented Jun 6, 2026

Copy link
Copy Markdown
Owner

Summary by Sourcery

Update authentication, notification, and infrastructure to support Better Auth string user IDs, Resend email delivery, and more robust auth request handling.

New Features:

  • Introduce Resend as a production email provider alongside existing local nodemailer setup.
  • Integrate Better Auth dash plugin and trusted origin configuration into the auth service.

Bug Fixes:

  • Ensure auth routes have dedicated body parsing and invalid JSON handling to prevent unhandled syntax errors.
  • Normalize X-Forwarded headers to handle comma-separated values from proxies.
  • Fix job repository create/update helpers to avoid leaking nested employer data into Prisma inputs.
  • Correct Redis ports and Mailhog web port mappings in development configuration and tests.

Enhancements:

  • Simplify admin registration type aliasing and tighten worker and test typings.
  • Improve logging setup by ensuring the logs directory exists before writing access logs.
  • Adjust config and interfaces to support Resend credentials and updated Redis defaults.
  • Remove noisy database connection log on server startup.

Build:

  • Add a Prisma migration to convert Users and related userId foreign keys from UUID to text for compatibility with Better Auth IDs.
  • Update npm package manager version and refresh several dependency versions including better-auth, axios, morgan, nodemailer, ioredis, eslint, and @types/node.
  • Add @better-auth/infra and resend packages as new runtime dependencies.

Tests:

  • Align e2e test setup Redis port resolution with updated Docker configuration.

refactor auth service and db id types
@sourcery-ai

sourcery-ai Bot commented Jun 6, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Refactors authentication and notification infrastructure to work with Better Auth string user IDs and the dash plugin, introduces Resend as the production email provider while keeping Nodemailer for non‑prod, tightens auth route middleware and error handling, and aligns config, Docker, and tests (notably Redis/ports) with the new setup.

Sequence diagram for auth email sending with Resend and Nodemailer

sequenceDiagram
  actor User
  participant BetterAuth as BetterAuth_callbacks
  participant NotificationUtil
  participant Resend
  participant Nodemailer as notificationLib

  User->>BetterAuth: signUp / resetPassword / etc.
  BetterAuth->>NotificationUtil: sendEmail(receiver, subject, htmlTemplate)
  alt NODE_ENV === production
    NotificationUtil->>NotificationUtil: sendWithResend(receiver, subject, htmlTemplate)
    NotificationUtil->>Resend: getResendClient().emails.send({ from, to, subject, html })
    Resend-->>NotificationUtil: { data, error }
    alt error
      NotificationUtil-->>BetterAuth: throw Error(error.message)
    else success
      NotificationUtil-->>BetterAuth: resolve
    end
  else non production
    NotificationUtil->>NotificationUtil: sendWithLocalMail(receiver, subject, htmlTemplate)
    NotificationUtil->>Nodemailer: createNodemailerTransport().sendMail(mail_options)
    Nodemailer-->>NotificationUtil: callback(error)
    alt error
      NotificationUtil-->>BetterAuth: throw error
    else success
      NotificationUtil-->>BetterAuth: resolve
    end
  end
  BetterAuth-->>User: email delivered or error
Loading

ER diagram for updated user ID text schema

erDiagram
  Users {
    TEXT id PK
  }
  Admins {
    TEXT userId FK
  }
  Candidates {
    TEXT userId FK
  }
  Employers {
    TEXT userId FK
  }
  session {
    TEXT userId FK
  }
  account {
    TEXT userId FK
  }

  Users ||--o{ Admins : userId
  Users ||--o{ Candidates : userId
  Users ||--o{ Employers : userId
  Users ||--o{ session : userId
  Users ||--o{ account : userId
Loading

Flow diagram for the /api/auth middleware pipeline

flowchart LR
  A[Incoming /api/auth request] --> B[express.json limit=JSON_BODY_LIMIT]
  B --> C[express.urlencoded extended=true limit=JSON_BODY_LIMIT]
  C --> D[authJsonParseErrorHandler]
  D --> E[normalizeForwardedAuthHeaders]
  E --> F["toNodeHandler(auth)"]
  F --> G[Auth response]
Loading

File-Level Changes

Change Details Files
Introduce Resend-based email sending in production while keeping Nodemailer for local/dev, and centralize email sender configuration.
  • Add Resend client with lazy initialization and configuration from RESEND_API_KEY/RESEND_FROM_EMAIL
  • Split email sending into Resend and local Nodemailer paths selected by NODE_ENV
  • Add shared getFromAddress helper and structured logging for both providers
  • Extend config and config interfaces to include Resend settings and sample env vars
src/utils/notification.util.ts
src/configs/config.ts
src/interfaces/configs/config.ts
.env.example
package.json
package-lock.json
Tighten auth HTTP handling (JSON parsing, error handling, proxy header normalization) and integrate Better Auth dash plugin and trusted origins.
  • Add per-/api/auth JSON and URL-encoded body parsers with size limits and a JSON syntax error handler
  • Normalize x-forwarded-proto and x-forwarded-host headers to the first value when proxies send comma-separated lists
  • Compute trustedOrigins from BETTER_AUTH_URL and CORS_ORIGINS and pass to Better Auth config
  • Add dash() plugin from @better-auth/infra
  • Make all auth-related email sending awaited and wrap welcome email in a try/catch to avoid failing the auth flow
src/middlewares/app.middleware.ts
src/libs/auth.ts
package.json
package-lock.json
Align database and ID types with Better Auth string user IDs and update Redis/Postgres config to match Docker and tests.
  • Add Prisma migration converting Users.id and all userId foreign keys to TEXT, dropping default and re-adding cascading FKs
  • Change Redis port defaults from 6379 to 6380 in config and Docker compose, and adjust test setup to probe the proper Redis port
  • Slightly adjust Postgres host port quoting and health check definitions in docker-compose
prisma/migrations/20260606124500_convert_user_ids_to_text/migration.sql
src/configs/config.ts
docker-compose.yml
e2e/src/support/global-setup.ts
prisma/schema.prisma
package-lock.json
Minor refactors and type-safety improvements across repositories, workers, and tests.
  • Refactor JobRepository create/update helpers to explicitly strip employer and type from data without destructuring side effects
  • Change renderEmailTemplate worker helper to use Record<string, unknown> for safer typing
  • Tighten test typing by replacing any casts with unknown as Role
  • Simplify IAdminRegister to a type alias of IBaseRegister and remove unused DB connection logging from server startup
  • Ensure log directory creation before configuring morgan file logging
src/repositories/job.repository.ts
src/queues/workers/authentication.worker.ts
src/utils/frontend.util.test.ts
src/interfaces/services/authentication.ts
src/server.ts
src/middlewares/app.middleware.ts
src/middlewares/app.middleware.ts
src/services/admin.service.ts
src/services/employer.service.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@iamkabelomoobi iamkabelomoobi merged commit a3cc91b into main Jun 6, 2026
1 of 2 checks passed

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've left some high level feedback:

  • The Redis service port mapping in docker-compose now exposes host 6380 to container 6380 while the Redis server still listens on 6379 by default; consider either mapping to 6379 in the container or explicitly configuring Redis to listen on 6380 to avoid connectivity issues.
  • In e2e/src/support/global-setup.ts, the Redis port resolution array is [6380, 6380], which removes the fallback to the default 6379 and is likely a typo; consider restoring a distinct secondary port (e.g., [6379, 6380]).
  • In src/libs/auth.ts, the welcome email failure is logged using console.error; consider switching this to the central logger for consistency with the rest of the codebase and better log management.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The Redis service port mapping in docker-compose now exposes host 6380 to container 6380 while the Redis server still listens on 6379 by default; consider either mapping to 6379 in the container or explicitly configuring Redis to listen on 6380 to avoid connectivity issues.
- In e2e/src/support/global-setup.ts, the Redis port resolution array is [6380, 6380], which removes the fallback to the default 6379 and is likely a typo; consider restoring a distinct secondary port (e.g., [6379, 6380]).
- In src/libs/auth.ts, the welcome email failure is logged using console.error; consider switching this to the central logger for consistency with the rest of the codebase and better log management.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant