Search in sources :

Example 36 with ModelDuplicateException

use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.

the class KeycloakErrorHandler method getStatusCode.

private int getStatusCode(Throwable throwable) {
    int status = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
    if (throwable instanceof WebApplicationException) {
        WebApplicationException ex = (WebApplicationException) throwable;
        status = ex.getResponse().getStatus();
    }
    if (throwable instanceof Failure) {
        Failure f = (Failure) throwable;
        status = f.getErrorCode();
    }
    if (throwable instanceof JsonParseException) {
        status = Response.Status.BAD_REQUEST.getStatusCode();
    }
    if (throwable instanceof ModelDuplicateException) {
        status = Response.Status.CONFLICT.getStatusCode();
    }
    return status;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) Failure(org.jboss.resteasy.spi.Failure)

Example 37 with ModelDuplicateException

use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.

the class MapPolicyStore method create.

@Override
public Policy create(AbstractPolicyRepresentation representation, ResourceServer resourceServer) {
    LOG.tracef("create(%s, %s, %s)%s", representation.getId(), resourceServer.getId(), resourceServer, getShortStackTrace());
    // @UniqueConstraint(columnNames = {"NAME", "RESOURCE_SERVER_ID"})
    DefaultModelCriteria<Policy> mcb = forResourceServer(resourceServer.getId()).compare(SearchableFields.NAME, Operator.EQ, representation.getName());
    if (tx.getCount(withCriteria(mcb)) > 0) {
        throw new ModelDuplicateException("Policy with name '" + representation.getName() + "' for " + resourceServer.getId() + " already exists");
    }
    String uid = representation.getId();
    MapPolicyEntity entity = new MapPolicyEntityImpl();
    entity.setId(uid);
    entity.setType(representation.getType());
    entity.setName(representation.getName());
    entity.setResourceServerId(resourceServer.getId());
    entity = tx.create(entity);
    return entityToAdapter(entity);
}
Also used : Policy(org.keycloak.authorization.model.Policy) MapPolicyEntityImpl(org.keycloak.models.map.authorization.entity.MapPolicyEntityImpl) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) MapPolicyEntity(org.keycloak.models.map.authorization.entity.MapPolicyEntity)

Example 38 with ModelDuplicateException

use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.

the class AbstractUsernameFormAuthenticator method getUserFromForm.

private UserModel getUserFromForm(AuthenticationFlowContext context, MultivaluedMap<String, String> inputData) {
    String username = inputData.getFirst(AuthenticationManager.FORM_USERNAME);
    if (username == null) {
        context.getEvent().error(Errors.USER_NOT_FOUND);
        Response challengeResponse = challenge(context, getDefaultChallengeMessage(context), FIELD_USERNAME);
        context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return null;
    }
    // remove leading and trailing whitespace
    username = username.trim();
    context.getEvent().detail(Details.USERNAME, username);
    context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);
    UserModel user = null;
    try {
        user = KeycloakModelUtils.findUserByNameOrEmail(context.getSession(), context.getRealm(), username);
    } catch (ModelDuplicateException mde) {
        ServicesLogger.LOGGER.modelDuplicateException(mde);
        // Could happen during federation import
        if (mde.getDuplicateFieldName() != null && mde.getDuplicateFieldName().equals(UserModel.EMAIL)) {
            setDuplicateUserChallenge(context, Errors.EMAIL_IN_USE, Messages.EMAIL_EXISTS, AuthenticationFlowError.INVALID_USER);
        } else {
            setDuplicateUserChallenge(context, Errors.USERNAME_IN_USE, Messages.USERNAME_EXISTS, AuthenticationFlowError.INVALID_USER);
        }
        return user;
    }
    testInvalidUser(context, user);
    return user;
}
Also used : Response(javax.ws.rs.core.Response) UserModel(org.keycloak.models.UserModel) ModelDuplicateException(org.keycloak.models.ModelDuplicateException)

Example 39 with ModelDuplicateException

use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.

the class ValidateUsername method authenticate.

