Search in sources :

Example 1 with ModelDuplicateException

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

the class MapPermissionTicketStore method create.

@Override
public PermissionTicket create(String resourceId, String scopeId, String requester, ResourceServer resourceServer) {
    LOG.tracef("create(%s, %s, %s, %s)%s", resourceId, scopeId, requester, resourceServer, getShortStackTrace());
    String owner = authorizationProvider.getStoreFactory().getResourceStore().findById(resourceId, resourceServer.getId()).getOwner();
    // @UniqueConstraint(columnNames = {"OWNER", "REQUESTER", "RESOURCE_SERVER_ID", "RESOURCE_ID", "SCOPE_ID"})
    DefaultModelCriteria<PermissionTicket> mcb = forResourceServer(resourceServer.getId()).compare(SearchableFields.OWNER, Operator.EQ, owner).compare(SearchableFields.RESOURCE_ID, Operator.EQ, resourceId).compare(SearchableFields.REQUESTER, Operator.EQ, requester);
    if (scopeId != null) {
        mcb = mcb.compare(SearchableFields.SCOPE_ID, Operator.EQ, scopeId);
    }
    if (tx.getCount(withCriteria(mcb)) > 0) {
        throw new ModelDuplicateException("Permission ticket for resource server: '" + resourceServer.getId() + ", Resource: " + resourceId + ", owner: " + owner + ", scopeId: " + scopeId + " already exists.");
    }
    MapPermissionTicketEntity entity = new MapPermissionTicketEntityImpl();
    entity.setResourceId(resourceId);
    entity.setRequester(requester);
    entity.setCreatedTimestamp(System.currentTimeMillis());
    if (scopeId != null) {
        entity.setScopeId(scopeId);
    }
    entity.setOwner(owner);
    entity.setResourceServerId(resourceServer.getId());
    entity = tx.create(entity);
    return entityToAdapter(entity);
}
Also used : PermissionTicket(org.keycloak.authorization.model.PermissionTicket) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) MapPermissionTicketEntityImpl(org.keycloak.models.map.authorization.entity.MapPermissionTicketEntityImpl) MapPermissionTicketEntity(org.keycloak.models.map.authorization.entity.MapPermissionTicketEntity)

Example 2 with ModelDuplicateException

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

the class UsersResource method createUser.

