-
Notifications
You must be signed in to change notification settings - Fork 27
/
forgot_password.go
356 lines (302 loc) · 11.1 KB
/
forgot_password.go
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package authflowv2
import (
"errors"
"net/http"
"net/url"
handlerwebapp "github.com/authgear/authgear-server/pkg/auth/handler/webapp"
"github.com/authgear/authgear-server/pkg/auth/handler/webapp/viewmodels"
"github.com/authgear/authgear-server/pkg/auth/webapp"
authflow "github.com/authgear/authgear-server/pkg/lib/authenticationflow"
"github.com/authgear/authgear-server/pkg/lib/authenticationflow/declarative"
"github.com/authgear/authgear-server/pkg/lib/authn/otp"
"github.com/authgear/authgear-server/pkg/lib/config"
"github.com/authgear/authgear-server/pkg/util/httproute"
"github.com/authgear/authgear-server/pkg/util/template"
"github.com/authgear/authgear-server/pkg/util/validation"
)
var TemplateWebAuthflowV2ForgotPasswordHTML = template.RegisterHTML(
"web/authflowv2/forgot_password.html",
handlerwebapp.Components...,
)
var AuthflowV2ForgotPasswordSchema = validation.NewSimpleSchema(`
{
"type": "object",
"properties": {
"x_login_id": { "type": "string" },
"x_login_id_type": { "type": "string", "enum": ["phone", "email"] }
},
"required": ["x_login_id", "x_login_id_type"]
}
`)
func ConfigureAuthflowV2ForgotPasswordRoute(route httproute.Route) httproute.Route {
return route.
WithMethods("OPTIONS", "POST", "GET").
WithPathPattern(AuthflowV2RouteForgotPassword)
}
type ForgotPasswordLoginIDInputType string
const (
ForgotPasswordLoginIDInputTypeEmail ForgotPasswordLoginIDInputType = "email"
ForgotPasswordLoginIDInputTypePhone ForgotPasswordLoginIDInputType = "phone"
)
func (t ForgotPasswordLoginIDInputType) IsValid() bool {
switch t {
case ForgotPasswordLoginIDInputTypeEmail:
fallthrough
case ForgotPasswordLoginIDInputTypePhone:
return true
default:
return false
}
}
type AuthFlowV2ForgotPasswordAlternativeType string
const (
AuthFlowV2ForgotPasswordAlternativeTypeEmail AuthFlowV2ForgotPasswordAlternativeType = "email"
AuthFlowV2ForgotPasswordAlternativeTypePhone AuthFlowV2ForgotPasswordAlternativeType = "phone"
)
type AuthFlowV2ForgotPasswordAlternative struct {
AlternativeType AuthFlowV2ForgotPasswordAlternativeType
Href string
}
type AuthFlowV2ForgotPasswordViewModel struct {
LoginIDInputType ForgotPasswordLoginIDInputType
LoginID string
PhoneLoginIDEnabled bool
EmailLoginIDEnabled bool
LoginIDDisabled bool
OTPForm string
RequiresLoginIDInput bool
Alternatives []*AuthFlowV2ForgotPasswordAlternative
}
func forgotPasswordGetInitialLoginIDInputType(data declarative.IntentAccountRecoveryFlowStepIdentifyData) ForgotPasswordLoginIDInputType {
if len(data.Options) < 1 {
return ForgotPasswordLoginIDInputTypeEmail
}
switch data.Options[0].Identification {
case config.AuthenticationFlowAccountRecoveryIdentificationEmail:
return ForgotPasswordLoginIDInputTypeEmail
case config.AuthenticationFlowAccountRecoveryIdentificationPhone:
return ForgotPasswordLoginIDInputTypePhone
}
return ForgotPasswordLoginIDInputTypeEmail
}
func deriveForgotPasswordAlternatives(
r *http.Request,
loginIDInputType ForgotPasswordLoginIDInputType,
emailLoginIDEnabled bool,
phoneLoginIDEnabled bool) []*AuthFlowV2ForgotPasswordAlternative {
alternatives := []*AuthFlowV2ForgotPasswordAlternative{}
if loginIDInputType != ForgotPasswordLoginIDInputTypeEmail && emailLoginIDEnabled {
alternatives = append(alternatives, &AuthFlowV2ForgotPasswordAlternative{
AlternativeType: AuthFlowV2ForgotPasswordAlternativeTypeEmail,
Href: webapp.MakeURL(r.URL, "", url.Values{
"q_login_id_input_type": []string{string(ForgotPasswordLoginIDInputTypeEmail)},
}).String(),
})
}
if loginIDInputType != ForgotPasswordLoginIDInputTypePhone && phoneLoginIDEnabled {
alternatives = append(alternatives, &AuthFlowV2ForgotPasswordAlternative{
AlternativeType: AuthFlowV2ForgotPasswordAlternativeTypePhone,
Href: webapp.MakeURL(r.URL, "", url.Values{
"q_login_id_input_type": []string{string(ForgotPasswordLoginIDInputTypePhone)},
}).String(),
})
}
return alternatives
}
func NewAuthFlowV2ForgotPasswordViewModel(
r *http.Request,
initialScreen *webapp.AuthflowScreenWithFlowResponse,
selectDestinationScreen *webapp.AuthflowScreenWithFlowResponse) AuthFlowV2ForgotPasswordViewModel {
requiresLoginIDInput := true
data, ok := initialScreen.StateTokenFlowResponse.Action.Data.(declarative.IntentAccountRecoveryFlowStepIdentifyData)
if !ok {
panic("authflow webapp: unexpected data")
}
loginIDInputType := forgotPasswordGetInitialLoginIDInputType(data)
qLoginIDInputType := ForgotPasswordLoginIDInputType(r.Form.Get("q_login_id_input_type"))
if qLoginIDInputType.IsValid() {
loginIDInputType = qLoginIDInputType
}
loginID := r.Form.Get("q_login_id")
phoneLoginIDEnabled := false
emailLoginIDEnabled := false
for _, opt := range data.Options {
switch opt.Identification {
case config.AuthenticationFlowAccountRecoveryIdentificationEmail:
emailLoginIDEnabled = true
case config.AuthenticationFlowAccountRecoveryIdentificationPhone:
phoneLoginIDEnabled = true
}
}
loginIDDisabled := !phoneLoginIDEnabled && !emailLoginIDEnabled
otpForm := ""
if selectDestinationScreen != nil {
requiresLoginIDInput = false
data2, ok := selectDestinationScreen.StateTokenFlowResponse.Action.
Data.(declarative.IntentAccountRecoveryFlowStepSelectDestinationData)
if ok && len(data2.Options) > 0 {
otpForm = string(data2.Options[0].OTPForm)
}
}
alternatives := deriveForgotPasswordAlternatives(
r,
loginIDInputType,
emailLoginIDEnabled,
phoneLoginIDEnabled,
)
return AuthFlowV2ForgotPasswordViewModel{
LoginIDInputType: loginIDInputType,
LoginID: loginID,
PhoneLoginIDEnabled: phoneLoginIDEnabled,
EmailLoginIDEnabled: emailLoginIDEnabled,
LoginIDDisabled: loginIDDisabled,
OTPForm: otpForm,
RequiresLoginIDInput: requiresLoginIDInput,
Alternatives: alternatives,
}
}
type AuthflowV2ForgotPasswordHandler struct {
Controller *handlerwebapp.AuthflowController
BaseViewModel *viewmodels.BaseViewModeler
Renderer handlerwebapp.Renderer
}
func (h *AuthflowV2ForgotPasswordHandler) GetData(
w http.ResponseWriter,
r *http.Request,
s *webapp.Session,
initialScreen *webapp.AuthflowScreenWithFlowResponse,
selectDestinationScreen *webapp.AuthflowScreenWithFlowResponse) (map[string]interface{}, error) {
data := make(map[string]interface{})
baseViewModel := h.BaseViewModel.ViewModelForAuthFlow(r, w)
viewmodels.Embed(data, baseViewModel)
screenViewModel := NewAuthFlowV2ForgotPasswordViewModel(r, initialScreen, selectDestinationScreen)
viewmodels.Embed(data, screenViewModel)
return data, nil
}
func (h *AuthflowV2ForgotPasswordHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var handlers handlerwebapp.AuthflowControllerHandlers
handlers.Get(func(s *webapp.Session, screen *webapp.AuthflowScreenWithFlowResponse) error {
var screenIdentify *webapp.AuthflowScreenWithFlowResponse
var screenSelectDestination *webapp.AuthflowScreenWithFlowResponse
// screen can be identity or select_destination according to the query
switch config.AuthenticationFlowStepType(screen.StateTokenFlowResponse.Action.Type) {
case config.AuthenticationFlowStepTypeIdentify:
screenIdentify = screen
case config.AuthenticationFlowStepTypeSelectDestination:
screenSelectDestination = screen
var err error
screenIdentify, err = h.Controller.GetScreen(s, screen.Screen.PreviousXStep)
if err != nil {
return err
}
}
data, err := h.GetData(w, r, s, screenIdentify, screenSelectDestination)
if err != nil {
return err
}
h.Renderer.RenderHTML(w, r, TemplateWebAuthflowV2ForgotPasswordHTML, data)
return nil
})
handlers.PostAction("", func(s *webapp.Session, screen *webapp.AuthflowScreenWithFlowResponse) error {
err := AuthflowV2ForgotPasswordSchema.Validator().ValidateValue(handlerwebapp.FormToJSON(r.Form))
if err != nil {
return err
}
loginID := r.Form.Get("x_login_id")
identification := r.Form.Get("x_login_id_type")
inputs := h.makeInputs(screen, identification, loginID, 0)
result, err := h.Controller.AdvanceWithInputs(r, s, screen, inputs, nil)
if errors.Is(err, otp.ErrInvalidWhatsappUser) {
// The code failed to send because it is not a valid whatsapp user
// Try again with sms if possible
var fallbackErr error
result, fallbackErr = h.fallbackToSMS(r, s, screen, identification, loginID)
if errors.Is(fallbackErr, handlerwebapp.ErrNoFallbackAvailable) {
return err
} else if fallbackErr != nil {
return fallbackErr
}
} else if err != nil {
return err
}
result.WriteResponse(w, r)
return nil
})
identification := r.URL.Query().Get("q_login_id_input_type")
loginID := r.URL.Query().Get("q_login_id")
var input interface{} = nil
if identification != "" && loginID != "" {
input = map[string]interface{}{
"identification": identification,
"login_id": loginID,
}
}
h.Controller.HandleStartOfFlow(w, r, webapp.SessionOptions{}, authflow.FlowTypeAccountRecovery, &handlers, input)
}
func (h *AuthflowV2ForgotPasswordHandler) fallbackToSMS(
r *http.Request,
s *webapp.Session,
screen *webapp.AuthflowScreenWithFlowResponse,
identification string,
loginID string,
) (*webapp.Result, error) {
options := []declarative.AccountRecoveryDestinationOption{}
switch config.AuthenticationFlowStepType(screen.StateTokenFlowResponse.Action.Type) {
case config.AuthenticationFlowStepTypeIdentify:
input := map[string]interface{}{
"identification": identification,
"login_id": loginID,
}
output, err := h.Controller.FeedInputWithoutNavigate(screen.StateTokenFlowResponse.StateToken, input)
if err != nil {
return nil, err
}
if data, ok := output.FlowAction.Data.(declarative.IntentAccountRecoveryFlowStepSelectDestinationData); ok {
options = data.Options
}
case config.AuthenticationFlowStepTypeSelectDestination:
if data, ok := screen.StateTokenFlowResponse.Action.Data.(declarative.IntentAccountRecoveryFlowStepSelectDestinationData); ok {
options = data.Options
}
}
smsOptionIdx := -1
for idx, option := range options {
if option.Channel == declarative.AccountRecoveryChannelSMS {
smsOptionIdx = idx
break
}
}
if smsOptionIdx == -1 {
// No sms option is available, failing
return nil, handlerwebapp.ErrNoFallbackAvailable
}
inputs := h.makeInputs(screen, identification, loginID, smsOptionIdx)
return h.Controller.AdvanceWithInputs(r, s, screen, inputs, nil)
}
func (h *AuthflowV2ForgotPasswordHandler) makeInputs(
screen *webapp.AuthflowScreenWithFlowResponse,
identification string,
loginID string,
optionIndex int) (inputs []map[string]interface{}) {
// screen can be identity or select_destination depends on the query
switch config.AuthenticationFlowStepType(screen.StateTokenFlowResponse.Action.Type) {
case config.AuthenticationFlowStepTypeIdentify:
// We need data of both steps, so they must be two inputs
inputs = []map[string]interface{}{
{
"identification": identification,
"login_id": loginID,
},
{
"index": optionIndex,
},
}
case config.AuthenticationFlowStepTypeSelectDestination:
inputs = []map[string]interface{}{
{
"index": optionIndex,
},
}
}
return
}