78 lines
1.4 KiB
Go
78 lines
1.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"github.com/gorilla/securecookie"
|
|
)
|
|
|
|
const (
|
|
AuthorizeCookie = "authorize"
|
|
ContextUser ctxKey = "context_user"
|
|
)
|
|
|
|
var secureCookie *securecookie.SecureCookie
|
|
|
|
type ctxKey string
|
|
|
|
type Authorize struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
func SetSecureCookie(sc *securecookie.SecureCookie) {
|
|
secureCookie = sc
|
|
}
|
|
|
|
func Encode(name string, value any) (string, error) {
|
|
return secureCookie.Encode(name, value)
|
|
}
|
|
|
|
func MyAuthorize(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
u := GetUser(r.Context())
|
|
if u == nil {
|
|
http.Redirect(w, r, "/login", http.StatusFound)
|
|
return
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
func SetUser(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
cookie, err := r.Cookie(AuthorizeCookie)
|
|
if err != nil {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
if cookie == nil || len(cookie.Value) == 0 {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
u := Authorize{}
|
|
err = secureCookie.Decode(AuthorizeCookie, cookie.Value, &u)
|
|
if err != nil {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
ctx := r.Context()
|
|
ctx = context.WithValue(ctx, ContextUser, u)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
func GetUser(ctx context.Context) *Authorize {
|
|
val := ctx.Value(ContextUser)
|
|
if u, ok := val.(Authorize); ok {
|
|
return &u
|
|
}
|
|
|
|
return nil
|
|
}
|