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.

73 lines
2.1 KiB

  1. package queries
  2. import (
  3. "context"
  4. "errors"
  5. "time"
  6. "git.aiterp.net/rpdata/api/internal/auth"
  7. "git.aiterp.net/rpdata/api/models/stories"
  8. "git.aiterp.net/rpdata/api/graph2/input"
  9. "git.aiterp.net/rpdata/api/models"
  10. "git.aiterp.net/rpdata/api/models/chapters"
  11. )
  12. func (r *resolver) Chapter(ctx context.Context, id string) (models.Chapter, error) {
  13. return chapters.FindID(id)
  14. }
  15. func (r *mutationResolver) AddChapter(ctx context.Context, input input.ChapterAddInput) (models.Chapter, error) {
  16. story, err := stories.FindID(input.StoryID)
  17. if err != nil {
  18. return models.Chapter{}, errors.New("Story not found")
  19. }
  20. token := auth.TokenFromContext(ctx)
  21. if !token.Authenticated() {
  22. return models.Chapter{}, errors.New("Unauthorized")
  23. }
  24. author := token.UserID
  25. if input.Author != nil && *input.Author != author {
  26. if !token.Permitted("story.add") {
  27. return models.Chapter{}, errors.New("False pretender")
  28. }
  29. author = *input.Author
  30. }
  31. if !story.Open && story.Author != author {
  32. return models.Chapter{}, errors.New("Story is not open")
  33. }
  34. return chapters.Add(story, input.Title, author, input.Source, time.Now(), input.FictionalDate)
  35. }
  36. func (r *mutationResolver) EditChapter(ctx context.Context, input input.ChapterEditInput) (models.Chapter, error) {
  37. chapter, err := chapters.FindID(input.ID)
  38. if err != nil {
  39. return models.Chapter{}, errors.New("Chapter not found")
  40. }
  41. token := auth.TokenFromContext(ctx)
  42. if !token.Authenticated() || !token.PermittedUser(chapter.Author, "member", "story.edit") {
  43. return models.Chapter{}, errors.New("Unauthorized")
  44. }
  45. return chapters.Edit(chapter, input.Title, input.Source, input.FictionalDate)
  46. }
  47. func (r *mutationResolver) RemoveChapter(ctx context.Context, input input.ChapterRemoveInput) (models.Chapter, error) {
  48. chapter, err := chapters.FindID(input.ID)
  49. if err != nil {
  50. return models.Chapter{}, errors.New("Chapter not found")
  51. }
  52. token := auth.TokenFromContext(ctx)
  53. if !token.Authenticated() || !token.PermittedUser(chapter.Author, "member", "story.remove") {
  54. return models.Chapter{}, errors.New("Unauthorized")
  55. }
  56. return chapters.Remove(chapter)
  57. }