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;
}
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);
}
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;
}
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();
}
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;
}
Aggregations