goshort/internal/server/middleware/auth/authMethods.go

40 lines
731 B
Go

package authmiddleware
import (
"context"
)
type (
authMethodCtxKey struct{}
AuthMethod string
)
const (
TokenAuth AuthMethod = "token"
SessionAuth AuthMethod = "session"
)
// authMethodFromCtx gets the current request's auth method.
func authMethodFromCtx(ctx context.Context) AuthMethod {
method, ok := ctx.Value(authMethodCtxKey{}).(AuthMethod)
if !ok || method == "" {
return ""
}
return method
}
// authMethodAllowed checks if the current request's auth method is allowed.
func authMethodAllowed(ctx context.Context, authMethods []AuthMethod) bool {
method := authMethodFromCtx(ctx)
for _, allowedMethod := range authMethods {
if allowedMethod == method {
return true
}
}
return false
}