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. convert2 "gogs.io/gogs/internal/route/api/v1/convert"
  7. "net/http"
  8. api "github.com/gogs/go-gogs-client"
  9. "gogs.io/gogs/internal/conf"
  10. "gogs.io/gogs/internal/context"
  11. "gogs.io/gogs/internal/db"
  12. )
  13. func ListEmails(c *context.APIContext) {
  14. emails, err := db.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] = convert2.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([]*db.EmailAddress, len(form.Emails))
  31. for i := range form.Emails {
  32. emails[i] = &db.EmailAddress{
  33. UID: c.User.ID,
  34. Email: form.Emails[i],
  35. IsActivated: !conf.Auth.RequireEmailConfirmation,
  36. }
  37. }
  38. if err := db.AddEmailAddresses(emails); err != nil {
  39. if db.IsErrEmailAlreadyUsed(err) {
  40. c.Error(http.StatusUnprocessableEntity, "", "email address has been used: "+err.(db.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] = convert2.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([]*db.EmailAddress, len(form.Emails))
  58. for i := range form.Emails {
  59. emails[i] = &db.EmailAddress{
  60. UID: c.User.ID,
  61. Email: form.Emails[i],
  62. }
  63. }
  64. if err := db.DeleteEmailAddresses(emails); err != nil {
  65. c.Error(http.StatusInternalServerError, "DeleteEmailAddresses", err)
  66. return
  67. }
  68. c.NoContent()
  69. }