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.

81 lines
2.2 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. // Queries
  13. func (r *resolver) Chapter(ctx context.Context, id string) (models.Chapter, error) {
  14. return chapters.FindID(id)
  15. }
  16. // Mutations
  17. func (r *mutationResolver) AddChapter(ctx context.Context, input input.ChapterAddInput) (models.Chapter, error) {
  18. story, err := stories.FindID(input.StoryID)
  19. if err != nil {
  20. return models.Chapter{}, errors.New("Story not found")
  21. }
  22. token := auth.TokenFromContext(ctx)
  23. if !token.Authenticated() {
  24. return models.Chapter{}, errors.New("Unauthorized")
  25. }
  26. author := token.UserID
  27. if input.Author != nil && *input.Author != author {
  28. if !token.Permitted("story.add") {
  29. return models.Chapter{}, errors.New("False pretender")
  30. }
  31. author = *input.Author
  32. }
  33. if !story.Open && story.Author != author {
  34. return models.Chapter{}, errors.New("Story is not open")
  35. }
  36. return chapters.Add(story, input.Title, author, input.Source, time.Now(), input.FictionalDate)
  37. }
  38. func (r *mutationResolver) EditChapter(ctx context.Context, input input.ChapterEditInput) (models.Chapter, error) {
  39. chapter, err := chapters.FindID(input.ID)
  40. if err != nil {
  41. return models.Chapter{}, errors.New("Chapter not found")
  42. }
  43. token := auth.TokenFromContext(ctx)
  44. if !token.Authenticated() || !token.PermittedUser(chapter.Author, "member", "story.edit") {
  45. return models.Chapter{}, errors.New("Unauthorized")
  46. }
  47. if input.ClearFictionalDate != nil && *input.ClearFictionalDate == true {
  48. input.FictionalDate = &time.Time{}
  49. }
  50. return chapters.Edit(chapter, input.Title, input.Source, input.FictionalDate)
  51. }
  52. func (r *mutationResolver) RemoveChapter(ctx context.Context, input input.ChapterRemoveInput) (models.Chapter, error) {
  53. chapter, err := chapters.FindID(input.ID)
  54. if err != nil {
  55. return models.Chapter{}, errors.New("Chapter not found")
  56. }
  57. token := auth.TokenFromContext(ctx)
  58. if !token.Authenticated() || !token.PermittedUser(chapter.Author, "member", "story.remove") {
  59. return models.Chapter{}, errors.New("Unauthorized")
  60. }
  61. return chapters.Remove(chapter)
  62. }