email.go 2.1 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. 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. Email: form.Emails[i],
  63. }
  64. }
  65. if err := models.DeleteEmailAddresses(emails); err != nil {
  66. ctx.Error(500, "DeleteEmailAddresses", err)
  67. return
  68. }
  69. ctx.Status(204)
  70. }