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