/
mfa_tools.go
42 lines (38 loc) · 1.36 KB
/
mfa_tools.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
package keycloakb
import (
"context"
errorhandler "github.com/cloudtrust/common-service/errors"
kc "github.com/cloudtrust/keycloak-client"
)
var notMFATypes = map[string]bool{"password": true, "password-history": true}
// CheckRemovableMFA checks if a given credential is removable (owned by user and not the last MFA)
func CheckRemovableMFA(ctx context.Context, credentialID string, getCredentials func() ([]kc.CredentialRepresentation, error), logger Logger) error {
credentialsKc, err := getCredentials()
if err != nil {
logger.Warn(ctx, "msg", "Can't get credentials", "err", err.Error())
return err
}
var found bool
var foundRemainingMFA bool
for _, credential := range credentialsKc {
if credential.ID != nil && *credential.ID != credentialID {
if value, ok := notMFATypes[*credential.Type]; !ok || !value {
foundRemainingMFA = true
}
} else if *credential.Type == "password" {
logger.Info(ctx, "msg", "Can't remove password credential")
return errorhandler.CreateBadRequestError("cantRemovePassword")
} else {
found = true
}
}
if !found {
logger.Info(ctx, "msg", "Can't remove unknown credential")
return errorhandler.CreateNotFoundError("credential")
}
if foundRemainingMFA {
return nil
}
logger.Info(ctx, "msg", "Not enough MFA registered: can't remove any credential")
return errorhandler.CreateBadRequestError("notEnoughMFA")
}