/**
 * Create a new user
 *
 * Username must be unique.
 *
 * @param rep
 * @return
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createUser(final UserRepresentation rep) {
    // first check if user has manage rights
    try {
        auth.users().requireManage();
    } catch (ForbiddenException exception) {
        if (!canCreateGroupMembers(rep)) {
            throw exception;
        }
    }
    String username = rep.getUsername();
    if (realm.isRegistrationEmailAsUsername()) {
        username = rep.getEmail();
    }
    if (ObjectUtil.isBlank(username)) {
        return ErrorResponse.error("User name is missing", Response.Status.BAD_REQUEST);
    }
    // Double-check duplicated username and email here due to federation
    if (session.users().getUserByUsername(realm, username) != null) {
        return ErrorResponse.exists("User exists with same username");
    }
    if (rep.getEmail() != null && !realm.isDuplicateEmailsAllowed()) {
        try {
            if (session.users().getUserByEmail(realm, rep.getEmail()) != null) {
                return ErrorResponse.exists("User exists with same email");
            }
        } catch (ModelDuplicateException e) {
            return ErrorResponse.exists("User exists with same email");
        }
    }
    UserProfileProvider profileProvider = session.getProvider(UserProfileProvider.class);
    UserProfile profile = profileProvider.create(USER_API, rep.toAttributes());
    try {
        Response response = UserResource.validateUserProfile(profile, null, session);
        if (response != null) {
            return response;
        }
        UserModel user = profile.create();
        UserResource.updateUserFromRep(profile, user, rep, session, false);
        RepresentationToModel.createFederatedIdentities(rep, session, realm, user);
        RepresentationToModel.createGroups(rep, realm, user);
        RepresentationToModel.createCredentials(rep, session, realm, user, true);
        adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), user.getId()).representation(rep).success();
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().commit();
        }
        return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(user.getId()).build()).build();
    } catch (ModelDuplicateException e) {
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().setRollbackOnly();
        }
        return ErrorResponse.exists("User exists with same username or email");
    } catch (PasswordPolicyNotMetException e) {
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().setRollbackOnly();
        }
        return ErrorResponse.error("Password policy not met", Response.Status.BAD_REQUEST);
    } catch (ModelException me) {
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().setRollbackOnly();
        }
        logger.warn("Could not create user", me);
        return ErrorResponse.error("Could not create user", Response.Status.BAD_REQUEST);
    }
}
Also used : Response(javax.ws.rs.core.Response) ErrorResponse(org.keycloak.services.ErrorResponse) UserModel(org.keycloak.models.UserModel) ForbiddenException(org.keycloak.services.ForbiddenException) UserProfile(org.keycloak.userprofile.UserProfile) ModelException(org.keycloak.models.ModelException) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) PasswordPolicyNotMetException(org.keycloak.policy.PasswordPolicyNotMetException) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Example 3 with ModelDuplicateException

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

the class AbstractClientRegistrationProvider method create.

public ClientRepresentation create(ClientRegistrationContext context) {
    ClientRepresentation client = context.getClient();
    event.event(EventType.CLIENT_REGISTER);
    RegistrationAuth registrationAuth = auth.requireCreate(context);
    try {
        RealmModel realm = session.getContext().getRealm();
        ClientModel clientModel = ClientManager.createClient(session, realm, client);
        if (client.getDefaultRoles() != null) {
            for (String name : client.getDefaultRoles()) {
                clientModel.addDefaultRole(name);
            }
        }
        if (clientModel.isServiceAccountsEnabled()) {
            new ClientManager(new RealmManager(session)).enableServiceAccount(clientModel);
        }
        if (Boolean.TRUE.equals(client.getAuthorizationServicesEnabled())) {
            RepresentationToModel.createResourceServer(clientModel, session, true);
        }
        session.clientPolicy().triggerOnEvent(new DynamicClientRegisteredContext(context, clientModel, auth.getJwt(), realm));
        ClientRegistrationPolicyManager.triggerAfterRegister(context, registrationAuth, clientModel);
        client = ModelToRepresentation.toRepresentation(clientModel, session);
        client.setSecret(clientModel.getSecret());
        String registrationAccessToken = ClientRegistrationTokenUtils.updateRegistrationAccessToken(session, clientModel, registrationAuth);
        client.setRegistrationAccessToken(registrationAccessToken);
        if (auth.isInitialAccessToken()) {
            ClientInitialAccessModel initialAccessModel = auth.getInitialAccessModel();
            session.realms().decreaseRemainingCount(realm, initialAccessModel);
        }
        client.setDirectAccessGrantsEnabled(false);
        Stream<String> defaultRolesNames = clientModel.getDefaultRolesStream();
        if (defaultRolesNames != null) {
            client.setDefaultRoles(defaultRolesNames.toArray(String[]::new));
        }
        event.client(client.getClientId()).success();
        return client;
    } catch (ModelDuplicateException e) {
        throw new ErrorResponseException(ErrorCodes.INVALID_CLIENT_METADATA, "Client Identifier in use", Response.Status.BAD_REQUEST);
    } catch (ClientPolicyException cpe) {
        throw new ErrorResponseException(cpe.getError(), cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
    }
}
Also used : ClientInitialAccessModel(org.keycloak.models.ClientInitialAccessModel) RegistrationAuth(org.keycloak.services.clientregistration.policy.RegistrationAuth) DynamicClientRegisteredContext(org.keycloak.services.clientpolicy.context.DynamicClientRegisteredContext) RealmManager(org.keycloak.services.managers.RealmManager) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException) RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) ClientManager(org.keycloak.services.managers.ClientManager) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) ErrorResponseException(org.keycloak.services.ErrorResponseException)

Example 4 with ModelDuplicateException

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

the class JpaRealmProvider method addRealmRole.

@Override
public RoleModel addRealmRole(RealmModel realm, String id, String name) {
    if (getRealmRole(realm, name) != null) {
        throw new ModelDuplicateException();
    }
    RoleEntity entity = new RoleEntity();
    entity.setId(id);
    entity.setName(name);
    entity.setRealmId(realm.getId());
    em.persist(entity);
    em.flush();
    RoleAdapter adapter = new RoleAdapter(session, realm, em, entity);
    return adapter;
}
Also used : RoleEntity(org.keycloak.models.jpa.entities.RoleEntity) ModelDuplicateException(org.keycloak.models.ModelDuplicateException)

Example 5 with ModelDuplicateException

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

the class ClientAdapter method addProtocolMapper.

@Override
public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) {
    if (getProtocolMapperByName(model.getProtocol(), model.getName()) != null) {
        throw new ModelDuplicateException("Protocol mapper name must be unique per protocol");
    }
    String id = model.getId() != null ? model.getId() : KeycloakModelUtils.generateId();
    ProtocolMapperEntity entity = new ProtocolMapperEntity();
    entity.setId(id);
    entity.setName(model.getName());
    entity.setProtocol(model.getProtocol());
    entity.setProtocolMapper(model.getProtocolMapper());
    entity.setClient(this.entity);
    entity.setConfig(model.getConfig());
    em.persist(entity);
    this.entity.getProtocolMappers().add(entity);
    return entityToModel(entity);
}
Also used : ProtocolMapperEntity(org.keycloak.models.jpa.entities.ProtocolMapperEntity) 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