aboutsummaryrefslogtreecommitdiff
path: root/internal/route/api/v1/user/email.go
blob: b85d424a31b6210fd0714e90477a36f76c3db01b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// 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 (
	"net/http"

	api "github.com/gogs/go-gogs-client"
	"github.com/pkg/errors"

	"gogs.io/gogs/internal/conf"
	"gogs.io/gogs/internal/context"
	"gogs.io/gogs/internal/db"
	"gogs.io/gogs/internal/route/api/v1/convert"
)

func ListEmails(c *context.APIContext) {
	emails, err := db.Users.ListEmails(c.Req.Context(), c.User.ID)
	if err != nil {
		c.Error(err, "get email addresses")
		return
	}
	apiEmails := make([]*api.Email, len(emails))
	for i := range emails {
		apiEmails[i] = convert.ToEmail(emails[i])
	}
	c.JSONSuccess(&apiEmails)
}

func AddEmail(c *context.APIContext, form api.CreateEmailOption) {
	if len(form.Emails) == 0 {
		c.Status(http.StatusUnprocessableEntity)
		return
	}

	apiEmails := make([]*api.Email, 0, len(form.Emails))
	for _, email := range form.Emails {
		err := db.Users.AddEmail(c.Req.Context(), c.User.ID, email, !conf.Auth.RequireEmailConfirmation)
		if err != nil {
			if db.IsErrEmailAlreadyUsed(err) {
				c.ErrorStatus(http.StatusUnprocessableEntity, errors.Errorf("email address has been used: %s", err.(db.ErrEmailAlreadyUsed).Email()))
			} else {
				c.Error(err, "add email addresses")
			}
			return
		}

		apiEmails = append(apiEmails,
			&api.Email{
				Email:    email,
				Verified: !conf.Auth.RequireEmailConfirmation,
			},
		)
	}
	c.JSON(http.StatusCreated, &apiEmails)
}

func DeleteEmail(c *context.APIContext, form api.CreateEmailOption) {
	for _, email := range form.Emails {
		if email == c.User.Email {
			c.ErrorStatus(http.StatusBadRequest, errors.Errorf("cannot delete primary email %q", email))
			return
		}

		err := db.Users.DeleteEmail(c.Req.Context(), c.User.ID, email)
		if err != nil {
			c.Error(err, "delete email addresses")
			return
		}
	}
	c.NoContent()
}