@Override
public void authenticate(AuthenticationFlowContext context) {
    String username = retrieveUsername(context);
    if (username == null) {
        context.getEvent().error(Errors.USER_NOT_FOUND);
        Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_request", "Missing parameter: username");
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return;
    }
    context.getEvent().detail(Details.USERNAME, username);
    context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);
    UserModel user = null;
    try {
        user = KeycloakModelUtils.findUserByNameOrEmail(context.getSession(), context.getRealm(), username);
    } catch (ModelDuplicateException mde) {
        ServicesLogger.LOGGER.modelDuplicateException(mde);
        Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_request", "Invalid user credentials");
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return;
    }
    if (user == null) {
        context.getEvent().error(Errors.USER_NOT_FOUND);
        Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_grant", "Invalid user credentials");
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return;
    }
    String bruteForceError = getDisabledByBruteForceEventError(context.getProtector(), context.getSession(), context.getRealm(), user);
    if (bruteForceError != null) {
        context.getEvent().user(user);
        context.getEvent().error(bruteForceError);
        Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_grant", "Invalid user credentials");
        context.forceChallenge(challengeResponse);
        return;
    }
    if (!user.isEnabled()) {
        context.getEvent().user(user);
        context.getEvent().error(Errors.USER_DISABLED);
        Response challengeResponse = errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_grant", "Account disabled");
        context.forceChallenge(challengeResponse);
        return;
    }
    context.setUser(user);
    context.success();
}
Also used : Response(javax.ws.rs.core.Response) UserModel(org.keycloak.models.UserModel) ModelDuplicateException(org.keycloak.models.ModelDuplicateException)

Example 40 with ModelDuplicateException

use of org.keycloak.models.ModelDuplicateException in project keycloak by keycloak.

the class MapUserProvider method addUser.

@Override
public UserModel addUser(RealmModel realm, String id, String username, boolean addDefaultRoles, boolean addDefaultRequiredActions) {
    LOG.tracef("addUser(%s, %s, %s, %s, %s)%s", realm, id, username, addDefaultRoles, addDefaultRequiredActions, getShortStackTrace());
    DefaultModelCriteria<UserModel> mcb = criteria();
    mcb = mcb.compare(SearchableFields.REALM_ID, Operator.EQ, realm.getId()).compare(SearchableFields.USERNAME, Operator.EQ, username);
    if (tx.getCount(withCriteria(mcb)) > 0) {
        throw new ModelDuplicateException("User with username '" + username + "' in realm " + realm.getName() + " already exists");
    }
    if (id != null && tx.read(id) != null) {
        throw new ModelDuplicateException("User exists: " + id);
    }
    MapUserEntity entity = new MapUserEntityImpl();
    entity.setId(id);
    entity.setRealmId(realm.getId());
    entity.setEmailConstraint(KeycloakModelUtils.generateId());
    entity.setUsername(username.toLowerCase());
    entity.setCreatedTimestamp(Time.currentTimeMillis());
    entity = tx.create(entity);
    final UserModel userModel = entityToAdapterFunc(realm).apply(entity);
    if (addDefaultRoles) {
        userModel.grantRole(realm.getDefaultRole());
        // No need to check if user has group as it's new user
        realm.getDefaultGroupsStream().forEach(userModel::joinGroup);
    }
    if (addDefaultRequiredActions) {
        realm.getRequiredActionProvidersStream().filter(RequiredActionProviderModel::isEnabled).filter(RequiredActionProviderModel::isDefaultAction).map(RequiredActionProviderModel::getAlias).forEach(userModel::addRequiredAction);
    }
    return userModel;
}
Also used : UserModel(org.keycloak.models.UserModel) RequiredActionProviderModel(org.keycloak.models.RequiredActionProviderModel) ModelDuplicateException(org.keycloak.models.ModelDuplicateException)

Aggregations

ModelDuplicateException (org.keycloak.models.ModelDuplicateException)42 Consumes (javax.ws.rs.Consumes)12 UserModel (org.keycloak.models.UserModel)11 POST (javax.ws.rs.POST)9 Response (javax.ws.rs.core.Response)6 NotFoundException (javax.ws.rs.NotFoundException)5 ClientModel (org.keycloak.models.ClientModel)5 RealmModel (org.keycloak.models.RealmModel)5 BadRequestException (javax.ws.rs.BadRequestException)4 PUT (javax.ws.rs.PUT)4 Path (javax.ws.rs.Path)4 ModelException (org.keycloak.models.ModelException)4 X509Certificate (java.security.cert.X509Certificate)3 NoCache (org.jboss.resteasy.annotations.cache.NoCache)3 ErrorResponseException (org.keycloak.services.ErrorResponseException)3 ClientPolicyException (org.keycloak.services.clientpolicy.ClientPolicyException)3 URI (java.net.URI)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 ClientScopeModel (org.keycloak.models.ClientScopeModel)2 ProtocolMapperModel (org.keycloak.models.ProtocolMapperModel)2