email.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. "net/http"
  7. api "github.com/gogs/go-gogs-client"
  8. "github.com/gogs/gogs/models"
  9. "github.com/gogs/gogs/pkg/context"
  10. "github.com/gogs/gogs/pkg/setting"
  11. "github.com/gogs/gogs/routes/api/v1/convert"
  12. )
  13. func ListEmails(c *context.APIContext) {
  14. emails, err := models.GetEmailAddresses(c.User.ID)
  15. if err != nil {
  16. c.ServerError("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.JSONSuccess(&apiEmails)
  24. }
  25. func AddEmail(c *context.APIContext, form api.CreateEmailOption) {
  26. if len(form.Emails) == 0 {
  27. c.Status(http.StatusUnprocessableEntity)
  28. return
  29. }
  30. emails := make([]*models.EmailAddress, len(form.Emails))
  31. for i := range form.Emails {
  32. emails[i] = &models.EmailAddress{
  33. UID: c.User.ID,
  34. Email: form.Emails[i],
  35. IsActivated: !setting.Service.RegisterEmailConfirm,
  36. }
  37. }
  38. if err := models.AddEmailAddresses(emails); err != nil {
  39. if models.IsErrEmailAlreadyUsed(err) {
  40. c.Error(http.StatusUnprocessableEntity, "", "email address has been used: "+err.(models.ErrEmailAlreadyUsed).Email)
  41. } else {
  42. c.Error(http.StatusInternalServerError, "AddEmailAddresses", err)
  43. }
  44. return
  45. }
  46. apiEmails := make([]*api.Email, len(emails))
  47. for i := range emails {
  48. apiEmails[i] = convert.ToEmail(emails[i])
  49. }
  50. c.JSON(http.StatusCreated, &apiEmails)
  51. }
  52. func DeleteEmail(c *context.APIContext, form api.CreateEmailOption) {
  53. if len(form.Emails) == 0 {
  54. c.NoContent()
  55. return
  56. }
  57. emails := make([]*models.EmailAddress, len(form.Emails))
  58. for i := range form.Emails {
  59. emails[i] = &models.EmailAddress{
  60. UID: c.User.ID,
  61. Email: form.Emails[i],
  62. }
  63. }
  64. if err := models.DeleteEmailAddresses(emails); err != nil {
  65. c.Error(http.StatusInternalServerError, "DeleteEmailAddresses", err)
  66. return
  67. }
  68. c.NoContent()
  69. }