feat(auth): Implement database-backed user authentication and
Build and Test / build-and-test-backend (push) Successful in 40s
Build and Test / build-and-test-frontend (push) Successful in 36s

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.
This commit is contained in:
wt committed 2025-08-08 23:47:36 +07:00
1 parent c6ed1d66b0
commit 599142af80
23 files changed
+458 -108

No files matched your search

-17
View File
@@ -1,17 +0,0 @@
package api
import (
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt"
)
func Accessible(c *fiber.Ctx) error {
return c.SendString("Accessible")
}
func Restricted(c *fiber.Ctx) error {
user := c.Locals("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
name := claims["name"].(string)
return c.SendString("Welcome " + name)
}
+56
View File
@@ -0,0 +1,56 @@
package api
import (
"backend/database"
"backend/model"
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v5"
)
func GetAllUsers(c *fiber.Ctx) error {
user := c.Locals("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userid := claims["id"].(string)
dbuser, e := database.GetUserById(userid)
if e != nil {
return c.Status(
fiber.StatusInternalServerError,
).JSON(
fiber.Map{
"error": e.Error(),
},
)
}
if !dbuser.IsSuperuser {
return c.Status(
fiber.StatusForbidden,
).JSON(
fiber.Map{
"error": "you are not superuser",
},
)
}
users, e := database.GetAllUsers()
if e != nil {
return fmt.Errorf("Error: %v", e)
}
var responseUsers []model.UserResponse
for i := range users {
responseUsers = append(
responseUsers,
model.UserResponse{
ID: users[i].ID,
Username: users[i].Username,
Email: users[i].Email,
Group: users[i].Group,
IsSuperuser: users[i].IsSuperuser,
},
)
}
return c.JSON(responseUsers)
}
+34
View File
@@ -0,0 +1,34 @@
package api
import (
"backend/database"
"backend/model"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v5"
)
func GetUserData(c *fiber.Ctx) error {
user := c.Locals("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
userid := claims["id"].(string)
dbuser, e := database.GetUserById(userid)
if e != nil {
return c.Status(
fiber.StatusInternalServerError,
).JSON(
fiber.Map{
"error": e.Error(),
},
)
}
return c.JSON(model.UserResponse{
ID: dbuser.ID,
Username: dbuser.Username,
Email: dbuser.Email,
Group: dbuser.Group,
IsSuperuser: dbuser.IsSuperuser,
})
}
+11 -5
View File
@@ -1,13 +1,14 @@
package api
import (
"backend/database"
"backend/model"
"fmt"
"os"
"time"
"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt"
"github.com/golang-jwt/jwt/v5"
)
func Login(c *fiber.Ctx) error {
@@ -16,13 +17,18 @@ func Login(c *fiber.Ctx) error {
if err != nil {
return fmt.Errorf("Error parse body, %s", err)
}
if requestdata.Username != "tola" || requestdata.Password != "2808" {
return c.SendStatus(fiber.StatusUnauthorized)
dbuser, e := database.GetUserByUsername(requestdata.Username)
if e != nil {
return fiber.ErrInternalServerError
}
if dbuser.Password != requestdata.Password {
return fiber.ErrForbidden
}
claims := jwt.MapClaims{
"username": "tola",
"is_superuser": true,
"id": dbuser.ID,
"username": dbuser.Username,
"is_superuser": dbuser.IsSuperuser,
"exp": time.Now().Add(time.Hour * 72).Unix(),
}