context.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package auth
  2. import (
  3. "context"
  4. "errors"
  5. )
  6. // contextKey is the type for context keys in this package
  7. type contextKey string
  8. const (
  9. userKey contextKey = "user"
  10. )
  11. // UserContext represents the authenticated user in context
  12. type UserContext struct {
  13. ID uint
  14. Email string
  15. Roles []RoleClaim
  16. Permissions []string
  17. }
  18. // WithUser adds a user to the context
  19. func WithUser(ctx context.Context, user *UserContext) context.Context {
  20. return context.WithValue(ctx, userKey, user)
  21. }
  22. // CurrentUser retrieves the user from context
  23. func CurrentUser(ctx context.Context) (*UserContext, error) {
  24. user, ok := ctx.Value(userKey).(*UserContext)
  25. if !ok {
  26. return nil, errors.New("no user in context")
  27. }
  28. return user, nil
  29. }
  30. // HasPermission checks if the current user has a specific permission
  31. func HasPermission(ctx context.Context, permissionCode string) bool {
  32. user, err := CurrentUser(ctx)
  33. if err != nil {
  34. return false
  35. }
  36. for _, perm := range user.Permissions {
  37. if perm == permissionCode {
  38. return true
  39. }
  40. }
  41. return false
  42. }
  43. // HasAnyPermission checks if the current user has any of the specified permissions
  44. func HasAnyPermission(ctx context.Context, permissionCodes ...string) bool {
  45. user, err := CurrentUser(ctx)
  46. if err != nil {
  47. return false
  48. }
  49. permSet := make(map[string]bool)
  50. for _, perm := range user.Permissions {
  51. permSet[perm] = true
  52. }
  53. for _, code := range permissionCodes {
  54. if permSet[code] {
  55. return true
  56. }
  57. }
  58. return false
  59. }
  60. // IsAuthenticated checks if there's an authenticated user in context
  61. func IsAuthenticated(ctx context.Context) bool {
  62. _, err := CurrentUser(ctx)
  63. return err == nil
  64. }