2024-07-12 20:32:33 +08:00
|
|
|
|
package middleware
|
|
|
|
|
|
|
|
|
|
import (
|
2024-07-16 20:32:22 +08:00
|
|
|
|
"context"
|
2024-08-09 20:30:35 +08:00
|
|
|
|
"github.com/gorilla/sessions"
|
2024-07-12 20:32:33 +08:00
|
|
|
|
"net/http"
|
2024-07-13 20:33:20 +08:00
|
|
|
|
"picgo/configs"
|
|
|
|
|
"picgo/corelib"
|
|
|
|
|
"picgo/data"
|
2024-07-16 20:32:22 +08:00
|
|
|
|
"picgo/model"
|
2024-07-13 20:33:20 +08:00
|
|
|
|
"strings"
|
2024-07-12 20:32:33 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// LoginMiddleware 登录 // 添加日志中间件到路由器 使用:r.Handle("/", LoginMiddleware(http.HandlerFunc(handler)))
|
|
|
|
|
func LoginMiddleware(next http.Handler) http.Handler {
|
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2024-08-09 20:30:35 +08:00
|
|
|
|
var (
|
|
|
|
|
user model.SysUser
|
|
|
|
|
err error
|
|
|
|
|
session *sessions.Session
|
|
|
|
|
)
|
2024-07-13 20:33:20 +08:00
|
|
|
|
resPath := r.URL.Path
|
|
|
|
|
if resPath == "/login" || resPath == "/captcha" || strings.HasPrefix(resPath, "/static") {
|
|
|
|
|
next.ServeHTTP(w, r)
|
|
|
|
|
}
|
2024-08-09 20:30:35 +08:00
|
|
|
|
if session, err = corelib.SessionStore.Get(r, configs.Settings.Server.SessionName); err == nil {
|
|
|
|
|
|
|
|
|
|
}
|
2024-07-13 20:33:20 +08:00
|
|
|
|
username, ok := session.Values["username"].(string)
|
|
|
|
|
if !ok || username == "" {
|
|
|
|
|
http.Redirect(w, r, "/login", http.StatusFound)
|
|
|
|
|
return
|
|
|
|
|
}
|
2024-07-16 20:32:22 +08:00
|
|
|
|
if user, err = data.SysUserSelectByUsername(username); err != nil {
|
2024-07-13 20:33:20 +08:00
|
|
|
|
http.Redirect(w, r, "/login", http.StatusFound)
|
|
|
|
|
return
|
|
|
|
|
}
|
2024-08-09 20:30:35 +08:00
|
|
|
|
// 权限判断
|
|
|
|
|
if user.IsSuper != 1 && (resPath != "/" && resPath != "/api/v1/upload") {
|
|
|
|
|
http.Error(w, "没有权限访问", 403)
|
|
|
|
|
return
|
|
|
|
|
}
|
2024-07-16 20:32:22 +08:00
|
|
|
|
ctx := context.WithValue(r.Context(), "username", user.Username)
|
|
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
2024-07-12 20:32:33 +08:00
|
|
|
|
})
|
|
|
|
|
}
|