Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Role-Based Authentication API

A simple RESTful API built in Go for user registration, login, and role-based access control using JWT (JSON Web Tokens) and SQLite as the database. The API supports user management with role-based authorization, allowing specific actions (e.g., deleting users) to be restricted to users with the "admin" role.

Features

  • User registration with password hashing using bcrypt.
  • User login with JWT-based authentication.
  • Role-based access control for protected endpoints.
  • SQLite database for storing user data.
  • Middleware to enforce role-based authorization.

Prerequisites

  • Go (version 1.16 or later)
  • Install the required dependencies:
    go get github.com/gorilla/mux
    go get github.com/dgrijalva/jwt-go
    go get golang.org/x/crypto/bcrypt
    go get gorm.io/driver/sqlite
    go get gorm.io/gorm

Installation

  1. Clone or download the source code to your local machine.
  2. Ensure you have the required dependencies installed (see Prerequisites).
  3. Create a SQLite database file (test.db) in the project directory by running the program, which will automatically set up the database schema.

Usage

  1. Run the program:
    go run main.go
  2. The API will start on http://localhost:8000.
  3. Use the following endpoints:
    • POST /register: Register a new user with a JSON payload containing username, password, and role. Example:
      {
        "username": "johndoe",
        "password": "secret123",
        "role": "admin"
      }
    • POST /login: Log in a user and receive a JWT token in a cookie. Example:
      {
        "username": "johndoe",
        "password": "secret123"
      }
    • DELETE /admin/delete: Delete a user (requires "admin" role). Include the JWT token in the request cookie.

Notes

  • The JWT secret key is hardcoded as your_secret_key. Replace it with a secure key in production.
  • The JWT token is stored in a cookie with a 5-minute expiration time.
  • The SQLite database (test.db) is created automatically in the project directory.
  • The /admin/delete endpoint is a placeholder and requires an admin role to access.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages