keycloak/services/src/main/java/org/keycloak/forms/account/freemarker/model/AuthenticationBean.java

245 lines
10 KiB
Java
Executable File

/*
* Copyright 2022 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.forms.account.freemarker.model;
import org.keycloak.authentication.Authenticator;
import org.keycloak.authentication.AuthenticatorFactory;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.common.util.reflections.Types;
import org.keycloak.credential.*;
import org.keycloak.models.*;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.representations.account.CredentialMetadataRepresentation;
import org.keycloak.representations.idm.CredentialRepresentation;
import javax.ws.rs.core.UriInfo;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.keycloak.models.AuthenticationExecutionModel.Requirement.DISABLED;
import static org.keycloak.utils.CredentialHelper.createUserStorageCredentialRepresentation;
/**
* @author <a href="mailto:nullobsi@unix.dog">Kayden Tebau</a>
*/
public class AuthenticationBean {
private final KeycloakSession session;
private final RealmModel realm;
private final UserModel user;
private final AuthorizationProvider authorization;
private final UriInfo uriInfo;
private final Map<String, CredentialTypeBean> credTypes;
private final Map<String, List<CredentialUserMetadataBean>> credentials;
public AuthenticationBean(KeycloakSession session, RealmModel realm, UserModel user, UriInfo uriInfo) {
this.session = session;
this.realm = realm;
this.user = user;
this.uriInfo = uriInfo;
authorization = session.getProvider(AuthorizationProvider.class);
credTypes = findCredentialTypes();
credentials = new HashMap<>();
}
public static class CredentialUserMetadataBean {
}
public static class CredentialTypeBean {
// ** category, displayName and helptext attributes can be ordinary UI text or a key into
// a localized message bundle. Typically, it will be a key, but
// the UI will work just fine if you don't care about localization
// and you want to just send UI text.
//
// Also, the ${} shown in Apicurio is not needed.
private String type;
private String category; // **
private String displayName;
private String helptext; // **
private String iconCssClass;
private String createAction;
private String updateAction;
private boolean removable;
private List<CredentialMetadataRepresentation> userCredentialMetadatas;
private CredentialTypeMetadata metadata;
public CredentialTypeBean() {
}
public CredentialTypeBean(CredentialTypeMetadata metadata, List<CredentialMetadataRepresentation> userCredentialMetadatas) {
this.metadata = metadata;
this.type = metadata.getType();
this.category = metadata.getCategory().toString();
this.displayName = metadata.getDisplayName();
this.helptext = metadata.getHelpText();
this.iconCssClass = metadata.getIconCssClass();
this.createAction = metadata.getCreateAction();
this.updateAction = metadata.getUpdateAction();
this.removable = metadata.isRemoveable();
this.userCredentialMetadatas = userCredentialMetadatas;
}
public String getCategory() {
return category;
}
public String getType() {
return type;
}
public String getDisplayName() {
return displayName;
}
public String getHelpText() {
return helptext;
}
public String getIconCssClass() {
return iconCssClass;
}
public String getCreateAction() {
return createAction;
}
public String getUpdateAction() {
return updateAction;
}
public boolean getRemovable() {
return removable;
}
public List<CredentialMetadataRepresentation> getUserCredentialMetadatas() {
return userCredentialMetadatas;
}
public CredentialTypeMetadata getMetadata() {
return metadata;
}
}
public List<CredentialTypeBean> getCredentialTypes() {
return new ArrayList<>(credTypes.values());
}
private Map<String, CredentialTypeBean> findCredentialTypes() {
List<CredentialProvider> credentialProviders = session.getKeycloakSessionFactory().getProviderFactoriesStream(CredentialProvider.class)
.filter(f -> Types.supports(CredentialProvider.class, f, CredentialProviderFactory.class))
.map(f -> session.getProvider(CredentialProvider.class, f.getId()))
.collect(Collectors.toList());
Set<String> enabledCredentialTypes = getEnabledCredentialTypes(credentialProviders);
Stream<CredentialModel> modelsStream = user.credentialManager().getStoredCredentialsStream();
List<CredentialModel> models = modelsStream.collect(Collectors.toList());
Function<CredentialProvider, CredentialTypeBean> toCredentialBean = (credentialProvider) -> {
CredentialTypeMetadataContext ctx = CredentialTypeMetadataContext.builder()
.user(user)
.build(session);
CredentialTypeMetadata metadata = credentialProvider.getCredentialTypeMetadata(ctx);
List<CredentialMetadataRepresentation> userCredentialMetadataModels = null;
List<CredentialModel> modelsOfType = models.stream()
.filter(credentialModel -> credentialProvider.getType().equals(credentialModel.getType()))
.collect(Collectors.toList());
List<CredentialMetadata> credentialMetadataList = modelsOfType.stream()
.map(m -> {
return credentialProvider.getCredentialMetadata(
credentialProvider.getCredentialFromModel(m), metadata
);
}).collect(Collectors.toList());
credentialMetadataList.stream().forEach(md -> md.getCredentialModel().setSecretData(null));
userCredentialMetadataModels = credentialMetadataList.stream().map(ModelToRepresentation::toRepresentation).collect(Collectors.toList());
if (userCredentialMetadataModels.isEmpty() &&
user.credentialManager().isConfiguredFor(credentialProvider.getType())) {
// In case user is federated in the userStorage, he may have credential configured on the userStorage side. We're
// creating "dummy" credential representing the credential provided by userStorage
CredentialMetadataRepresentation metadataRepresentation = new CredentialMetadataRepresentation();
CredentialRepresentation credential = createUserStorageCredentialRepresentation(credentialProvider.getType());
metadataRepresentation.setCredential(credential);
userCredentialMetadataModels = Collections.singletonList(metadataRepresentation);
}
// In case that there are no userCredentials AND there are not required actions for setup new credential,
// we won't include credentialType as user won't be able to do anything with it
if (userCredentialMetadataModels.isEmpty() && metadata.getCreateAction() == null && metadata.getUpdateAction() == null) {
return null;
}
return new CredentialTypeBean(metadata, userCredentialMetadataModels);
};
return credentialProviders.stream()
.filter(p -> enabledCredentialTypes.contains(p.getType()))
.map(toCredentialBean)
.filter(Objects::nonNull)
.sorted(Comparator.comparing(CredentialTypeBean::getMetadata))
.collect(Collectors.toMap(CredentialTypeBean::getType, Function.identity()));
}
private Set<String> getEnabledCredentialTypes(List<CredentialProvider> credentialProviders) {
Stream<String> enabledCredentialTypes = realm.getAuthenticationFlowsStream()
.filter(((Predicate<AuthenticationFlowModel>) this::isFlowEffectivelyDisabled).negate())
.flatMap(flow ->
realm.getAuthenticationExecutionsStream(flow.getId())
.filter(exe -> Objects.nonNull(exe.getAuthenticator()) && exe.getRequirement() != DISABLED)
.map(exe -> (AuthenticatorFactory) session.getKeycloakSessionFactory()
.getProviderFactory(Authenticator.class, exe.getAuthenticator()))
.filter(Objects::nonNull)
.map(AuthenticatorFactory::getReferenceCategory)
.filter(Objects::nonNull)
);
Set<String> credentialTypes = credentialProviders.stream()
.map(CredentialProvider::getType)
.collect(Collectors.toSet());
return enabledCredentialTypes.filter(credentialTypes::contains).collect(Collectors.toSet());
}
// Returns true if flow is effectively disabled - either it's execution or some parent execution is disabled
private boolean isFlowEffectivelyDisabled(AuthenticationFlowModel flow) {
while (!flow.isTopLevel()) {
AuthenticationExecutionModel flowExecution = realm.getAuthenticationExecutionByFlowId(flow.getId());
if (flowExecution == null) return false; // Can happen under some corner cases
if (DISABLED == flowExecution.getRequirement()) return true;
if (flowExecution.getParentFlow() == null) return false;
// Check parent flow
flow = realm.getAuthenticationFlowById(flowExecution.getParentFlow());
if (flow == null) return false;
}
return false;
}
}