You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.2 KiB

  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. api "code.gitea.io/sdk/gitea"
  7. "code.gitea.io/gitea/models"
  8. "code.gitea.io/gitea/modules/context"
  9. "code.gitea.io/gitea/modules/setting"
  10. "code.gitea.io/gitea/routers/api/v1/convert"
  11. )
  12. // ListEmails list all the emails of mine
  13. // see https://github.com/gogits/go-gogs-client/wiki/Users-Emails#list-email-addresses-for-a-user
  14. func ListEmails(ctx *context.APIContext) {
  15. emails, err := models.GetEmailAddresses(ctx.User.ID)
  16. if err != nil {
  17. ctx.Error(500, "GetEmailAddresses", err)
  18. return
  19. }
  20. apiEmails := make([]*api.Email, len(emails))
  21. for i := range emails {
  22. apiEmails[i] = convert.ToEmail(emails[i])
  23. }
  24. ctx.JSON(200, &apiEmails)
  25. }
  26. // AddEmail add email for me
  27. // see https://github.com/gogits/go-gogs-client/wiki/Users-Emails#add-email-addresses
  28. func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) {
  29. if len(form.Emails) == 0 {
  30. ctx.Status(422)
  31. return
  32. }
  33. emails := make([]*models.EmailAddress, len(form.Emails))
  34. for i := range form.Emails {
  35. emails[i] = &models.EmailAddress{
  36. UID: ctx.User.ID,
  37. Email: form.Emails[i],
  38. IsActivated: !setting.Service.RegisterEmailConfirm,
  39. }
  40. }
  41. if err := models.AddEmailAddresses(emails); err != nil {
  42. if models.IsErrEmailAlreadyUsed(err) {
  43. ctx.Error(422, "", "Email address has been used: "+err.(models.ErrEmailAlreadyUsed).Email)
  44. } else {
  45. ctx.Error(500, "AddEmailAddresses", err)
  46. }
  47. return
  48. }
  49. apiEmails := make([]*api.Email, len(emails))
  50. for i := range emails {
  51. apiEmails[i] = convert.ToEmail(emails[i])
  52. }
  53. ctx.JSON(201, &apiEmails)
  54. }
  55. // DeleteEmail delete email
  56. // see https://github.com/gogits/go-gogs-client/wiki/Users-Emails#delete-email-addresses
  57. func DeleteEmail(ctx *context.APIContext, form api.CreateEmailOption) {
  58. if len(form.Emails) == 0 {
  59. ctx.Status(204)
  60. return
  61. }
  62. emails := make([]*models.EmailAddress, len(form.Emails))
  63. for i := range form.Emails {
  64. emails[i] = &models.EmailAddress{
  65. Email: form.Emails[i],
  66. }
  67. }
  68. if err := models.DeleteEmailAddresses(emails); err != nil {
  69. ctx.Error(500, "DeleteEmailAddresses", err)
  70. return
  71. }
  72. ctx.Status(204)
  73. }