56 lines
1.4 KiB
Go
56 lines
1.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"errors"
|
|
"net/http"
|
|
|
|
"git.red-panda.pet/pandaware/house/backend/db"
|
|
"git.red-panda.pet/pandaware/house/backend/router"
|
|
)
|
|
|
|
func Authenticated(ctx *router.Context) error {
|
|
sessionCookie, err := ctx.Cookie("session")
|
|
if err != nil {
|
|
return ctx.Error(err, http.StatusUnauthorized, "login required")
|
|
}
|
|
|
|
sessionBs, err := base64.StdEncoding.DecodeString(sessionCookie.Value)
|
|
if err != nil {
|
|
return ctx.Error(err, http.StatusUnauthorized, "login required")
|
|
}
|
|
|
|
hashedKey := sha256.Sum256(sessionBs)
|
|
|
|
session, err := ctx.Query.GetSession(ctx, hashedKey[:])
|
|
if err != nil {
|
|
return ctx.Error(err, http.StatusUnauthorized, "login required")
|
|
}
|
|
|
|
user, err := ctx.Query.GetUser(ctx, session.UserID)
|
|
if err != nil {
|
|
return ctx.Error(err, http.StatusUnauthorized, "login required")
|
|
}
|
|
|
|
ctx.With(sessionKey, session)
|
|
ctx.With(userKey, user)
|
|
|
|
return nil
|
|
}
|
|
|
|
func Session(route router.AuthorizedRoute, ctx *router.Context) db.Session {
|
|
user, ok := ctx.Value(sessionKey).(db.Session)
|
|
if !ok {
|
|
panic(errors.New("middleware.Session cannot be used from an unauthenticated route"))
|
|
}
|
|
return user
|
|
}
|
|
|
|
func User(route router.AuthorizedRoute, ctx *router.Context) db.GetUserRow {
|
|
user, ok := ctx.Value(userKey).(db.GetUserRow)
|
|
if !ok {
|
|
panic(errors.New("middleware.User cannot be used from an unauthenticated route"))
|
|
}
|
|
return user
|
|
}
|