email.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/database"
  12. "gogs.io/gogs/internal/route/api/v1/convert"
  13. )
  14. func ListEmails(c *context.APIContext) {
  15. emails, err := database.Handle.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 := database.Handle.Users().AddEmail(c.Req.Context(), c.User.ID, email, !conf.Auth.RequireEmailConfirmation)
  34. if err != nil {
  35. if database.IsErrEmailAlreadyUsed(err) {
  36. c.ErrorStatus(http.StatusUnprocessableEntity, errors.Errorf("email address has been used: %s", err.(database.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 := database.Handle.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. }