email.go 1.9 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. "net/http"
  7. api "github.com/gogs/go-gogs-client"
  8. "github.com/pkg/errors"
  9. "gogs.io/gogs/internal/conf"
  10. "gogs.io/gogs/internal/context"
  11. "gogs.io/gogs/internal/db"
  12. "gogs.io/gogs/internal/route/api/v1/convert"
  13. )
  14. func ListEmails(c *context.APIContext) {
  15. emails, err := db.GetEmailAddresses(c.User.ID)
  16. if err != nil {
  17. c.Error(err, "get email addresses")
  18. return
  19. }
  20. apiEmails := make([]*api.Email, len(emails))
  21. for i := range emails {
  22. apiEmails[i] = convert.ToEmail(emails[i])
  23. }
  24. c.JSONSuccess(&apiEmails)
  25. }
  26. func AddEmail(c *context.APIContext, form api.CreateEmailOption) {
  27. if len(form.Emails) == 0 {
  28. c.Status(http.StatusUnprocessableEntity)
  29. return
  30. }
  31. emails := make([]*db.EmailAddress, len(form.Emails))
  32. for i := range form.Emails {
  33. emails[i] = &db.EmailAddress{
  34. UID: c.User.ID,
  35. Email: form.Emails[i],
  36. IsActivated: !conf.Auth.RequireEmailConfirmation,
  37. }
  38. }
  39. if err := db.AddEmailAddresses(emails); err != nil {
  40. if db.IsErrEmailAlreadyUsed(err) {
  41. c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("email address has been used: "+err.(db.ErrEmailAlreadyUsed).Email))
  42. } else {
  43. c.Error(err, "add email addresses")
  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(http.StatusCreated, &apiEmails)
  52. }
  53. func DeleteEmail(c *context.APIContext, form api.CreateEmailOption) {
  54. if len(form.Emails) == 0 {
  55. c.NoContent()
  56. return
  57. }
  58. emails := make([]*db.EmailAddress, len(form.Emails))
  59. for i := range form.Emails {
  60. emails[i] = &db.EmailAddress{
  61. UID: c.User.ID,
  62. Email: form.Emails[i],
  63. }
  64. }
  65. if err := db.DeleteEmailAddresses(emails); err != nil {
  66. c.Error(err, "delete email addresses")
  67. return
  68. }
  69. c.NoContent()
  70. }