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