refactor: reorganize models to pkg/model and add authentication module
- Move ORM models from internal/model to pkg/model organized by module (auth/k8s/registry) - Add authentication module with login, user management handlers - Update all import paths to use new model locations - Add frontend auth pages (Login, UserManagement) and authStore - Remove deprecated internal/model/model.go
This commit is contained in:
41
internal/module/auth/auth.go
Normal file
41
internal/module/auth/auth.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
auth "gitea.loveuer.com/loveuer/cluster/pkg/model/auth"
|
||||
"gitea.loveuer.com/loveuer/cluster/pkg/tool"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func Init(ctx context.Context, db *gorm.DB) error {
|
||||
if err := db.AutoMigrate(&auth.User{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var count int64
|
||||
if err := db.Model(&auth.User{}).Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
defaultAdmin := &auth.User{
|
||||
Username: "admin",
|
||||
Password: tool.NewPassword("cluster"),
|
||||
Email: "admin@cluster.local",
|
||||
Nickname: "Administrator",
|
||||
Role: "admin",
|
||||
Status: "active",
|
||||
Permissions: "registry_read,registry_write,cluster_read,cluster_write",
|
||||
}
|
||||
|
||||
if err := db.Create(defaultAdmin).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Println("[Auth] Default admin user created: username=admin, password=cluster")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
42
internal/module/auth/handler.current.go
Normal file
42
internal/module/auth/handler.current.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.loveuer.com/loveuer/cluster/pkg/resp"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
func GetCurrentUser(ctx context.Context) fiber.Handler {
|
||||
return func(c fiber.Ctx) error {
|
||||
authHeader := c.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
return resp.R401(c, "MISSING_TOKEN", nil, "authorization token is required")
|
||||
}
|
||||
|
||||
tokenString := authHeader
|
||||
if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
|
||||
tokenString = authHeader[7:]
|
||||
}
|
||||
|
||||
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(JWTSecret), nil
|
||||
})
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
return resp.R401(c, "INVALID_TOKEN", nil, "invalid or expired token")
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*Claims)
|
||||
if !ok {
|
||||
return resp.R401(c, "INVALID_CLAIMS", nil, "invalid token claims")
|
||||
}
|
||||
|
||||
return resp.R200(c, map[string]interface{}{
|
||||
"user_id": claims.UserID,
|
||||
"username": claims.Username,
|
||||
"role": claims.Role,
|
||||
})
|
||||
}
|
||||
}
|
||||
97
internal/module/auth/handler.login.go
Normal file
97
internal/module/auth/handler.login.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
authModel "gitea.loveuer.com/loveuer/cluster/pkg/model/auth"
|
||||
"gitea.loveuer.com/loveuer/cluster/pkg/resp"
|
||||
"gitea.loveuer.com/loveuer/cluster/pkg/tool"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
JWTSecret = "cluster-secret-key-change-in-production"
|
||||
TokenDuration = 7 * 24 * time.Hour
|
||||
)
|
||||
|
||||
type LoginRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
Token string `json:"token"`
|
||||
Username string `json:"username"`
|
||||
Nickname string `json:"nickname"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
type Claims struct {
|
||||
UserID uint `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func Login(ctx context.Context, db *gorm.DB) fiber.Handler {
|
||||
return func(c fiber.Ctx) error {
|
||||
var req LoginRequest
|
||||
|
||||
body := c.Body()
|
||||
if len(body) == 0 {
|
||||
return resp.R400(c, "EMPTY_BODY", nil, "request body is empty")
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
return resp.R400(c, "INVALID_REQUEST", nil, "invalid request body")
|
||||
}
|
||||
|
||||
if req.Username == "" || req.Password == "" {
|
||||
return resp.R400(c, "MISSING_CREDENTIALS", nil, "username and password are required")
|
||||
}
|
||||
|
||||
var user authModel.User
|
||||
if err := db.Where("username = ?", req.Username).First(&user).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return resp.R401(c, "INVALID_CREDENTIALS", nil, "invalid username or password")
|
||||
}
|
||||
return resp.R500(c, "", nil, err.Error())
|
||||
}
|
||||
|
||||
if user.Status != "active" {
|
||||
return resp.R403(c, "USER_INACTIVE", nil, "user account is inactive")
|
||||
}
|
||||
|
||||
if !tool.ComparePassword(req.Password, user.Password) {
|
||||
return resp.R401(c, "INVALID_CREDENTIALS", nil, "invalid username or password")
|
||||
}
|
||||
|
||||
claims := &Claims{
|
||||
UserID: user.ID,
|
||||
Username: user.Username,
|
||||
Role: user.Role,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(TokenDuration)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
NotBefore: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenString, err := token.SignedString([]byte(JWTSecret))
|
||||
if err != nil {
|
||||
return resp.R500(c, "", nil, "failed to generate token")
|
||||
}
|
||||
|
||||
return resp.R200(c, LoginResponse{
|
||||
Token: tokenString,
|
||||
Username: user.Username,
|
||||
Nickname: user.Nickname,
|
||||
Role: user.Role,
|
||||
})
|
||||
}
|
||||
}
|
||||
207
internal/module/auth/handler.user.go
Normal file
207
internal/module/auth/handler.user.go
Normal file
@@ -0,0 +1,207 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
|
||||
auth "gitea.loveuer.com/loveuer/cluster/pkg/model/auth"
|
||||
"gitea.loveuer.com/loveuer/cluster/pkg/resp"
|
||||
"gitea.loveuer.com/loveuer/cluster/pkg/tool"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func UserList(ctx context.Context, db *gorm.DB) fiber.Handler {
|
||||
return func(c fiber.Ctx) error {
|
||||
var users []auth.User
|
||||
if err := db.Find(&users).Error; err != nil {
|
||||
return resp.R500(c, "", nil, err.Error())
|
||||
}
|
||||
|
||||
return resp.R200(c, map[string]interface{}{
|
||||
"users": users,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func UserCreate(ctx context.Context, db *gorm.DB) fiber.Handler {
|
||||
return func(c fiber.Ctx) error {
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Email string `json:"email"`
|
||||
Nickname string `json:"nickname"`
|
||||
Role string `json:"role"`
|
||||
Status string `json:"status"`
|
||||
Permissions string `json:"permissions"`
|
||||
}
|
||||
|
||||
body := c.Body()
|
||||
if len(body) == 0 {
|
||||
return resp.R400(c, "EMPTY_BODY", nil, "request body is empty")
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
return resp.R400(c, "INVALID_REQUEST", nil, "invalid request body")
|
||||
}
|
||||
|
||||
if req.Username == "" || req.Password == "" {
|
||||
return resp.R400(c, "MISSING_FIELDS", nil, "username and password are required")
|
||||
}
|
||||
|
||||
if err := tool.CheckPassword(req.Password); err != nil {
|
||||
return resp.R400(c, "WEAK_PASSWORD", nil, err.Error())
|
||||
}
|
||||
|
||||
var existing auth.User
|
||||
if err := db.Unscoped().Where("username = ?", req.Username).First(&existing).Error; err == nil {
|
||||
return resp.R400(c, "USER_EXISTS", nil, "username already exists")
|
||||
}
|
||||
|
||||
user := &auth.User{
|
||||
Username: req.Username,
|
||||
Password: tool.NewPassword(req.Password),
|
||||
Email: req.Email,
|
||||
Nickname: req.Nickname,
|
||||
Role: req.Role,
|
||||
Status: req.Status,
|
||||
Permissions: req.Permissions,
|
||||
}
|
||||
|
||||
if user.Role == "" {
|
||||
user.Role = "user"
|
||||
}
|
||||
if user.Status == "" {
|
||||
user.Status = "active"
|
||||
}
|
||||
|
||||
if err := db.Create(user).Error; err != nil {
|
||||
return resp.R500(c, "", nil, err.Error())
|
||||
}
|
||||
|
||||
return resp.R200(c, map[string]interface{}{
|
||||
"user": user,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func UserUpdate(ctx context.Context, db *gorm.DB) fiber.Handler {
|
||||
return func(c fiber.Ctx) error {
|
||||
userID := c.Params("id")
|
||||
if userID == "" {
|
||||
return resp.R400(c, "MISSING_ID", nil, "user id is required")
|
||||
}
|
||||
|
||||
authHeader := c.Get("Authorization")
|
||||
var currentUserID uint
|
||||
if authHeader != "" {
|
||||
tokenString := authHeader
|
||||
if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
|
||||
tokenString = authHeader[7:]
|
||||
}
|
||||
|
||||
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(JWTSecret), nil
|
||||
})
|
||||
|
||||
if err == nil && token.Valid {
|
||||
if claims, ok := token.Claims.(*Claims); ok {
|
||||
currentUserID = claims.UserID
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
targetUserID, _ := strconv.ParseUint(userID, 10, 32)
|
||||
isSelf := currentUserID == uint(targetUserID)
|
||||
|
||||
var req struct {
|
||||
Email string `json:"email"`
|
||||
Nickname string `json:"nickname"`
|
||||
Password string `json:"password"`
|
||||
Role string `json:"role"`
|
||||
Status string `json:"status"`
|
||||
Permissions string `json:"permissions"`
|
||||
}
|
||||
|
||||
body := c.Body()
|
||||
if len(body) == 0 {
|
||||
return resp.R400(c, "EMPTY_BODY", nil, "request body is empty")
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(body, &req); err != nil {
|
||||
return resp.R400(c, "INVALID_REQUEST", nil, "invalid request body")
|
||||
}
|
||||
|
||||
var user auth.User
|
||||
if err := db.First(&user, userID).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return resp.R404(c, "USER_NOT_FOUND", nil, "user not found")
|
||||
}
|
||||
return resp.R500(c, "", nil, err.Error())
|
||||
}
|
||||
|
||||
user.Email = req.Email
|
||||
user.Nickname = req.Nickname
|
||||
|
||||
if req.Password != "" {
|
||||
if err := tool.CheckPassword(req.Password); err != nil {
|
||||
return resp.R400(c, "WEAK_PASSWORD", nil, err.Error())
|
||||
}
|
||||
user.Password = tool.NewPassword(req.Password)
|
||||
}
|
||||
|
||||
if !isSelf {
|
||||
user.Role = req.Role
|
||||
user.Status = req.Status
|
||||
user.Permissions = req.Permissions
|
||||
}
|
||||
|
||||
if err := db.Save(&user).Error; err != nil {
|
||||
return resp.R500(c, "", nil, err.Error())
|
||||
}
|
||||
|
||||
return resp.R200(c, map[string]interface{}{
|
||||
"user": user,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func UserDelete(ctx context.Context, db *gorm.DB) fiber.Handler {
|
||||
return func(c fiber.Ctx) error {
|
||||
userID := c.Params("id")
|
||||
if userID == "" {
|
||||
return resp.R400(c, "MISSING_ID", nil, "user id is required")
|
||||
}
|
||||
|
||||
var user auth.User
|
||||
if err := db.First(&user, userID).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return resp.R404(c, "USER_NOT_FOUND", nil, "user not found")
|
||||
}
|
||||
return resp.R500(c, "", nil, err.Error())
|
||||
}
|
||||
|
||||
if user.Username == "admin" {
|
||||
return resp.R403(c, "CANNOT_DELETE_ADMIN", nil, "cannot delete admin user")
|
||||
}
|
||||
|
||||
var count int64
|
||||
if err := db.Model(&auth.User{}).Count(&count).Error; err != nil {
|
||||
return resp.R500(c, "", nil, err.Error())
|
||||
}
|
||||
|
||||
if count <= 1 {
|
||||
return resp.R403(c, "LAST_USER", nil, "cannot delete the last user")
|
||||
}
|
||||
|
||||
if err := db.Delete(&user).Error; err != nil {
|
||||
return resp.R500(c, "", nil, err.Error())
|
||||
}
|
||||
|
||||
return resp.R200(c, map[string]interface{}{
|
||||
"message": "user deleted successfully",
|
||||
})
|
||||
}
|
||||
}
|
||||
108
internal/module/auth/wallpaper.go
Normal file
108
internal/module/auth/wallpaper.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.loveuer.com/loveuer/cluster/pkg/resp"
|
||||
"github.com/go-resty/resty/v2"
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
func Wallpaper(ctx context.Context) fiber.Handler {
|
||||
type Result struct {
|
||||
Images []struct {
|
||||
Startdate string `json:"startdate"`
|
||||
Fullstartdate string `json:"fullstartdate"`
|
||||
Enddate string `json:"enddate"`
|
||||
URL string `json:"url"`
|
||||
Urlbase string `json:"urlbase"`
|
||||
Copyright string `json:"copyright"`
|
||||
Copyrightlink string `json:"copyrightlink"`
|
||||
Title string `json:"title"`
|
||||
Quiz string `json:"quiz"`
|
||||
Wp bool `json:"wp"`
|
||||
Hsh string `json:"hsh"`
|
||||
Drk int `json:"drk"`
|
||||
Top int `json:"top"`
|
||||
Bot int `json:"bot"`
|
||||
} `json:"images"`
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
sync.Mutex
|
||||
Date string `json:"date"`
|
||||
Body []byte `json:"body"`
|
||||
Headers map[string]string `json:"headers"`
|
||||
}
|
||||
|
||||
client := resty.New().SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
|
||||
apiUrl := "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1"
|
||||
imgUrlPrefix := "https://cn.bing.com"
|
||||
store := &Store{}
|
||||
|
||||
get := func() ([]byte, map[string]string, error) {
|
||||
var (
|
||||
err error
|
||||
rr *resty.Response
|
||||
result = new(Result)
|
||||
headers = make(map[string]string)
|
||||
date = time.Now().Format("2006-01-02")
|
||||
)
|
||||
|
||||
if store.Date == date {
|
||||
return store.Body, store.Headers, nil
|
||||
}
|
||||
|
||||
if _, err = client.R().
|
||||
SetResult(result).
|
||||
Get(apiUrl); err != nil {
|
||||
return nil, nil, fmt.Errorf("[BingWallpaper] get %s err: %w", apiUrl, err)
|
||||
}
|
||||
|
||||
if len(result.Images) == 0 {
|
||||
err = errors.New("[BingWallpaper]: image length = 0")
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
address := fmt.Sprintf("%s%s", imgUrlPrefix, result.Images[0].URL)
|
||||
|
||||
if rr, err = client.R().
|
||||
Get(address); err != nil {
|
||||
err = fmt.Errorf("[BingWallpaper] get image body: %s err: %w", address, err)
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
for key := range rr.Header() {
|
||||
headers[key] = strings.Join(rr.Header()[key], ", ")
|
||||
}
|
||||
|
||||
store.Lock()
|
||||
store.Date = date
|
||||
store.Body = rr.Body()
|
||||
store.Headers = headers
|
||||
store.Unlock()
|
||||
|
||||
return rr.Body(), headers, nil
|
||||
}
|
||||
|
||||
return func(c fiber.Ctx) error {
|
||||
bs, headers, err := get()
|
||||
if err != nil {
|
||||
return resp.R500(c, "", nil, err.Error())
|
||||
}
|
||||
|
||||
for key := range headers {
|
||||
c.Set(key, headers[key])
|
||||
}
|
||||
|
||||
_, err = c.Write(bs)
|
||||
|
||||
return err
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user