83 lines
1.8 KiB
Go
83 lines
1.8 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"management/internal/db/model/dto"
|
|
"management/internal/pkg/know"
|
|
)
|
|
|
|
var defaultMenus = map[string]bool{
|
|
"/home.html": true,
|
|
"/dashboard": true,
|
|
"/system/menus": true,
|
|
"/upload/img": true,
|
|
"/upload/file": true,
|
|
"/upload/mutilfile": true,
|
|
"/pear.json": true,
|
|
}
|
|
|
|
func (m *middleware) Authorize(next http.Handler) http.Handler {
|
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
user, ok := m.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 := m.biz.MenuBiz().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 (m *middleware) isLogin(ctx context.Context) (*dto.AuthorizeUser, bool) {
|
|
if exists := m.session.Exists(ctx, know.StoreName); exists {
|
|
b := m.session.GetBytes(ctx, know.StoreName)
|
|
var user dto.AuthorizeUser
|
|
if err := json.Unmarshal(b, &user); err != nil {
|
|
return nil, false
|
|
}
|
|
return &user, true
|
|
}
|
|
|
|
return nil, false
|
|
}
|
|
|
|
func (m *middleware) AuthUser(ctx context.Context) dto.AuthorizeUser {
|
|
var user dto.AuthorizeUser
|
|
if exists := m.session.Exists(ctx, know.StoreName); exists {
|
|
b := m.session.GetBytes(ctx, know.StoreName)
|
|
_ = json.Unmarshal(b, &user)
|
|
}
|
|
return user
|
|
}
|