Skip to content

Email Verification System & Role-Based Access Control #18

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

Merged
merged 10 commits into from
Dec 14, 2024

Conversation

foyzulkarim
Copy link
Owner

@foyzulkarim foyzulkarim commented Dec 14, 2024

Overview

This PR implements email verification functionality for new user registrations and establishes a comprehensive role-based access control (RBAC) system. It also includes cleanup of unused domain modules and improvements to the repository structure.

Key Changes

Email Verification

  • Added SendGrid integration for sending verification emails
  • Implemented email verification flow with token generation and validation
  • Created email templates for verification messages
  • Added debug mode for local email testing
  • New environment variables for SendGrid configuration

Role-Based Access Control

  • Implemented new Role and Resource schemas
  • Added migration system with initial data for resources and roles
  • Defined three system roles: SuperAdmin, Admin, and Visitor
  • Added granular permissions for API endpoints and client-side features

Code Cleanup

  • Removed unused domain modules (Product, Customer, Student)
  • Restructured User schema to include verification fields
  • Updated API endpoints for better RESTful practices
  • Added migration runner for database schema updates

Security Improvements

  • Enhanced user authentication flow to require email verification
  • Added role-based authorization checks
  • Improved password handling and user activation process

Configuration Changes

  • Added new environment variables:
    • SENDGRID_API_KEY
    • SENDGRID_FROM_EMAIL
    • SUPERADMIN_EMAIL
    • SUPERADMIN_PASSWORD
    • DB_NAME

Testing

  • Added debug mode for email verification testing
  • Local email templates can be tested without sending actual emails
  • Migration system includes dry-run capability

Migration Instructions

  1. Update environment variables
  2. Run npm run migrate to apply database changes
  3. Verify email templates in debug mode if needed

Notes

  • Existing users will need to be assigned roles manually
  • Email verification is required for new registrations
  • Debug mode can be enabled with EMAIL_DEBUG=true

Related client PR

foyzulkarim/commitstreams-client#30

- Introduce `migrate` script to handle database migrations
- Update configuration to include `DB_NAME`
- Modify resource schema
- Update user API routes for better clarity and consistency
- Added SUPERADMIN_PASSWORD and SUPERADMIN_EMAIL to the config schema.
- Introduced isSuperAdmin field in the user schema.
- Replaced resource data with a new structure in the migration file for initial resources.
- Updated role definitions in the migration file to include new roles and permissions.
- Removed old JSON files for resources and roles as they are now embedded in migration scripts.
- Implement Role-Based Access Control (RBAC) system
- Add migration scripts for initial resources, roles, and users
- Update user schema to use role identifier instead of ObjectId
- Simplify resource types to 'api' and 'client'
- Remove unused CRUD endpoints from resource and role APIs
- Update authentication flow to include user permissions
- Standardize user object structure across auth flows
- Update repository follow endpoint path
- Remove pagination from resource search
Add email verification system for local authentication strategy:

- Add SendGrid integration for sending verification emails
- Require email verification before allowing login
- Add verification token and expiry fields to User schema
- Implement verification endpoints (/verify-email and /resend-verification)
- Add rate limiting for verification email requests
- Add debug email routes for development environment
- Update registration flow to send verification email
- Add error handling for verification-related errors

BREAKING CHANGE: Local authentication now requires email verification before login
**Refactor Email Verification Process and Update Configuration**

- **Update `.gitignore`:**
  - Added `**/debug/**` to ignore debug directories.
  - Added `.DS_Store` to ignore macOS system files.

- **Configuration Schema (`src/configs/config.schema.js`):**
  - Removed `SENDGRID_VERIFICATION_TEMPLATE_ID` field.

- **User Schema (`src/domains/user/schema.js`):**
  - Added `verificationEmailSentAt` field to track when the verification email was last sent.

- **User Service (`src/domains/user/service.js`):**
  - Changed verification token expiry from 1 minute to 24 hours.
  - Updated logic to use `verificationEmailSentAt` for rate limiting resend attempts.
  - Enhanced logging for debug mode.

- **Email Service (`src/libraries/email/emailService.js`):**
  - Simplified debug mode configuration.
  - Added `loadTemplate` function to compile HTML email templates.
  - Refactored `sendVerificationEmail` to use HTML templates instead of SendGrid dynamic templates.
  - Improved debug email saving with HTML content.
- Add API endpoint to update user roles (/update-role/:id)
- Add roleId field to User schema with Role reference
- Refactor migrations to use constants for role names
- Improve demo user creation with proper password hashing
- Remove redundant migration 004
- Update resource logging to use identifiers instead of IDs
- Add proper session saving in login endpoint with explicit save calls
- Update user verification flow to set proper role and activation state
- Standardize API endpoint naming for user operations
- Add verifiedAt timestamp to track when users complete verification
- Clean up console logs and improve logging messages
- Fix session userId storage to consistently use string format

The main changes focus on ensuring sessions are properly saved during login
and standardizing how we handle user verification and activation states.
Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
10.4% Duplication on New Code (required ≤ 3%)
C Reliability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

@foyzulkarim foyzulkarim changed the title Feature/apply role based access control Email Verification System & Role-Based Access Control Dec 14, 2024
@foyzulkarim foyzulkarim marked this pull request as ready for review December 14, 2024 23:07
@foyzulkarim foyzulkarim merged commit 1e4f6b2 into main Dec 14, 2024
2 of 3 checks passed
@foyzulkarim foyzulkarim deleted the feature/apply-role-based-access-control branch December 14, 2024 23:11
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