GraphQL API and utilities for the rpdata project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.3 KiB

  1. package auth
  2. import (
  3. "context"
  4. "reflect"
  5. "git.aiterp.net/rpdata/api/models"
  6. )
  7. // CheckPermission does some magic.
  8. func CheckPermission(ctx context.Context, op string, obj interface{}) error {
  9. token := TokenFromContext(ctx)
  10. if token == nil {
  11. return ErrUnauthenticated
  12. }
  13. if reflect.TypeOf(obj).Kind() != reflect.Ptr {
  14. return CheckPermission(ctx, op, &obj)
  15. }
  16. var authorized = false
  17. switch v := obj.(type) {
  18. case *models.Channel:
  19. authorized = token.Permitted("channel." + op)
  20. case *models.Character:
  21. authorized = token.PermittedUser(v.Author, "member", "character."+op)
  22. case *models.Chapter:
  23. authorized = token.PermittedUser(v.Author, "member", "chapter."+op)
  24. case *models.Comment:
  25. if op == "add" && v.Author != token.UserID {
  26. return ErrInvalidOperation
  27. }
  28. authorized = token.PermittedUser(v.Author, "member", "comment."+op)
  29. case *models.File:
  30. authorized = token.PermittedUser(v.Author, "member", "file."+op)
  31. case *models.Log:
  32. authorized = token.Permitted("log." + op)
  33. case *models.Post:
  34. authorized = token.Permitted("post." + op)
  35. case *models.Story:
  36. authorized = token.PermittedUser(v.Author, "member", "story."+op)
  37. case *models.User:
  38. authorized = token.Permitted("user." + op)
  39. }
  40. if !authorized {
  41. return ErrUnauthorized
  42. }
  43. return nil
  44. }