This API provides user authentication functionality, including registration, login, and Google OAuth2 authentication.
- OAuth2 for Google authentication
- JWT (JSON Web Tokens) for token-based authentication
- bcrypt for hashing passwords
- Redis for OTP and token storage
- MongoDB for user data storage
- Sendgrid for Email OTP SMTP
- Passport for handling Google OAuth2 and JWT authentication
- Register a new user by providing
name,email, andpassword. - Sends an OTP for email verification.
- Returns a token to verify OTP.
{
"name": "John Doe",
"email": "[email protected]",
"password": "securepassword"
}- Verifies the OTP sent to the user's email.
- Finalizes user registration and saves the user to the database.
{
"token": "temporary-jwt-token",
"type": "register",
"otp": "123456"
}- Log in an existing user by providing
emailandpassword. - Sends an OTP for email verification.
- Returns a token to verify OTP.
{
"email": "[email protected]",
"password": "securepassword"
}- Verifies the OTP sent to the user's email.
- If successful, returns an access token and refresh token.
{
"token": "temporary-jwt-token",
"type": "login",
"otp": "123456"
}- Refreshes the access token using the provided refresh token.
{
"refreshToken": "refresh-token"
}- Initiates Google OAuth2 login.
- Handles the callback from Google after user authentication.
- Returns access and refresh tokens for the authenticated user.
- Fetches the profile of the authenticated user.
- Updates the profile of the authenticated user.
- Allows updates to
name,phone, andaddress.
{
"name": "John Doe",
"phone": "1234567890",
"address": "123 Street, City, Country"
}- Registration: The user registers with an email and password, and receives an OTP to verify their email.
- Login: The user logs in with their email and password, then verifies their email via OTP.
- Google OAuth2: The user can log in via Google OAuth2, which generates access and refresh tokens.
- Access Tokens: Used for authenticating API requests for a short period (15 minutes).
- Refresh Tokens: Used to refresh access tokens after expiration (valid for 7 days).
- authMiddleware: Ensures the user is authenticated by verifying the JWT.
- roleMiddleware: Checks the user's role before allowing access to certain routes.
-
Clone the repository:
git clone https://github.com/rahmate2003/OAUTH20-MONGO-REDIS-SENDGRID-API.git
-
Install dependencies:
npm install
-
Create a
.envfile and set the necessary environment variables:# Sendgrid API SENDGRID_API_KEY= EMAIL_FROM= # MongoDB Connection MONGO_URI= # JWT Secret Key JWT_OTP_SECRET= JWT_SECRET= REFRESH_TOKEN_SECRET= # Redis URL REDIS_URL= # Google Oauth2.0 GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= GOOGLE_CALLBACK_URL= CLIENT_URL= SESSION_SECRET= # Server Port PORT= # Environment Mode NODE_ENV=
-
Start the server:
npm run dev