neko/internal/http/auth/auth.go

58 lines
1.2 KiB
Go
Raw Normal View History

2020-11-17 07:37:52 +13:00
package auth
import (
"context"
"net/http"
"demodesk/neko/internal/types"
"demodesk/neko/internal/utils"
)
type key int
const (
keySessionCtx key = iota
)
func SetSession(r *http.Request, session types.Session) *http.Request {
ctx := context.WithValue(r.Context(), keySessionCtx, session)
return r.WithContext(ctx)
}
func GetSession(r *http.Request) types.Session {
return r.Context().Value(keySessionCtx).(types.Session)
}
func AdminsOnly(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := GetSession(r)
if !session.Admin() {
2020-11-29 03:00:21 +13:00
utils.HttpForbidden(w)
2020-11-17 07:37:52 +13:00
} else {
next.ServeHTTP(w, r)
}
})
}
func HostsOnly(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := GetSession(r)
if !session.IsHost() {
2020-11-29 03:00:21 +13:00
utils.HttpForbidden(w, "Only host can do this.")
2020-11-17 07:37:52 +13:00
} else {
next.ServeHTTP(w, r)
}
})
}
func HostsOrAdminsOnly(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := GetSession(r)
if !session.IsHost() && !session.Admin() {
2020-11-29 03:00:21 +13:00
utils.HttpForbidden(w, "Only host can do this.")
2020-11-17 07:37:52 +13:00
} else {
next.ServeHTTP(w, r)
}
})
}