Use middleware for user session
This commit is contained in:
49
context/users.go
Normal file
49
context/users.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package userctx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"git.kealoha.me/lks/lenslocked/models"
|
||||
)
|
||||
|
||||
type key string
|
||||
|
||||
const userKey key = "User"
|
||||
|
||||
func WithUser(ctx context.Context, user *models.User) context.Context {
|
||||
return context.WithValue(ctx, userKey, user)
|
||||
}
|
||||
|
||||
func User(ctx context.Context) *models.User {
|
||||
val := ctx.Value(userKey)
|
||||
user, ok := val.(*models.User)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
type UserMiddleware struct {
|
||||
SS *models.SessionService
|
||||
}
|
||||
|
||||
func (umw UserMiddleware) SetUser(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
seshCookie, err := r.Cookie("session")
|
||||
if err != nil {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
user, err := umw.SS.User(seshCookie.Value)
|
||||
if err != nil {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
ctx = WithUser(ctx, user)
|
||||
r = r.WithContext(ctx)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user