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.
- 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.
- 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
- Clone or download the source code to your local machine.
- Ensure you have the required dependencies installed (see Prerequisites).
- Create a SQLite database file (
test.db) in the project directory by running the program, which will automatically set up the database schema.
- Run the program:
go run main.go
- The API will start on
http://localhost:8000. - Use the following endpoints:
POST /register: Register a new user with a JSON payload containingusername,password, androle. 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.
- 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/deleteendpoint is a placeholder and requires an admin role to access.