66 lines
1.2 KiB
Go
66 lines
1.2 KiB
Go
package server
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
)
|
|
|
|
type AccessContext struct {
|
|
Kind string
|
|
TenantID int64
|
|
UserID int64
|
|
Role string
|
|
Token string
|
|
}
|
|
|
|
func (s *Server) ResolveAccess(r *http.Request, masterToken uint64) (*AccessContext, bool) {
|
|
tok := BearerToken(r)
|
|
if tok == "" {
|
|
return nil, false
|
|
}
|
|
|
|
if tok == strconv.FormatUint(masterToken, 10) {
|
|
return &AccessContext{Kind: "master", Role: "admin", Token: tok}, true
|
|
}
|
|
|
|
return s.ResolveTenantAccessToken(tok)
|
|
}
|
|
|
|
func GetAccessContext(r *http.Request) *AccessContext {
|
|
v := r.Context().Value(ServerCtxKeyAccess{})
|
|
if v == nil {
|
|
return nil
|
|
}
|
|
if ac, ok := v.(*AccessContext); ok {
|
|
return ac
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) ResolveTenantAccessToken(tok string) (*AccessContext, bool) {
|
|
if tok == "" || s.store == nil {
|
|
return nil, false
|
|
}
|
|
|
|
if ss, err := s.store.VerifySessionToken(tok); err == nil && ss != nil {
|
|
return &AccessContext{
|
|
Kind: "session",
|
|
TenantID: ss.TenantID,
|
|
UserID: ss.UserID,
|
|
Role: ss.Role,
|
|
Token: tok,
|
|
}, true
|
|
}
|
|
|
|
if ten, err := s.store.VerifyAPIKey(tok); err == nil && ten != nil {
|
|
return &AccessContext{
|
|
Kind: "apikey",
|
|
TenantID: ten.ID,
|
|
Role: "apikey",
|
|
Token: tok,
|
|
}, true
|
|
}
|
|
|
|
return nil, false
|
|
}
|