This project implements a robust user authentication API with features including registration, email verification, login, password reset, and user profile management.
- Features
- API Endpoints
- Technologies Used
- Configuration
- Logging
- Database Connection
- User Model
- Middleware
- Utilities
- Setup
- Usage
- Security Features
- Error Handling
- Contributing
- User registration with email verification
- Login and logout functionality
- Password reset via email
- User profile management (view, update, delete)
- Email notifications for account actions
POST /api/v1/user/register
: Register a new userPOST /api/v1/user/account/verify
: Resend email verificationPOST /api/v1/user/verify/:token
: Verify user's emailPOST /api/v1/user/login
: User loginPOST /api/v1/user/logout
: User logoutPOST /api/v1/user/reset-password
: Request password reset linkPOST /api/v1/user/reset-password/:token
: Verify password reset tokenPOST /api/v1/user/generate-password/:token
: Generate new password after reset
GET /api/v1/user/profile
: Get user profilePATCH /api/v1/user/update
: Update user informationDELETE /api/v1/user/delete
: Delete user account
- Node.js
- Express.js
- TypeScript
- MongoDB (assumed, based on the use of models)
- JWT for authentication
- Nodemailer for sending emails
The project uses the following environment variables:
NODE_ENV
: Set to "development" or "test"SERVER_HOSTNAME
: Server hostname (default: "localhost")SERVER_PORT
: Server port (default: 12345)EMAIL_USERNAME
: Email username for sending notificationsEMAIL_PASSWORD
: Email password for sending notificationsDB_URI
: MongoDB connection URIJWT_SECRET_KEY
: Secret key for JWT token generation (default: "12313456165")
The API is documented using Swagger:
- OpenAPI version: 3.0.0
- Title: Authentication API
- Version: 1.0.0
- Server URL:
http://${SERVER_HOSTNAME}:${SERVER_PORT}/api/docs
Nodemailer is configured to use Gmail SMTP:
- Service: Gmail
- Host: smtp.gmail.com
- Port: 587
- Secure: false
A custom logging utility is implemented with color-coded console outputs:
log
: General logging (magenta)info
: Information logging (cyan)warn
: Warning logging (yellow)error
: Error logging (red)
Logging includes timestamps and calling function names.
MongoDB connection is established using Mongoose:
- Connection string is set via the
DB_URI
environment variable - Successful connection and errors are logged
The User model is defined using Mongoose and represents the structure of user data in the database.
The User schema includes the following fields:
username
: String (required)email
: String (required, unique)password
: String (required)isVerified
: Boolean- Default: false
verificationToken
: String (unique)passresetToken
: StringpassresetTokenExp
: Date
The schema also includes timestamps (createdAt
and updatedAt
).
Two interfaces are defined:
IUser
: ExtendsDocument
and defines the structure of a user document.IUserModel
: ExtendsModel<IUser>
for potential static methods.
matchPassword(enteredPassword: string): Promise<boolean>
- Compares entered password with stored hashed password using bcrypt
A pre-save hook is implemented to automatically hash the password before saving if it has been modified:
- Uses bcrypt with a salt round of 10
- Only hashes the password if it has been modified
The application uses several middleware functions to handle various aspects:
- Route Not Found Middleware: Handles 404 errors for undefined routes.
- Logging Middleware: Logs incoming requests and outgoing responses.
- Authentication Middleware: Verifies JWT tokens for protected routes.
- CORS Middleware: Handles Cross-Origin Resource Sharing settings.
The isAuthenticated
middleware:
- Checks for a valid JWT token in the request cookies
- Verifies the token and attaches the user object to the request
- Used to protect private routes
The CORS middleware:
- Sets appropriate headers for cross-origin requests
- Handles preflight OPTIONS requests
- Allows credentials to be included in cross-origin requests
The project includes a utility function for generating and setting JWT tokens:
settoken(res: Response, payload: object)
:- Generates a JWT token with the provided payload
- Sets the token as an HTTP-only cookie named "session_cookie"
- Cookie is set with strict same-site policy and expires in 7 days
The API uses Zod for input validation. The following schemas are defined:
emailSchema
: Validates email inputregisterSchema
: Validates user registration dataloginSchema
: Validates login credentialsverifyEmailSchema
: Validates email verification tokenresetPasswordSchema
: Validates password reset requestverifyPasswordSchema
: Validates password reset tokengeneratePasswordSchema
: Validates new password generationupdateUserSchema
: Validates user profile update data
Key features of the validation schemas:
- Email validation
- Password strength requirements (min 8 characters, uppercase, lowercase, number, special character)
- Username length restrictions (4-30 characters)
- Role validation (TUTOR or USER)
- Clone the repository
- Install dependencies:
npm install
- Set up environment variables (database connection, JWT secret, email configuration)
- Run the server:
npm start
- Register a new user by sending a POST request to
/api/v1/user/register
- Verify the user's email using the link sent to their email
- Log in using the
/api/v1/user/login
endpoint - Use the authenticated routes to manage the user profile
- Password hashing (implied by the
matchPassword
method) - JWT-based authentication with secure cookie storage
- Email verification for new accounts
- Secure password reset flow with time-limited tokens
- CORS protection
- Input validation using Zod schemas
The API includes basic error handling and logging. Ensure proper logging configuration for production use.
Contributions are welcome! Please feel free to submit issues and pull requests to improve the project.