persistence This commit introduces a major architectural change by replacing the previous hardcoded user and data system with a robust, database-driven approach. It lays the foundation for persistent data storage for all application models. Key Changes: - **Database Integration:** - Added `GORM` and `SQLite` for the database layer. - The database is now initialized and migrated on application startup. - Configuration is managed through environment variables (`DATABASE`, `USERS_FILE`). - **User Authentication & Management:** - The login endpoint (`/api/token`) now authenticates users against the database. - JWT claims are now populated with real user data (`id`, `username`, `is_superuser`). - Implemented a system to seed the database with initial users from a `users.json` file. - **New User API Endpoints:** - `GET /api/users`: Retrieves a list of all users (superuser access required). - `GET /api/users/user`: Fetches the data for the currently authenticated user based on their JWT. - **Data Model Overhaul:** - Refactored all data models (`User`, `Category`, `Operation`, `Subcategory`) to include GORM tags, relationships, and a `BaseModel` with auto-generated UUIDs for primary keys. - Separated user-related structs into `User` (database model), `AuthRequest` (login payload), and `UserResponse` (safe API response). - **Middleware & Routing:** - Improved JWT error handling for clearer client-side messages. - Added a new middleware to allow passing the JWT in the request body for more flexible client integration.
43 lines
948 B
Go
43 lines
948 B
Go
package api
|
|
|
|
import (
|
|
"backend/database"
|
|
"backend/model"
|
|
"fmt"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
func Login(c *fiber.Ctx) error {
|
|
var requestdata model.AuthRequest
|
|
err := c.BodyParser(&requestdata)
|
|
if err != nil {
|
|
return fmt.Errorf("Error parse body, %s", err)
|
|
}
|
|
dbuser, e := database.GetUserByUsername(requestdata.Username)
|
|
if e != nil {
|
|
return fiber.ErrInternalServerError
|
|
}
|
|
if dbuser.Password != requestdata.Password {
|
|
return fiber.ErrForbidden
|
|
}
|
|
|
|
claims := jwt.MapClaims{
|
|
"id": dbuser.ID,
|
|
"username": dbuser.Username,
|
|
"is_superuser": dbuser.IsSuperuser,
|
|
"exp": time.Now().Add(time.Hour * 72).Unix(),
|
|
}
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
|
|
t, err := token.SignedString([]byte(os.Getenv("JWT_SECRET_KEY")))
|
|
if err != nil {
|
|
return c.SendStatus(fiber.StatusInternalServerError)
|
|
}
|
|
return c.JSON(fiber.Map{"token": t})
|
|
}
|