-
Notifications
You must be signed in to change notification settings - Fork 657
Expand file tree
/
Copy pathmagic_link.go
More file actions
165 lines (143 loc) · 4.79 KB
/
magic_link.go
File metadata and controls
165 lines (143 loc) · 4.79 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package api
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/supabase/auth/internal/api/apierrors"
"github.com/supabase/auth/internal/crypto"
"github.com/supabase/auth/internal/models"
"github.com/supabase/auth/internal/storage"
)
// MagicLinkParams holds the parameters for a magic link request
type MagicLinkParams struct {
Email string `json:"email"`
Data map[string]interface{} `json:"data"`
CodeChallengeMethod string `json:"code_challenge_method"`
CodeChallenge string `json:"code_challenge"`
}
func (p *MagicLinkParams) Validate(a *API) error {
if p.Email == "" {
return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeValidationFailed, "Password recovery requires an email")
}
var err error
p.Email, err = a.validateEmail(p.Email)
if err != nil {
return err
}
if err := validatePKCEParams(p.CodeChallengeMethod, p.CodeChallenge); err != nil {
return err
}
return nil
}
// MagicLink sends a recovery email
func (a *API) MagicLink(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
db := a.db.WithContext(ctx)
config := a.config
if !config.External.Email.Enabled {
return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeEmailProviderDisabled, "Email logins are disabled")
}
if !config.External.Email.MagicLinkEnabled {
return apierrors.NewUnprocessableEntityError(apierrors.ErrorCodeEmailProviderDisabled, "Login with magic link is disabled")
}
params := &MagicLinkParams{}
jsonDecoder := json.NewDecoder(r.Body)
err := jsonDecoder.Decode(params)
if err != nil {
return apierrors.NewBadRequestError(apierrors.ErrorCodeBadJSON, "Could not read verification params: %v", err).WithInternalError(err)
}
if err := params.Validate(a); err != nil {
return err
}
if params.Data == nil {
params.Data = make(map[string]interface{})
}
flowType := getFlowFromChallenge(params.CodeChallenge)
var isNewUser bool
aud := a.requestAud(ctx, r)
user, err := models.FindUserByEmailAndAudience(db, params.Email, aud)
if err != nil {
if models.IsNotFoundError(err) {
isNewUser = true
} else {
return apierrors.NewInternalServerError("Database error finding user").WithInternalError(err)
}
}
if user != nil {
isNewUser = !user.IsConfirmed()
}
if isNewUser {
// User either doesn't exist or hasn't completed the signup process.
// Sign them up with temporary password.
password := crypto.GeneratePassword(config.Password.RequiredCharacters, 33)
signUpParams := &SignupParams{
Email: params.Email,
Password: password,
Data: params.Data,
CodeChallengeMethod: params.CodeChallengeMethod,
CodeChallenge: params.CodeChallenge,
}
newBodyContent, err := json.Marshal(signUpParams)
if err != nil {
// SignupParams must always be marshallable
panic(fmt.Errorf("failed to marshal SignupParams: %w", err))
}
r.Body = io.NopCloser(strings.NewReader(string(newBodyContent)))
r.ContentLength = int64(len(string(newBodyContent)))
fakeResponse := &responseStub{}
if config.Mailer.Autoconfirm {
// signups are autoconfirmed, send magic link after signup
if err := a.Signup(fakeResponse, r); err != nil {
return err
}
newBodyContent := &SignupParams{
Email: params.Email,
Data: params.Data,
CodeChallengeMethod: params.CodeChallengeMethod,
CodeChallenge: params.CodeChallenge,
}
metadata, err := json.Marshal(newBodyContent)
if err != nil {
// SignupParams must always be marshallable
panic(fmt.Errorf("failed to marshal SignupParams: %w", err))
}
r.Body = io.NopCloser(bytes.NewReader(metadata))
return a.MagicLink(w, r)
}
// otherwise confirmation email already contains 'magic link'
if err := a.Signup(fakeResponse, r); err != nil {
return err
}
return sendJSON(w, http.StatusOK, make(map[string]string))
}
if isPKCEFlow(flowType) {
if _, err = generateFlowState(db, models.MagicLink.String(), models.MagicLink, params.CodeChallengeMethod, params.CodeChallenge, &user.ID); err != nil {
return err
}
}
err = db.Transaction(func(tx *storage.Connection) error {
if terr := models.NewAuditLogEntry(config.AuditLog, r, tx, user, models.UserRecoveryRequestedAction, nil); terr != nil {
return terr
}
return a.sendMagicLink(r, tx, user, flowType)
})
if err != nil {
return err
}
return sendJSON(w, http.StatusOK, make(map[string]string))
}
// responseStub only implement http responsewriter for ignoring
// incoming data from methods where it passed
type responseStub struct {
}
func (rw *responseStub) Header() http.Header {
return http.Header{}
}
func (rw *responseStub) Write(data []byte) (int, error) {
return 1, nil
}
func (rw *responseStub) WriteHeader(statusCode int) {
}