5 Commits

Author SHA1 Message Date
Adrian Zürcher
b6988638c0 fix minor bugs in role api 2025-10-24 17:35:32 +02:00
Adrian Zürcher
1b7218e5de change dlete role api from id to key 'role' 2025-10-24 17:10:28 +02:00
Adrian Zürcher
8285cf0384 add middleware for api 2025-10-24 16:29:37 +02:00
Adrian Zürcher
14994edcad add login for api handler 2025-10-24 16:22:17 +02:00
Adrian Zürcher
ab85632410 fix wrong handler namr 2025-10-24 16:10:19 +02:00
6 changed files with 434 additions and 49 deletions

View File

@@ -51,7 +51,7 @@ type AccessHandlerAPI struct {
// if err != nil { // if err != nil {
// log.Fatal(err) // log.Fatal(err)
// } // }
func NewAccessHandlerAPIAPI(path string, logger *logging.Logger) (aH *AccessHandlerAPI, err error) { func NewAccessHandlerAPI(path string, logger *logging.Logger) (aH *AccessHandlerAPI, err error) {
if logger == nil { if logger == nil {
logger, err = logging.NewLogger("accessHandler.log", nil) logger, err = logging.NewLogger("accessHandler.log", nil)
if err != nil { if err != nil {

83
api.go
View File

@@ -34,13 +34,6 @@ func (aH *AccessHandlerAPI) AddUser(c *gin.Context) {
return return
} }
hash, err := utils.HashPassword(user.Password)
if err != nil {
aH.logger.Error("AddUser", err)
c.JSON(http.StatusInternalServerError, nil)
return
}
if !utils.IsValidEmail(user.Email) { if !utils.IsValidEmail(user.Email) {
aH.logger.Error("AddUser", "not valid email address") aH.logger.Error("AddUser", "not valid email address")
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(errors.New("not valid email address"))) c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(errors.New("not valid email address")))
@@ -48,7 +41,7 @@ func (aH *AccessHandlerAPI) AddUser(c *gin.Context) {
} }
// Hash the provided password before saving // Hash the provided password before saving
hash, err = utils.HashPassword(user.Password) hash, err := utils.HashPassword(user.Password)
if err != nil { if err != nil {
aH.logger.Error("AddUser", err) aH.logger.Error("AddUser", err)
c.JSON(http.StatusInternalServerError, nil) c.JSON(http.StatusInternalServerError, nil)
@@ -188,7 +181,7 @@ func (aH *AccessHandlerAPI) AddRole(c *gin.Context) {
} }
// Check if a role with this name already exists // Check if a role with this name already exists
if err := aH.dbHandler.Exists(&models.Role{}, "role", role, false); err == nil { if err := aH.dbHandler.Exists(&models.Role{}, "role", role.Role, false); err == nil {
aH.logger.Error("AddRole", fmt.Sprintf("role with name %s already exists", role.Role)) aH.logger.Error("AddRole", fmt.Sprintf("role with name %s already exists", role.Role))
c.JSON(http.StatusBadRequest, models.NewJsonMessageResponse(fmt.Sprintf("role with name %s already exists", role.Role))) c.JSON(http.StatusBadRequest, models.NewJsonMessageResponse(fmt.Sprintf("role with name %s already exists", role.Role)))
} }
@@ -206,25 +199,30 @@ func (aH *AccessHandlerAPI) AddRole(c *gin.Context) {
func (aH *AccessHandlerAPI) GetRole(c *gin.Context) { func (aH *AccessHandlerAPI) GetRole(c *gin.Context) {
var i int var i int
var err error var err error
var roles []models.Role
role := c.Query("role")
id := c.Query("id") id := c.Query("id")
if id != "" {
if role != "" {
err = aH.dbHandler.GetByKey(&roles, "role", role, false)
} else if id != "" {
i, err = strconv.Atoi(id) i, err = strconv.Atoi(id)
if err != nil { if err != nil {
aH.logger.Error("GetRole", err) c.JSON(http.StatusBadRequest, gin.H{
c.JSON(http.StatusInternalServerError, nil) "message": err.Error(),
})
return return
} }
err = aH.dbHandler.GetById(&roles, uint(i))
} }
var role []models.Role
err = aH.dbHandler.GetById(&role, uint(i))
if err != nil { if err != nil {
aH.logger.Error("GetRole", err) aH.logger.Error("GetRole", err)
c.JSON(http.StatusInternalServerError, nil) c.JSON(http.StatusInternalServerError, nil)
return return
} }
c.JSON(http.StatusOK, role) c.JSON(http.StatusOK, roles)
} }
func (aH *AccessHandlerAPI) UpdateRole(c *gin.Context) { func (aH *AccessHandlerAPI) UpdateRole(c *gin.Context) {
@@ -244,61 +242,54 @@ func (aH *AccessHandlerAPI) UpdateRole(c *gin.Context) {
} }
func (aH *AccessHandlerAPI) DeleteRole(c *gin.Context) { func (aH *AccessHandlerAPI) DeleteRole(c *gin.Context) {
queryId := c.Query("id") queryRole := c.Query("role")
if queryRole == "" || queryRole == "null" || queryRole == "undefined" {
if queryId == "" || queryId == "null" || queryId == "undefined" { aH.logger.Error("DeleteRole", "id query missing or wrong value: "+queryRole)
aH.logger.Error("DeleteRole", "id query missing or wrong value: "+queryId) c.JSON(http.StatusInternalServerError, nil)
c.JSON(http.StatusBadRequest, gin.H{
"message": "id query missing or wrong value: " + queryId,
})
return return
} }
var request struct { var request struct {
Ids []int `json:"ids"` Roles []string `json:"roles"`
} }
err := c.BindJSON(&request) err := c.BindJSON(&request)
if err != nil { if err != nil {
aH.logger.Error("DeleteRole", "id query missing or wrong value: "+queryId) aH.logger.Error("DeleteRole", err)
c.JSON(http.StatusInternalServerError, nil) c.JSON(http.StatusBadRequest, nil)
return return
} }
if len(request.Ids) == 0 { if len(request.Roles) == 0 {
aH.logger.Error("DeleteRole", "no ids given to be deleted") aH.logger.Error("DeleteRole", "no ids given to be deleted")
c.JSON(http.StatusBadRequest, gin.H{ c.JSON(http.StatusBadRequest, models.NewJsonMessageResponse("no roles given to be deleted"))
"message": "no ids given to be deleted",
})
return return
} }
var ownId string var ownRole string
removeIds := make([]uint, len(request.Ids))
for i, id := range request.Ids { for _, role := range request.Roles {
if queryId == fmt.Sprint(id) { if queryRole == role {
ownId = queryId ownRole = role
continue continue
} }
removeIds[i] = uint(id) err = aH.dbHandler.DeleteByKey(&models.Role{}, "role", role, false)
if err != nil {
aH.logger.Error("DeleteRole", err)
c.JSON(http.StatusInternalServerError, nil)
return
}
} }
if ownId != "" { if ownRole != "" {
aH.logger.Error("DeleteRole", "can not delete logged in member role id: "+queryId) aH.logger.Error("DeleteRole", "can not delete logged in role id: "+ownRole)
c.JSON(http.StatusBadRequest, gin.H{ c.JSON(http.StatusBadRequest, gin.H{
"message": "can not delete logged in member id: " + queryId, "message": "can not delete logged in role id: " + ownRole,
"id": queryId, "role": ownRole,
}) })
return return
} }
err = aH.dbHandler.DeleteById(&models.Role{}, removeIds...)
if err != nil {
aH.logger.Error("DeleteUser", err)
c.JSON(http.StatusInternalServerError, nil)
return
}
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"message": "role(s) deleted", "message": "role(s) deleted",
}) })

View File

@@ -112,7 +112,7 @@ func TestLoginHandler(t *testing.T) {
r.POST("/login/refresh", aH.Refresh) r.POST("/login/refresh", aH.Refresh)
r.GET("/login/me", aH.Me) r.GET("/login/me", aH.Me)
r.GET("/logout", aH.Logout) r.GET("/logout", aH.Logout)
middleware := r.Group("", AuthMiddleware()) middleware := r.Group("", aH.AuthMiddleware())
auth := middleware.Group("/members", aH.AuthorizeRole("")) auth := middleware.Group("/members", aH.AuthorizeRole(""))
auth.GET("", func(ctx *gin.Context) { auth.GET("", func(ctx *gin.Context) {

227
loginApi.go Normal file
View File

@@ -0,0 +1,227 @@
package AccessHandler
import (
"fmt"
"log"
"net/http"
"time"
"gitea.tecamino.com/paadi/access-handler/models"
"gitea.tecamino.com/paadi/access-handler/utils"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// -----------------------------
// 🧠 HANDLERS
// -----------------------------
// Login authenticates a user and returns JWT tokens (access + refresh).
func (aH *AccessHandlerAPI) Login(c *gin.Context) {
var user models.User
aH.logger.Debug("Login", "bind JSON request")
if err := c.BindJSON(&user); err != nil {
aH.logger.Error("Login", err)
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
// Validate input
if !user.IsValid() {
aH.logger.Error("Login", "user empty")
c.JSON(http.StatusBadRequest, models.NewJsonMessageResponse("user empty"))
return
}
// Fetch user record from DB
var dbRecord []models.User
err := aH.dbHandler.GetByKey(&dbRecord, "user_name", user.Name, false)
if err != nil {
aH.logger.Error("Login", err)
c.JSON(http.StatusBadRequest, models.NewJsonErrorResponse(err))
return
}
if len(dbRecord) > 1 {
log.Println("multiple users found")
aH.logger.Error("Login", "more than one record found")
c.JSON(http.StatusInternalServerError, models.NewJsonMessageResponse("internal error"))
return
}
// Check password
if !utils.CheckPassword(user.Password, dbRecord[0].Password) {
aH.logger.Error("Login", "invalid password")
c.JSON(http.StatusUnauthorized, models.NewJsonMessageResponse("invalid credentials"))
return
}
user = dbRecord[0]
// -----------------------------
// 🔑 TOKEN CREATION
// -----------------------------
aH.logger.Debug("Login", "create tokens")
accessTokenExp := time.Now().Add(ACCESS_TOKEN_TIME)
refreshTokenExp := time.Now().Add(REFRESH_TOKEN_TIME)
// Create access token
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": user.Id,
"username": user.Name,
"role": user.Role,
"type": "access",
"exp": accessTokenExp.Unix(),
})
// Create refresh token
refreshToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": user.Id,
"username": user.Name,
"role": user.Role,
"type": "refresh",
"exp": refreshTokenExp.Unix(),
})
// Sign tokens
accessString, err := accessToken.SignedString(ACCESS_SECRET)
if err != nil {
aH.logger.Error("Login", "failed to sign access token")
c.JSON(http.StatusInternalServerError, models.NewJsonMessageResponse("could not create access token"))
return
}
refreshString, err := refreshToken.SignedString(REFRESH_SECRET)
if err != nil {
aH.logger.Error("Login", "failed to sign refresh token")
c.JSON(http.StatusInternalServerError, models.NewJsonMessageResponse("could not create refresh token"))
return
}
// -----------------------------
// 🍪 SET COOKIES
// -----------------------------
aH.logger.Debug("Login", "set cookies")
secure := gin.Mode() == gin.ReleaseMode
c.SetCookie("access_token", accessString, int(time.Until(accessTokenExp).Seconds()),
"/", "", secure, true)
c.SetCookie("refresh_token", refreshString, int(time.Until(refreshTokenExp).Seconds()),
"/", "", secure, true)
aH.logger.Info("Login", "user "+user.Name+" logged in successfully")
c.JSON(http.StatusOK, gin.H{
"message": "login successful",
"id": user.Id,
"user": user.Name,
"role": user.Role,
"settings": user.Settings,
})
}
// Refresh generates a new access token from a valid refresh token.
func (aH *AccessHandlerAPI) Refresh(c *gin.Context) {
aH.logger.Debug("Refresh", "get refresh cookie")
refreshCookie, err := c.Cookie("refresh_token")
if err != nil {
aH.logger.Error("Refresh", "no refresh token")
c.JSON(http.StatusUnauthorized, gin.H{"message": "no refresh token"})
return
}
// Validate token
aH.logger.Debug("Refresh", "parse token")
token, err := jwt.Parse(refreshCookie, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return REFRESH_SECRET, nil
})
if err != nil || !token.Valid {
aH.logger.Error("Refresh", err)
c.JSON(http.StatusUnauthorized, gin.H{"message": "invalid refresh token"})
return
}
// Extract claims
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || claims["type"] != "refresh" {
aH.logger.Error("Refresh", "invalid token type")
c.JSON(http.StatusUnauthorized, gin.H{"message": "invalid token type"})
return
}
username := claims["username"].(string)
id := int(claims["id"].(float64))
role := claims["role"].(string)
// Create new access token
aH.logger.Debug("Refresh", "create new access token")
accessExp := time.Now().Add(ACCESS_TOKEN_TIME)
newAccess := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": id,
"username": username,
"role": role,
"exp": accessExp.Unix(),
})
accessString, _ := newAccess.SignedString(ACCESS_SECRET)
// Set new access cookie
aH.logger.Debug("Refresh", "set new access cookie")
c.SetCookie("access_token", accessString, int(time.Until(accessExp).Seconds()),
"/", DOMAIN, gin.Mode() == gin.ReleaseMode, true)
c.JSON(http.StatusOK, gin.H{"message": "token refreshed"})
}
// Me returns information about the currently authenticated user.
func (aH *AccessHandlerAPI) Me(c *gin.Context) {
aH.logger.Debug("Me", "get access cookie")
cookie, err := c.Cookie("access_token")
if err != nil {
aH.logger.Error("Me", err)
c.JSON(http.StatusUnauthorized, gin.H{"message": "not logged in"})
return
}
// Parse and validate access token
aH.logger.Debug("Me", "parse token")
token, err := jwt.Parse(cookie, func(t *jwt.Token) (any, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return ACCESS_SECRET, nil
})
if err != nil || !token.Valid {
aH.logger.Error("Me", err)
c.JSON(http.StatusUnauthorized, gin.H{"message": "invalid token"})
return
}
claims := token.Claims.(jwt.MapClaims)
c.JSON(http.StatusOK, gin.H{
"id": claims["id"],
"user": claims["username"],
"role": claims["role"],
})
}
// Logout clears authentication cookies and ends the session.
func (aH *AccessHandlerAPI) Logout(c *gin.Context) {
aH.logger.Info("Logout", "logout user")
secure := gin.Mode() == gin.ReleaseMode
aH.logger.Debug("Logout", fmt.Sprintf("domain=%s secure=%t", DOMAIN, secure))
// Clear cookies
c.SetCookie("access_token", "", -1, "/", DOMAIN, secure, true)
c.SetCookie("refresh_token", "", -1, "/", DOMAIN, secure, true)
c.JSON(http.StatusOK, gin.H{"message": "logged out"})
}

View File

@@ -56,7 +56,7 @@ func SetMiddlewareLogger(r *gin.Engine, logger *logging.Logger) {
// Usage: // Usage:
// //
// r.Use(AuthMiddleware()) // r.Use(AuthMiddleware())
func AuthMiddleware() gin.HandlerFunc { func (aH *AccessHandler) AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
// Retrieve logger from Gin context // Retrieve logger from Gin context
middlewareLogger, ok := c.Get("logger") middlewareLogger, ok := c.Get("logger")

167
middlewareApi.go Normal file
View File

@@ -0,0 +1,167 @@
package AccessHandler
import (
"fmt"
"log"
"net/http"
"strings"
"gitea.tecamino.com/paadi/access-handler/models"
"gitea.tecamino.com/paadi/tecamino-logger/logging"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// SetMiddlewareLogger
//
// Description:
//
// Registers a Gin middleware that attaches a custom logger instance
// to every incoming request via the Gin context. This allows other
// middleware and handlers to access the logger using:
//
// logger := c.MustGet("logger").(*logging.Logger)
//
// Parameters:
// - r: The Gin engine to which the middleware is applied.
// - logger: A pointer to the application's custom logger.
//
// Usage:
//
// SetMiddlewareLogger(router, logger)
func (aH *AccessHandlerAPI) SetMiddlewareLogger(r *gin.Engine, logger *logging.Logger) {
// Add middleware that injects logger into context
r.Use(func(c *gin.Context) {
c.Set("logger", logger)
c.Next()
})
}
// AuthMiddleware
//
// Description:
//
// A Gin middleware that performs authentication using a JWT token stored
// in a cookie named "access_token". It validates the token and extracts
// the user's role from the claims, storing it in the Gin context.
//
// Behavior:
// - Requires that SetMiddlewareLogger was used earlier to inject the logger.
// - If the JWT cookie is missing or invalid, it aborts the request with
// an appropriate HTTP error (401 or 500).
//
// Returns:
//
// A Gin handler function that can be used as middleware.
//
// Usage:
//
// r.Use(AuthMiddleware())
func (aH *AccessHandlerAPI) AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Retrieve logger from Gin context
middlewareLogger, ok := c.Get("logger")
if !ok {
log.Fatal("middleware logger not set — use SetMiddlewareLogger first")
c.AbortWithStatusJSON(http.StatusInternalServerError, http.StatusInternalServerError)
return
}
logger := middlewareLogger.(*logging.Logger)
// Read access token from cookie
cookie, err := c.Cookie("access_token")
if err != nil {
logger.Error("AuthMiddleware", err)
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "not logged in"})
return
}
// Parse and validate JWT token
token, err := jwt.Parse(cookie, func(t *jwt.Token) (any, error) {
return ACCESS_SECRET, nil
})
if err != nil || !token.Valid {
logger.Error("AuthMiddleware", err)
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "invalid token"})
return
}
// Extract custom claims (role)
if claims, ok := token.Claims.(jwt.MapClaims); ok {
role, _ := claims["role"].(string)
c.Set("role", role)
}
c.Next()
}
}
// (AccessHandler).AuthorizeRole
//
// Description:
//
// A role-based authorization middleware. It checks whether the authenticated
// user (based on the "role" set in AuthMiddleware) has permission to access
// the given route. The check is performed by comparing the requested URL
// path against the users allowed permissions.
//
// Parameters:
// - suffix: A URL prefix to trim from the request path before matching
// permissions (e.g., "/api/v1").
//
// Behavior:
// - Fetches the user role from Gin context.
// - Uses aH.GetRoleByKey() to retrieve role records and permissions.
// - Grants access (calls c.Next()) if a matching permission is found.
// - Denies access (401 Unauthorized) if no permission matches.
//
// Usage:
//
// router.GET("/secure/:id", aH.AuthorizeRole("/api/v1"))
func (aH *AccessHandlerAPI) AuthorizeRole(suffix string) gin.HandlerFunc {
return func(c *gin.Context) {
aH.logger.Debug("AuthorizeRole", "permission path of url path")
permissionPath := strings.TrimPrefix(c.Request.URL.Path, suffix+"/")
aH.logger.Debug("AuthorizeRole", "get set role")
role, ok := c.Get("role")
if !ok {
aH.logger.Error("AuthorizeRole", "no role set")
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": http.StatusInternalServerError})
return
}
// Fetch roles and associated permissions from the database or store
var roles []models.Role
err := aH.dbHandler.GetByKey(&roles, "role", role, false)
if err != nil {
aH.logger.Error("AuthorizeRole", err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"message": http.StatusInternalServerError})
return
}
// Validate that a role was found
if len(roles) == 0 {
log.Println("not logged in")
aH.logger.Error("AuthorizeRole", "no logged in")
c.JSON(http.StatusUnauthorized, http.StatusUnauthorized)
return
} else if len(roles) > 1 {
aH.logger.Error("AuthorizeRole", "more than one record found")
c.JSON(http.StatusInternalServerError, http.StatusInternalServerError)
return
}
// Check permissions
for _, permission := range roles[0].Permissions {
fmt.Println(100, permissionPath, permission.Name)
if permission.Name == permissionPath {
c.Next()
return
}
}
// Access denied
aH.logger.Error("AuthorizeRole", "Forbidden")
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"message": "Forbidden"})
}
}