/
login.go
167 lines (135 loc) · 5.5 KB
/
login.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
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package password
import (
"bytes"
"context"
"encoding/json"
"net/http"
"time"
"github.com/ory/kratos/selfservice/flowhelpers"
"github.com/ory/kratos/session"
"github.com/ory/x/stringsx"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
"github.com/ory/herodot"
"github.com/ory/x/decoderx"
"github.com/ory/kratos/hash"
"github.com/ory/kratos/identity"
"github.com/ory/kratos/schema"
"github.com/ory/kratos/selfservice/flow"
"github.com/ory/kratos/selfservice/flow/login"
"github.com/ory/kratos/text"
"github.com/ory/kratos/ui/node"
"github.com/ory/kratos/x"
)
func (s *Strategy) RegisterLoginRoutes(r *x.RouterPublic) {
}
func (s *Strategy) handleLoginError(w http.ResponseWriter, r *http.Request, f *login.Flow, payload *updateLoginFlowWithPasswordMethod, err error) error {
if f != nil {
f.UI.Nodes.ResetNodes("password")
f.UI.Nodes.SetValueAttribute("identifier", stringsx.Coalesce(payload.Identifier, payload.LegacyIdentifier))
if f.Type == flow.TypeBrowser {
f.UI.SetCSRF(s.d.GenerateCSRFToken(r))
}
}
return err
}
func (s *Strategy) Login(w http.ResponseWriter, r *http.Request, f *login.Flow, _ *session.Session) (i *identity.Identity, err error) {
if err := login.CheckAAL(f, identity.AuthenticatorAssuranceLevel1); err != nil {
return nil, err
}
if err := flow.MethodEnabledAndAllowedFromRequest(r, f.GetFlowName(), s.ID().String(), s.d); err != nil {
return nil, err
}
var p updateLoginFlowWithPasswordMethod
if err := s.hd.Decode(r, &p,
decoderx.HTTPDecoderSetValidatePayloads(true),
decoderx.MustHTTPRawJSONSchemaCompiler(loginSchema),
decoderx.HTTPDecoderJSONFollowsFormFormat()); err != nil {
return nil, s.handleLoginError(w, r, f, &p, err)
}
if err := flow.EnsureCSRF(s.d, r, f.Type, s.d.Config().DisableAPIFlowEnforcement(r.Context()), s.d.GenerateCSRFToken, p.CSRFToken); err != nil {
return nil, s.handleLoginError(w, r, f, &p, err)
}
i, c, err := s.d.PrivilegedIdentityPool().FindByCredentialsIdentifier(r.Context(), s.ID(), stringsx.Coalesce(p.Identifier, p.LegacyIdentifier))
if err != nil {
time.Sleep(x.RandomDelay(s.d.Config().HasherArgon2(r.Context()).ExpectedDuration, s.d.Config().HasherArgon2(r.Context()).ExpectedDeviation))
return nil, s.handleLoginError(w, r, f, &p, errors.WithStack(schema.NewInvalidCredentialsError()))
}
var o identity.CredentialsPassword
d := json.NewDecoder(bytes.NewBuffer(c.Config))
if err := d.Decode(&o); err != nil {
return nil, herodot.ErrInternalServerError.WithReason("The password credentials could not be decoded properly").WithDebug(err.Error()).WithWrap(err)
}
if err := hash.Compare(r.Context(), []byte(p.Password), []byte(o.HashedPassword)); err != nil {
return nil, s.handleLoginError(w, r, f, &p, errors.WithStack(schema.NewInvalidCredentialsError()))
}
if !s.d.Hasher(r.Context()).Understands([]byte(o.HashedPassword)) {
if err := s.migratePasswordHash(r.Context(), i.ID, []byte(p.Password)); err != nil {
return nil, s.handleLoginError(w, r, f, &p, err)
}
}
f.Active = identity.CredentialsTypePassword
f.Active = s.ID()
if err = s.d.LoginFlowPersister().UpdateLoginFlow(r.Context(), f); err != nil {
return nil, s.handleLoginError(w, r, f, &p, errors.WithStack(herodot.ErrInternalServerError.WithReason("Could not update flow").WithDebug(err.Error())))
}
return i, nil
}
func (s *Strategy) migratePasswordHash(ctx context.Context, identifier uuid.UUID, password []byte) error {
hpw, err := s.d.Hasher(ctx).Generate(ctx, password)
if err != nil {
return err
}
co, err := json.Marshal(&identity.CredentialsPassword{HashedPassword: string(hpw)})
if err != nil {
return errors.Wrap(err, "unable to encode password configuration to JSON")
}
i, err := s.d.PrivilegedIdentityPool().GetIdentityConfidential(ctx, identifier)
if err != nil {
return err
}
c, ok := i.GetCredentials(s.ID())
if !ok {
return errors.New("expected to find password credential but could not")
}
c.Config = co
i.SetCredentials(s.ID(), *c)
return s.d.PrivilegedIdentityPool().UpdateIdentity(ctx, i)
}
func (s *Strategy) PopulateLoginMethod(r *http.Request, requestedAAL identity.AuthenticatorAssuranceLevel, sr *login.Flow) error {
// This strategy can only solve AAL1
if requestedAAL > identity.AuthenticatorAssuranceLevel1 {
return nil
}
if sr.IsForced() {
// We only show this method on a refresh request if the user has indeed a password set.
identifier, id, _ := flowhelpers.GuessForcedLoginIdentifier(r, s.d, sr, s.ID())
if identifier == "" {
return nil
}
count, err := s.CountActiveFirstFactorCredentials(id.Credentials)
if err != nil {
return err
} else if count == 0 {
return nil
}
sr.UI.SetCSRF(s.d.GenerateCSRFToken(r))
sr.UI.SetNode(node.NewInputField("identifier", identifier, node.DefaultGroup, node.InputAttributeTypeHidden))
} else {
ds, err := s.d.Config().DefaultIdentityTraitsSchemaURL(r.Context())
if err != nil {
return err
}
identifierLabel, err := login.GetIdentifierLabelFromSchema(r.Context(), ds.String())
if err != nil {
return err
}
sr.UI.SetNode(node.NewInputField("identifier", "", node.DefaultGroup, node.InputAttributeTypeText, node.WithRequiredInputAttribute).WithMetaLabel(identifierLabel))
}
sr.UI.SetCSRF(s.d.GenerateCSRFToken(r))
sr.UI.SetNode(NewPasswordNode("password", node.InputAttributeAutocompleteCurrentPassword))
sr.UI.GetNodes().Append(node.NewInputField("method", "password", node.PasswordGroup, node.InputAttributeTypeSubmit).WithMetaLabel(text.NewInfoLogin()))
return nil
}