email.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package user
  5. import (
  6. api "github.com/gogs/go-gogs-client"
  7. "github.com/gogs/gogs/models"
  8. "github.com/gogs/gogs/pkg/context"
  9. "github.com/gogs/gogs/pkg/setting"
  10. "github.com/gogs/gogs/routes/api/v1/convert"
  11. )
  12. // https://github.com/gogs/go-gogs-client/wiki/Users-Emails#list-email-addresses-for-a-user
  13. func ListEmails(c *context.APIContext) {
  14. emails, err := models.GetEmailAddresses(c.User.ID)
  15. if err != nil {
  16. c.Error(500, "GetEmailAddresses", err)
  17. return
  18. }
  19. apiEmails := make([]*api.Email, len(emails))
  20. for i := range emails {
  21. apiEmails[i] = convert.ToEmail(emails[i])
  22. }
  23. c.JSON(200, &apiEmails)
  24. }
  25. // https://github.com/gogs/go-gogs-client/wiki/Users-Emails#add-email-addresses
  26. func AddEmail(c *context.APIContext, form api.CreateEmailOption) {
  27. if len(form.Emails) == 0 {
  28. c.Status(422)
  29. return
  30. }
  31. emails := make([]*models.EmailAddress, len(form.Emails))
  32. for i := range form.Emails {
  33. emails[i] = &models.EmailAddress{
  34. UID: c.User.ID,
  35. Email: form.Emails[i],
  36. IsActivated: !setting.Service.RegisterEmailConfirm,
  37. }
  38. }
  39. if err := models.AddEmailAddresses(emails); err != nil {
  40. if models.IsErrEmailAlreadyUsed(err) {
  41. c.Error(422, "", "Email address has been used: "+err.(models.ErrEmailAlreadyUsed).Email)
  42. } else {
  43. c.Error(500, "AddEmailAddresses", err)
  44. }
  45. return
  46. }
  47. apiEmails := make([]*api.Email, len(emails))
  48. for i := range emails {
  49. apiEmails[i] = convert.ToEmail(emails[i])
  50. }
  51. c.JSON(201, &apiEmails)
  52. }
  53. // https://github.com/gogs/go-gogs-client/wiki/Users-Emails#delete-email-addresses
  54. func DeleteEmail(c *context.APIContext, form api.CreateEmailOption) {
  55. if len(form.Emails) == 0 {
  56. c.Status(204)
  57. return
  58. }
  59. emails := make([]*models.EmailAddress, len(form.Emails))
  60. for i := range form.Emails {
  61. emails[i] = &models.EmailAddress{
  62. UID: c.User.ID,
  63. Email: form.Emails[i],
  64. }
  65. }
  66. if err := models.DeleteEmailAddresses(emails); err != nil {
  67. c.Error(500, "DeleteEmailAddresses", err)
  68. return
  69. }
  70. c.Status(204)
  71. }