email.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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.Users.ListEmails(c.Req.Context(), 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. apiEmails := make([]*api.Email, 0, len(form.Emails))
  32. for _, email := range form.Emails {
  33. err := db.Users.AddEmail(c.Req.Context(), c.User.ID, email, !conf.Auth.RequireEmailConfirmation)
  34. if err != nil {
  35. if db.IsErrEmailAlreadyUsed(err) {
  36. c.ErrorStatus(http.StatusUnprocessableEntity, errors.Errorf("email address has been used: %s", err.(db.ErrEmailAlreadyUsed).Email()))
  37. } else {
  38. c.Error(err, "add email addresses")
  39. }
  40. return
  41. }
  42. apiEmails = append(apiEmails,
  43. &api.Email{
  44. Email: email,
  45. Verified: !conf.Auth.RequireEmailConfirmation,
  46. },
  47. )
  48. }
  49. c.JSON(http.StatusCreated, &apiEmails)
  50. }
  51. func DeleteEmail(c *context.APIContext, form api.CreateEmailOption) {
  52. for _, email := range form.Emails {
  53. if email == c.User.Email {
  54. c.ErrorStatus(http.StatusBadRequest, errors.Errorf("cannot delete primary email %q", email))
  55. return
  56. }
  57. err := db.Users.DeleteEmail(c.Req.Context(), c.User.ID, email)
  58. if err != nil {
  59. c.Error(err, "delete email addresses")
  60. return
  61. }
  62. }
  63. c.NoContent()
  64. }