Files
Gogs/internal/route/api/v1/user/email.go

83 lines
1.9 KiB
Go
Raw Normal View History

2015-12-15 22:57:18 -05:00
// Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package user
import (
2019-08-08 23:53:43 -07:00
"net/http"
2018-05-27 08:53:48 +08:00
api "github.com/gogs/go-gogs-client"
"github.com/pkg/errors"
2015-12-15 22:57:18 -05:00
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/db"
"gogs.io/gogs/internal/route/api/v1/convert"
2015-12-15 22:57:18 -05:00
)
2017-06-03 07:26:09 -04:00
func ListEmails(c *context.APIContext) {
emails, err := db.GetEmailAddresses(c.User.ID)
2015-12-15 22:57:18 -05:00
if err != nil {
c.Error(err, "get email addresses")
2015-12-15 22:57:18 -05:00
return
}
apiEmails := make([]*api.Email, len(emails))
for i := range emails {
apiEmails[i] = convert.ToEmail(emails[i])
2015-12-15 22:57:18 -05:00
}
2019-08-08 23:53:43 -07:00
c.JSONSuccess(&apiEmails)
2015-12-15 22:57:18 -05:00
}
2017-06-03 07:26:09 -04:00
func AddEmail(c *context.APIContext, form api.CreateEmailOption) {
2015-12-15 22:57:18 -05:00
if len(form.Emails) == 0 {
2019-08-08 23:53:43 -07:00
c.Status(http.StatusUnprocessableEntity)
2015-12-15 22:57:18 -05:00
return
}
emails := make([]*db.EmailAddress, len(form.Emails))
2015-12-15 22:57:18 -05:00
for i := range form.Emails {
emails[i] = &db.EmailAddress{
UserID: c.User.ID,
2015-12-15 22:57:18 -05:00
Email: form.Emails[i],
IsActivated: !conf.Auth.RequireEmailConfirmation,
2015-12-15 22:57:18 -05:00
}
}
if err := db.AddEmailAddresses(emails); err != nil {
if db.IsErrEmailAlreadyUsed(err) {
c.ErrorStatus(http.StatusUnprocessableEntity, errors.New("email address has been used: "+err.(db.ErrEmailAlreadyUsed).Email()))
2015-12-15 22:57:18 -05:00
} else {
c.Error(err, "add email addresses")
2015-12-15 22:57:18 -05:00
}
return
}
apiEmails := make([]*api.Email, len(emails))
for i := range emails {
apiEmails[i] = convert.ToEmail(emails[i])
2015-12-15 22:57:18 -05:00
}
2019-08-08 23:53:43 -07:00
c.JSON(http.StatusCreated, &apiEmails)
2015-12-15 22:57:18 -05:00
}
2017-06-03 07:26:09 -04:00
func DeleteEmail(c *context.APIContext, form api.CreateEmailOption) {
2015-12-15 22:57:18 -05:00
if len(form.Emails) == 0 {
2019-08-08 23:53:43 -07:00
c.NoContent()
2015-12-15 22:57:18 -05:00
return
}
emails := make([]*db.EmailAddress, len(form.Emails))
2015-12-15 22:57:18 -05:00
for i := range form.Emails {
emails[i] = &db.EmailAddress{
UserID: c.User.ID,
Email: form.Emails[i],
2015-12-15 22:57:18 -05:00
}
}
if err := db.DeleteEmailAddresses(emails); err != nil {
c.Error(err, "delete email addresses")
2015-12-15 22:57:18 -05:00
return
}
2019-08-08 23:53:43 -07:00
c.NoContent()
2015-12-15 22:57:18 -05:00
}