Skip to content

ProducerG-hub/authentication-system-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Authentication System API (Node.js + PostgreSQL + JWT)

A robust and secure authentication system built with Node.js, Express, and PostgreSQL. This system handles user registration, login, updates, deletions, and user search functionality.

It is designed to be a solid foundation for any application requiring user authentication.

Features

  • User Registration: Securely register new users with hashed passwords.
  • User Login: Authenticate users and issue JWT tokens.
  • Profile Management: Update user details.
  • User Deletion: Remove user accounts.
  • User Search: Find specific user details.
  • Security: Uses bcrypt for password hashing and jsonwebtoken (JWT) for secure transmission. Checks if a user is authenticated before allowing access to protected routes.
  • Role-Based Access Control: Admin users can manage other users (via roles table, referenced by role_id in users).
  • Active User Management: Only active users can log in.
  • Screenshots: Visual documentation of key features and flows, available in the screenshots/ directory.

Tech Stack

  • Runtime: Node.js
  • Framework: Express.js
  • Database: PostgreSQL
  • Authentication: JSON Web Token (JWT)
  • Security: Bcrypt (for password hashing)

Prerequisites

Before running this project, ensure you have the following installed:

Installation & Setup

  1. Clone the repository:

    git clone https://github.com/ProducerG-hub/authentication_system.git
    cd authentication-system
  2. Install dependencies:

    npm install
  3. Database Setup: Create a PostgreSQL database and a users table. Run the following SQL commands in your PostgreSQL interface (e.g., pgAdmin or psql):

    CREATE DATABASE auth_db;
    
    -- Connect to the newly created database
    \c auth_db
    
    -- Create Roles table (referenced by users)
    CREATE TABLE roles (
        id SERIAL PRIMARY KEY,
        name VARCHAR(50) NOT NULL
    );
    
    -- Insert default roles
    INSERT INTO roles (name) VALUES ('user'), ('admin');
    
    -- Create Users table with role_id as a foreign key to roles table
    CREATE TABLE users (
        id SERIAL PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        email VARCHAR(255) UNIQUE NOT NULL,
        password VARCHAR(255) NOT NULL,
        role_id INT DEFAULT 1 REFERENCES roles(id),
        is_active BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );
    
    -- Creating A foreign key for roles table in users table
    ALTER TABLE users
    ADD CONSTRAINT fk_role
    FOREIGN KEY (role_id) REFERENCES roles(id);
    
  4. Environment Configuration: Create a .env file in the root directory and add the following variables:

    PORT=your_port
    
    # Database Configuration
    DB_USER=your_postgres_user
    DB_PASSWORD=your_postgres_password
    DB_HOST=localhost
    DB_PORT=your_postgres_port
    DB_NAME=your_database_name
    
    # Security Secrets
    JWT_SECRET=your_super_secret_jwt_key
    SALT_ROUNDS=your_salt_rounds
  5. Run the Application:

    For development (with nodemon):

    npm run dev

    For production:

    npm start

API Endpoints

The base URL for all authentication routes is: http://localhost:3000/api/auth

1. Register User

  • URL: /register
  • Method: POST
  • Body:
    {
        "name": "David Francis",
        "email": "davidfrancis@gmail.com",
        "password": "securepassword123"
    }

2. Login User

  • URL: /login
  • Method: POST
  • Body:
    {
        "email": "davidfrancis@gmail.com",
        "password": "securepassword123"
    }
  • Response (Successful Login): Returns a JWT token upon success with a feedback message i.e authenticated successfully.
  • Response (Failed Login): Returns an error message indicating invalid credentials or inactive account i.e. Bad credentials or account is inactive.

3. Update User (Admin Only)

  • URL: /update/:id
  • Method: POST
  • Body: (Fields to update)
    {
        "name": "David Mwakajonga",
        "email": "mwakajongadavid@gmail.com"
    }

4. Delete User (Admin Only)

  • URL: /delete/:id
  • Method: POST

5. Find User (Authenticated Users)

  • URL: /find/:id
  • Method: POST

Project Structure

├── controller/
│   └── logics.js         # Business logic for auth operations
├── database/
│   └── connect.js        # Database connection configuration
├── middleware/
│   └── auth.js           # Authentication and role-based access middleware
├── routes/
│   └── urls.js           # API Route definitions
├── screenshots/          # Screenshots of the application (see below)
│   ├── access-control.png
│   ├── home-page.png
│   ├── register-user.png
│   ├── user-login.png
│   └── user-login (Bad Credintials).png
├── index.js              # Entry point of the application
├── .env                  # Environment variables (not included in repo)
├── package.json          # Dependencies and scripts
└── README.md             # Project documentation

Architecture Overview

  • Controller Layer → Handles business logic
  • Routes Layer → Defines API endpoints
  • Middleware → Authentication & authorization
  • Database Layer → PostgreSQL connection and queries
  • Screenshots → Visual documentation of features and flows
  • Environment Variables → Secure configuration management

Security Features

  • Password hashing using bcrypt
  • JWT-based authentication
  • Role-based authorization (admin/user)
  • Protection of private routes
  • Active user validation before login
  • Secure storage of sensitive information using environment variables
  • Input validation and error handling to prevent common vulnerabilities
  • Regular updates and maintenance to address security issues and ensure best practices are followed

Screenshots

The screenshots/ directory contains visual documentation of the application's main features and flows:

  • home-page.png: Landing page of the API.
  • register-user.png: User registration process.
  • user-login.png: Successful user login.
  • user-login (Bad Credintials).png: Failed login attempt (bad credentials).
  • access-control.png: Example of access control (admin vs. user permissions).

You can use these images for documentation, presentations, or to quickly understand the system's UI and API responses.

Future Improvements

  • Refresh token implementation
  • Email verification system
  • Password reset functionality
  • Rate limiting for security
  • Logging and monitoring
  • Unit and integration tests
  • Dockerization for easier deployment
  • Frontend integration (e.g., React, Vue)
  • Support for social login (Google, Facebook, etc.)
  • Improved error handling and validation
  • API documentation (e.g., Swagger)
  • Role management interface for admins
  • Multi-factor authentication (MFA) support

License

This project is licensed under the ISC License.

Contributing

Contributions are welcome! Please fork the repository and submit a pull request for any improvements or bug fixes.

Contact

For any questions or issues, please open an issue on the GitHub repository or contact me at [gwamakamwakabuta@gmail.com] or contact us at [mluetechnologytz@gmail.com].

Acknowledgements

Author

  • Gwamaka Mwakabuta - GitHub - Email
  • Mlue_Technology - Company in Tanzania - Email

About

Production-ready authentication API with Node.js, PostgreSQL, JWT-based authorization, bcrypt password hashing, and full user CRUD operations.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors