2025-03-21 11:05:42 +08:00

84 lines
1.8 KiB
Go

package auth
import (
"context"
"encoding/json"
"net/http"
"management/internal/db/model/dto"
"management/internal/global/auth"
"management/internal/pkg/session"
systemservice "management/internal/service/system"
)
var defaultMenus = map[string]bool{
"/home.html": true,
"/system/menus": true,
"/upload/img": true,
"/upload/file": true,
"/upload/mutilfile": true,
"/pear.json": true,
}
func Authorize(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user, ok := isLogin(ctx)
if !ok {
http.Redirect(w, r, "/", http.StatusFound)
return
}
if user == nil {
http.Error(w, "user not found", http.StatusUnauthorized)
return
}
// 登陆成功 判断权限
// 默认权限判断
path := r.URL.Path
if b, ok := defaultMenus[path]; ok && b {
next.ServeHTTP(w, r)
return
}
menus, err := systemservice.MapOwnerMenuByRoleID(ctx, user.RoleID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, ok := menus[path]; ok {
next.ServeHTTP(w, r)
return
}
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}
return http.HandlerFunc(fn)
}
func isLogin(ctx context.Context) (*dto.AuthorizeUser, bool) {
if exists := session.Exists(ctx, auth.StoreName); exists {
b := session.GetBytes(ctx, auth.StoreName)
var user dto.AuthorizeUser
if err := json.Unmarshal(b, &user); err != nil {
return nil, false
}
return &user, true
}
return nil, false
}
func AuthUser(ctx context.Context) dto.AuthorizeUser {
var user dto.AuthorizeUser
if exists := session.Exists(ctx, auth.StoreName); exists {
b := session.GetBytes(ctx, auth.StoreName)
_ = json.Unmarshal(b, &user)
}
return user
}