Implement split-credentials-check auth flow

This commit is contained in:
Denis Arh
2021-08-05 20:09:44 +02:00
parent 4b485b7bf5
commit 969581343c
15 changed files with 208 additions and 31 deletions
+1
View File
@@ -521,6 +521,7 @@ func updateAuthSettings(svc authServicer, current *types.AppSettings) {
SignupEnabled: current.Auth.Internal.Signup.Enabled,
EmailConfirmationRequired: current.Auth.Internal.Signup.EmailConfirmationRequired,
PasswordResetEnabled: current.Auth.Internal.PasswordReset.Enabled,
SplitCredentialsCheck: current.Auth.Internal.SplitCredentialsCheck,
ExternalEnabled: current.Auth.External.Enabled,
MultiFactor: authSettings.MultiFactor{
TOTP: authSettings.TOTP{
+15
View File
@@ -27,6 +27,7 @@
autocomplete="username"
aria-label="Email">
</div>
{{ if not .form.splitCredentialsCheck }}
<div class="mb-3">
<label>
Password *
@@ -58,6 +59,20 @@
</button>
</div>
</div>
{{ else }}
<div class="row">
<div class="col text-right">
<button
class="btn btn-primary btn-block btn-lg"
name="keep-session"
value="true"
type="submit"
>
Continue
</button>
</div>
</div>
{{ end }}
</form>
<div class="row text-center">
{{ if .settings.PasswordResetEnabled }}
+5
View File
@@ -39,6 +39,11 @@ login:
SignupEnabled: false
PasswordResetEnabled: false
With Split credentials check / username:
form:
splitCredentialsCheck: true
settings:
LocalEnabled: true
With errors after submit:
settings:
+4
View File
@@ -301,6 +301,10 @@ func (svc *service) UpdateSettings(s *settings.Settings) {
svc.log.Debug("setting changed", zap.Bool("passwordResetEnabled", s.PasswordResetEnabled))
}
if svc.settings.SplitCredentialsCheck != s.SplitCredentialsCheck {
svc.log.Debug("setting changed", zap.Bool("splitCredentialsCheck", s.SplitCredentialsCheck))
}
if svc.settings.ExternalEnabled != s.ExternalEnabled {
svc.log.Debug("setting changed", zap.Bool("externalEnabled", s.ExternalEnabled))
}
+53 -11
View File
@@ -1,6 +1,8 @@
package handlers
import (
"fmt"
"github.com/cortezaproject/corteza-server/auth/request"
"github.com/cortezaproject/corteza-server/pkg/auth"
"github.com/cortezaproject/corteza-server/pkg/errors"
@@ -17,26 +19,66 @@ type (
func (h *AuthHandlers) loginForm(req *request.AuthReq) error {
req.Template = TmplLogin
req.Data["form"] = req.PopKV()
kv := req.PopKV()
if kv == nil && h.Settings.SplitCredentialsCheck {
// Force login form to show only email input
//
// KV is nil (means that this is first load of the form)
// and credentials check is split into two parts (email first then credentials)
kv = map[string]string{
"splitCredentialsCheck": "split",
}
}
req.Data["form"] = kv
return nil
}
func (h *AuthHandlers) loginProc(req *request.AuthReq) (err error) {
// In most cases, we want to redirect back to login
req.RedirectTo = GetLinks().Login
req.SetKV(nil)
var (
user *types.User
email = req.Request.PostFormValue("email")
user *types.User
email = req.Request.PostFormValue("email")
password = req.Request.PostFormValue("password")
)
user, err = h.AuthService.InternalLogin(
req.Context(),
email,
req.Request.PostFormValue("password"),
)
err = func() (err error) {
if len(email) > 0 && len(password) == 0 && h.Settings.SplitCredentialsCheck {
// Email provided but no password and the
// split credentials check enabled
//
// SetKV w/ email will prevent the login form to show only email input
req.SetKV(map[string]string{"email": email})
// If user does not have password set (or in case there is no user with such email)
// and there is exactly one IdP we redirect user to that IdP
if !h.AuthService.PasswordSet(req.Context(), email) && len(h.Settings.Providers) == 1 {
// User w/o the password
// In case there is one single IdP automatically redirect user there
req.RedirectTo = fmt.Sprintf("%s/%s", GetLinks().External, h.Settings.Providers[0].Handle)
// for the clarity of the flow
// keeping this optional return here
return
}
// This user has existing password credentials or with more than one IdP
//
// Take user back to the login form and ask for the password
// or any other kind of login
return
}
user, err = h.AuthService.InternalLogin(req.Context(), email, password)
if err != nil {
return
}
if err == nil {
var (
isPerm = len(req.Request.PostFormValue("keep-session")) > 0
lifetime = h.Opt.SessionLifetime
@@ -69,8 +111,8 @@ func (h *AuthHandlers) loginProc(req *request.AuthReq) (err error) {
handleSuccessfulAuth(req)
return nil
}
return
}()
switch {
case service.AuthErrInternalLoginDisabledByConfig().Is(err):
+35
View File
@@ -152,6 +152,41 @@ func Test_loginProc(t *testing.T) {
}
},
},
{
name: "split credentials check",
payload: map[string]string{"email": "mockuser@example.tld"},
alerts: []request.Alert(nil),
link: GetLinks().Login,
fn: func(authSettings *settings.Settings) {
req.PostForm.Add("email", "mockuser@example.tld")
authSettings.SplitCredentialsCheck = true
authService = &authServiceMocked{
passwordSet: func(ctx context.Context, email string) bool {
return false
},
}
},
},
{
name: "split credentials check with providers",
payload: map[string]string{"email": "mockuser@example.tld"},
alerts: []request.Alert(nil),
link: GetLinks().External + "/test-idp",
fn: func(authSettings *settings.Settings) {
req.PostForm.Add("email", "mockuser@example.tld")
authSettings.SplitCredentialsCheck = true
authSettings.Providers = []settings.Provider{
{Handle: "test-idp"},
}
authService = &authServiceMocked{
passwordSet: func(ctx context.Context, email string) bool {
return false
},
}
},
},
}
for _, tc := range tcc {
+1 -1
View File
@@ -35,7 +35,7 @@ type (
SendEmailAddressConfirmationToken(ctx context.Context, u *types.User) (err error)
SendPasswordResetToken(ctx context.Context, email string) (err error)
GetProviders() types.ExternalAuthProviderSet
PasswordSet(ctx context.Context, email string) (is bool)
ValidateTOTP(ctx context.Context, code string) (err error)
ConfigureTOTP(ctx context.Context, secret string, code string) (u *types.User, err error)
RemoveTOTP(ctx context.Context, userID uint64, code string) (u *types.User, err error)
+1
View File
@@ -7,6 +7,7 @@ type (
EmailConfirmationRequired bool
PasswordResetEnabled bool
ExternalEnabled bool
SplitCredentialsCheck bool
Providers []Provider
Saml SAML
MultiFactor MultiFactor
+1 -2
View File
@@ -595,9 +595,8 @@ endpoints:
post:
- name: password
type: string
required: true
sensitive: true
title: New password
title: New password or empty to unset
- name: membershipList
method: GET
+1 -1
View File
@@ -221,7 +221,7 @@ type (
// Password POST parameter
//
// New password
// New password or empty to unset
Password string
}
+53 -14
View File
@@ -617,26 +617,13 @@ func (svc auth) CheckPasswordStrength(password string) bool {
func (svc auth) SetPasswordCredentials(ctx context.Context, userID uint64, password string) (err error) {
var (
hash []byte
cc types.CredentialsSet
f = types.CredentialsFilter{Kind: credentialsTypePassword, OwnerID: userID}
)
if hash, err = svc.hashPassword(password); err != nil {
return
}
if cc, _, err = store.SearchCredentials(ctx, svc.store, f); err != nil {
return nil
}
// Mark all credentials as deleted
_ = cc.Walk(func(c *types.Credentials) error {
c.DeletedAt = now()
return nil
})
// Do a partial update and soft-delete all
if err = store.UpdateCredentials(ctx, svc.store, cc...); err != nil {
if err = svc.removePasswordCredentials(ctx, userID); err != nil {
return
}
@@ -652,6 +639,33 @@ func (svc auth) SetPasswordCredentials(ctx context.Context, userID uint64, passw
return store.CreateCredentials(ctx, svc.store, c)
}
// RemovePasswordCredentials (soft) deletes old password entry
func (svc auth) RemovePasswordCredentials(ctx context.Context, userID uint64) (err error) {
// Do a partial update and soft-delete all
return svc.removePasswordCredentials(ctx, userID)
}
// RemovePasswordCredentials (soft) deletes old password entry
func (svc auth) removePasswordCredentials(ctx context.Context, userID uint64) (err error) {
var (
cc types.CredentialsSet
f = types.CredentialsFilter{Kind: credentialsTypePassword, OwnerID: userID}
)
if cc, _, err = store.SearchCredentials(ctx, svc.store, f); err != nil {
return nil
}
// Mark all credentials as deleted
_ = cc.Walk(func(c *types.Credentials) error {
c.DeletedAt = now()
return nil
})
// Do a partial update and soft-delete all
return store.UpdateCredentials(ctx, svc.store, cc...)
}
// ValidateEmailConfirmationToken issues a validation token that can be used for
func (svc auth) ValidateEmailConfirmationToken(ctx context.Context, token string) (user *types.User, err error) {
return svc.loadFromTokenAndConfirmEmail(ctx, token, credentialsTypeEmailAuthToken)
@@ -662,6 +676,31 @@ func (svc auth) ValidatePasswordResetToken(ctx context.Context, token string) (u
return svc.loadFromTokenAndConfirmEmail(ctx, token, credentialsTypeResetPasswordToken)
}
// PasswordSet checks and returns true if user's password is set
// False is also returned in case user does not exist.
func (svc *auth) PasswordSet(ctx context.Context, email string) (is bool) {
//svc.settings.Auth.External.Enabled
u, err := store.LookupUserByEmail(ctx, svc.store, email)
if err != nil {
return
}
cc, _, err := store.SearchCredentials(ctx, svc.store, types.CredentialsFilter{
OwnerID: u.ID,
Kind: credentialsTypePassword,
})
if err != nil {
return
}
if len(cc) > 0 && svc.settings.Auth.Internal.Enabled {
return true
}
return
}
// loadFromTokenAndConfirmEmail loads token, confirms user's
func (svc auth) loadFromTokenAndConfirmEmail(ctx context.Context, token, tokenType string) (u *types.User, err error) {
var (
+9 -2
View File
@@ -47,6 +47,7 @@ type (
userAuth interface {
CheckPasswordStrength(string) bool
SetPasswordCredentials(context.Context, uint64, string) error
RemovePasswordCredentials(context.Context, uint64) error
}
userAccessController interface {
@@ -674,11 +675,12 @@ func (svc user) Unsuspend(ctx context.Context, userID uint64) (err error) {
// SetPassword sets new password for a user
//
// Expecting setter to have permissions to update modify users and internal authentication enabled
// Expecting setter to have permissions to update users
func (svc user) SetPassword(ctx context.Context, userID uint64, newPassword string) (err error) {
var (
u *types.User
uaProps = &userActionProps{user: &types.User{ID: userID}}
a = UserActionSetPassword
)
err = func() error {
@@ -696,6 +698,11 @@ func (svc user) SetPassword(ctx context.Context, userID uint64, newPassword stri
return UserErrNotAllowedToUpdate()
}
if newPassword == "" {
a = UserActionRemovePassword
return svc.auth.RemovePasswordCredentials(ctx, userID)
}
if !svc.auth.CheckPasswordStrength(newPassword) {
return UserErrPasswordNotSecure()
}
@@ -707,7 +714,7 @@ func (svc user) SetPassword(ctx context.Context, userID uint64, newPassword stri
return nil
}()
return svc.recordAction(ctx, uaProps, UserActionSetPassword, err)
return svc.recordAction(ctx, uaProps, a, err)
}
+20
View File
@@ -506,6 +506,26 @@ func UserActionSetPassword(props ...*userActionProps) *userAction {
return a
}
// UserActionRemovePassword returns "system:user.removePassword" action
//
// This function is auto-generated.
//
func UserActionRemovePassword(props ...*userActionProps) *userAction {
a := &userAction{
timestamp: time.Now(),
resource: "system:user",
action: "removePassword",
log: "password removed for {user}",
severity: actionlog.Notice,
}
if len(props) > 0 {
a.props = props[0]
}
return a
}
// UserActionDeleteAuthTokens returns "system:user.deleteAuthTokens" action
//
// This function is auto-generated.
+3
View File
@@ -59,6 +59,9 @@ actions:
- action: setPassword
log: "password changed for {user}"
- action: removePassword
log: "password removed for {user}"
- action: deleteAuthTokens
log: "deleted auth tokens of {user}"
+6
View File
@@ -49,6 +49,12 @@ type (
// Can users reset their passwords
PasswordReset struct{ Enabled bool } `kv:"password-reset"`
// Splits credentials check into 2 parts
// If user has password credentials it offers him to enter the password
// Otherwise we offer the user to choose among the enabled external providers
// If only one ext. provider is enabled, user is automatically redirected there
SplitCredentialsCheck bool `kv:"split-credentials-check"`
}
External struct {