initial commit
This commit is contained in:
commit
d40b69f1f9
58 changed files with 7919 additions and 0 deletions
56
backend/middleware/authorize.go
Normal file
56
backend/middleware/authorize.go
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
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
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue