/** * Set up a temporary password for the user * * <p>User will have to reset the temporary password next time they log in. * * @param id User id * @param pass A Temporary password */ @Path("{id}/reset-password") @PUT @Consumes(MediaType.APPLICATION_JSON) public void resetPassword(@PathParam("id") String id, CredentialRepresentation pass) { auth.requireManage(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } if (pass == null || pass.getValue() == null || !CredentialRepresentation.PASSWORD.equals(pass.getType())) { throw new BadRequestException("No password provided"); } UserCredentialModel cred = RepresentationToModel.convertCredential(pass); try { session.users().updateCredential(realm, user, cred); } catch (IllegalStateException ise) { throw new BadRequestException("Resetting to N old passwords is not allowed."); } catch (ModelReadOnlyException mre) { throw new BadRequestException("Can't reset password as account is read only"); } if (pass.isTemporary() != null && pass.isTemporary()) user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); adminEvent.operation(OperationType.ACTION).resourcePath(uriInfo).success(); }
/** * Remove a social login provider from user * * @param id User id * @param provider Social login provider id */ @Path("{id}/federated-identity/{provider}") @DELETE @NoCache public void removeFederatedIdentity( final @PathParam("id") String id, final @PathParam("provider") String provider) { auth.requireManage(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } if (!session.users().removeFederatedIdentity(realm, user, provider)) { throw new NotFoundException("Link not found"); } adminEvent.operation(OperationType.DELETE).resourcePath(uriInfo).success(); }
/** * Revoke consent and offline tokens for particular client from user * * @param id User id * @param clientId Client id */ @Path("{id}/consents/{client}") @DELETE @NoCache public void revokeConsent( final @PathParam("id") String id, final @PathParam("client") String clientId) { auth.requireManage(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } ClientModel client = realm.getClientByClientId(clientId); boolean revokedConsent = user.revokeConsentForClient(client.getId()); boolean revokedOfflineToken = new UserSessionManager(session).revokeOfflineToken(user, client); if (revokedConsent) { // Logout clientSessions for this user and client AuthenticationManager.backchannelUserFromClient( session, realm, user, client, uriInfo, headers); } if (!revokedConsent && !revokedOfflineToken) { throw new NotFoundException("Consent nor offline token not found"); } adminEvent.operation(OperationType.ACTION).resourcePath(uriInfo).success(); }
/** * Get offline sessions associated with the user and client * * @param id User id * @return */ @Path("{id}/offline-sessions/{clientId}") @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public List<UserSessionRepresentation> getSessions( final @PathParam("id") String id, final @PathParam("clientId") String clientId) { auth.requireView(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } ClientModel client = realm.getClientById(clientId); if (client == null) { throw new NotFoundException("Client not found"); } List<UserSessionModel> sessions = new UserSessionManager(session).findOfflineSessions(realm, client, user); List<UserSessionRepresentation> reps = new ArrayList<UserSessionRepresentation>(); for (UserSessionModel session : sessions) { UserSessionRepresentation rep = ModelToRepresentation.toRepresentation(session); // Update lastSessionRefresh with the timestamp from clientSession for (ClientSessionModel clientSession : session.getClientSessions()) { if (clientId.equals(clientSession.getClient().getId())) { rep.setLastAccess(Time.toMillis(clientSession.getTimestamp())); break; } } reps.add(rep); } return reps; }
@Override public void disableCredential(RealmModel realm, UserModel user, String credentialType) { if (!StorageId.isLocalStorage(user)) { String providerId = StorageId.resolveProviderId(user); UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, providerId); if (provider instanceof CredentialInputUpdater) { CredentialInputUpdater updater = (CredentialInputUpdater) provider; if (updater.supportsCredentialType(credentialType)) { updater.disableCredentialType(realm, user, credentialType); } } } else { UserFederationProvider link = session.users().getFederationLink(realm, user); if (link != null && link.getSupportedCredentialTypes().contains(credentialType)) { link.disableCredentialType(realm, user, credentialType); } else if (user.getFederationLink() != null) { UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, user.getFederationLink()); if (provider != null && provider instanceof CredentialInputUpdater) { ((CredentialInputUpdater) provider).disableCredentialType(realm, user, credentialType); } } } List<CredentialInputUpdater> credentialProviders = getCredentialProviders(realm, CredentialInputUpdater.class); for (CredentialInputUpdater updater : credentialProviders) { if (!updater.supportsCredentialType(credentialType)) continue; updater.disableCredentialType(realm, user, credentialType); } }
@Override public void updateCredential(RealmModel realm, UserModel user, CredentialInput input) { if (!StorageId.isLocalStorage(user)) { String providerId = StorageId.resolveProviderId(user); UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, providerId); if (provider instanceof CredentialInputUpdater) { CredentialInputUpdater updater = (CredentialInputUpdater) provider; if (updater.supportsCredentialType(input.getType())) { if (updater.updateCredential(realm, user, input)) return; } } } else { // <deprecated> UserFederationProvider link = session.users().getFederationLink(realm, user); if (link != null) { if (link.updateCredential(realm, user, input)) return; } // </deprecated> else if (user.getFederationLink() != null) { UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, user.getFederationLink()); if (provider != null && provider instanceof CredentialInputUpdater) { if (((CredentialInputUpdater) provider).updateCredential(realm, user, input)) return; } } } List<CredentialInputUpdater> credentialProviders = getCredentialProviders(realm, CredentialInputUpdater.class); for (CredentialInputUpdater updater : credentialProviders) { if (!updater.supportsCredentialType(input.getType())) continue; if (updater.updateCredential(realm, user, input)) return; } }
/** * Get represenation of the user * * @param id User id * @return */ @Path("{id}") @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public UserRepresentation getUser(final @PathParam("id") String id) { auth.requireView(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } UserRepresentation rep = ModelToRepresentation.toRepresentation(user); if (realm.isIdentityFederationEnabled()) { List<FederatedIdentityRepresentation> reps = getFederatedIdentities(user); rep.setFederatedIdentities(reps); } if (session .getProvider(BruteForceProtector.class) .isTemporarilyDisabled(session, realm, rep.getUsername())) { rep.setEnabled(false); } return rep; }
@Override public boolean isConfiguredFor(RealmModel realm, UserModel user, String type) { if (!StorageId.isLocalStorage(user)) { String providerId = StorageId.resolveProviderId(user); UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, providerId); if (provider instanceof CredentialInputValidator) { CredentialInputValidator validator = (CredentialInputValidator) provider; if (validator.supportsCredentialType(type) && validator.isConfiguredFor(realm, user, type)) { return true; } } } else { // <deprecate> UserFederationProvider link = session.users().getFederationLink(realm, user); if (link != null) { if (link.isConfiguredFor(realm, user, type)) return true; } // </deprecate> else if (user.getFederationLink() != null) { UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, user.getFederationLink()); if (provider != null && provider instanceof CredentialInputValidator) { if (((CredentialInputValidator) provider).isConfiguredFor(realm, user, type)) return true; } } } return isConfiguredLocally(realm, user, type); }
protected void assertUser( String expectedUsername, String expectedEmail, String expectedFirstname, String expectedLastname, boolean updateProfileActionExpected) { KeycloakRule keycloakRule = getKeycloakRule(); KeycloakSession session = keycloakRule.startSession(); try { RealmManager manager = new RealmManager(session); RealmModel appRealm = manager.getRealm("test"); UserModel user = session.users().getUserByUsername(expectedUsername, appRealm); Assert.assertNotNull(user); Assert.assertEquals(user.getEmail(), expectedEmail); Assert.assertEquals(user.getFirstName(), expectedFirstname); Assert.assertEquals(user.getLastName(), expectedLastname); if (updateProfileActionExpected) { Assert.assertEquals( UserModel.RequiredAction.UPDATE_PROFILE.toString(), user.getRequiredActions().iterator().next()); } else { Assert.assertTrue(user.getRequiredActions().isEmpty()); } } finally { keycloakRule.stopSession(session, true); } }
private static String createAdminToken(String username, String realm) { KeycloakSession session = keycloakRule.startSession(); try { RealmManager manager = new RealmManager(session); RealmModel adminRealm = manager.getRealm(realm); ClientModel adminConsole = adminRealm.getClientByClientId(Constants.ADMIN_CLI_CLIENT_ID); TokenManager tm = new TokenManager(); UserModel admin = session.users().getUserByUsername(username, adminRealm); ClientSessionModel clientSession = session.sessions().createClientSession(adminRealm, adminConsole); clientSession.setNote(OIDCLoginProtocol.ISSUER, "http://localhost:8081/auth/realms/" + realm); UserSessionModel userSession = session .sessions() .createUserSession(adminRealm, admin, "admin", null, "form", false, null, null); AccessToken token = tm.createClientAccessToken( session, tm.getAccess(null, true, adminConsole, admin), adminRealm, adminConsole, admin, userSession, clientSession); return tm.encodeToken(adminRealm, token); } finally { keycloakRule.stopSession(session, true); } }
@Override public CredentialValidationOutput authenticate( KeycloakSession session, RealmModel realm, CredentialInput input) { List<UserFederationProviderModel> fedProviderModels = realm.getUserFederationProviders(); List<UserFederationProvider> fedProviders = new ArrayList<UserFederationProvider>(); for (UserFederationProviderModel fedProviderModel : fedProviderModels) { UserFederationProvider provider = session.users().getFederationProvider(fedProviderModel); if (input instanceof UserCredentialModel && provider != null && provider.supportsCredentialType(input.getType())) { CredentialValidationOutput output = provider.validCredentials(realm, (UserCredentialModel) input); if (output != null) return output; } } List<CredentialAuthentication> list = UserStorageManager.getStorageProviders(session, realm, CredentialAuthentication.class); for (CredentialAuthentication auth : list) { if (auth.supportsCredentialAuthenticationFor(input.getType())) { CredentialValidationOutput output = auth.authenticate(realm, input); if (output != null) return output; } } list = getCredentialProviders(realm, CredentialAuthentication.class); for (CredentialAuthentication auth : list) { if (auth.supportsCredentialAuthenticationFor(input.getType())) { CredentialValidationOutput output = auth.authenticate(realm, input); if (output != null) return output; } } return null; }
@Override public boolean isValid(RealmModel realm, UserModel user, List<CredentialInput> inputs) { List<CredentialInput> toValidate = new LinkedList<>(); toValidate.addAll(inputs); if (!StorageId.isLocalStorage(user)) { String providerId = StorageId.resolveProviderId(user); UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, providerId); if (provider instanceof CredentialInputValidator) { Iterator<CredentialInput> it = toValidate.iterator(); while (it.hasNext()) { CredentialInput input = it.next(); CredentialInputValidator validator = (CredentialInputValidator) provider; if (validator.supportsCredentialType(input.getType()) && validator.isValid(realm, user, input)) { it.remove(); } } } } else { // <deprecate> UserFederationProvider link = session.users().getFederationLink(realm, user); if (link != null) { session.users().validateUser(realm, user); validate(realm, user, toValidate, link); } // </deprecate> else if (user.getFederationLink() != null) { UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, user.getFederationLink()); if (provider != null && provider instanceof CredentialInputValidator) { validate(realm, user, toValidate, ((CredentialInputValidator) provider)); } } } if (toValidate.isEmpty()) return true; List<CredentialInputValidator> credentialProviders = getCredentialProviders(realm, CredentialInputValidator.class); for (CredentialInputValidator validator : credentialProviders) { validate(realm, user, toValidate, validator); } return toValidate.isEmpty(); }
/** * Get users * * <p>Returns a list of users, filtered according to query parameters * * @param search A String contained in username, first or last name, or email * @param last * @param first * @param email * @param username * @param first Pagination offset * @param maxResults Pagination size * @return */ @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public List<UserRepresentation> getUsers( @QueryParam("search") String search, @QueryParam("lastName") String last, @QueryParam("firstName") String first, @QueryParam("email") String email, @QueryParam("username") String username, @QueryParam("first") Integer firstResult, @QueryParam("max") Integer maxResults) { auth.requireView(); firstResult = firstResult != null ? firstResult : -1; maxResults = maxResults != null ? maxResults : -1; List<UserRepresentation> results = new ArrayList<UserRepresentation>(); List<UserModel> userModels; if (search != null) { userModels = session.users().searchForUser(search.trim(), realm, firstResult, maxResults); } else if (last != null || first != null || email != null || username != null) { Map<String, String> attributes = new HashMap<String, String>(); if (last != null) { attributes.put(UserModel.LAST_NAME, last); } if (first != null) { attributes.put(UserModel.FIRST_NAME, first); } if (email != null) { attributes.put(UserModel.EMAIL, email); } if (username != null) { attributes.put(UserModel.USERNAME, username); } userModels = session.users().searchForUserByAttributes(attributes, realm, firstResult, maxResults); } else { userModels = session.users().getUsers(realm, firstResult, maxResults, false); } for (UserModel user : userModels) { results.add(ModelToRepresentation.toRepresentation(user)); } return results; }
protected UserModel getUser(String userId) { KeycloakSession samlServerSession = keycloakRule.startSession(); try { RealmModel brokerRealm = samlServerSession.realms().getRealm("test"); return samlServerSession.users().getUserById(userId, brokerRealm); } finally { keycloakRule.stopSession(samlServerSession, false); } }
/** * Impersonate the user * * @param id User id * @return */ @Path("{id}/impersonation") @POST @NoCache @Produces(MediaType.APPLICATION_JSON) public Map<String, Object> impersonate(final @PathParam("id") String id) { auth.init(RealmAuth.Resource.IMPERSONATION); auth.requireManage(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } RealmModel authenticatedRealm = auth.getAuth().getRealm(); // if same realm logout before impersonation boolean sameRealm = false; if (authenticatedRealm.getId().equals(realm.getId())) { sameRealm = true; UserSessionModel userSession = session .sessions() .getUserSession(authenticatedRealm, auth.getAuth().getToken().getSessionState()); AuthenticationManager.expireIdentityCookie(realm, uriInfo, clientConnection); AuthenticationManager.expireRememberMeCookie(realm, uriInfo, clientConnection); AuthenticationManager.backchannelLogout( session, authenticatedRealm, userSession, uriInfo, clientConnection, headers, true); } EventBuilder event = new EventBuilder(realm, session, clientConnection); UserSessionModel userSession = session .sessions() .createUserSession( realm, user, user.getUsername(), clientConnection.getRemoteAddr(), "impersonate", false, null, null); AuthenticationManager.createLoginCookie( realm, userSession.getUser(), userSession, uriInfo, clientConnection); URI redirect = AccountService.accountServiceApplicationPage(uriInfo).build(realm.getName()); Map<String, Object> result = new HashMap<>(); result.put("sameRealm", sameRealm); result.put("redirect", redirect.toString()); event .event(EventType.IMPERSONATE) .session(userSession) .user(user) .detail(Details.IMPERSONATOR_REALM, authenticatedRealm.getName()) .detail(Details.IMPERSONATOR, auth.getAuth().getUser().getUsername()) .success(); return result; }
/** * Get consents granted by the user * * @param id User id * @return */ @Path("{id}/consents") @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public List<Map<String, Object>> getConsents(final @PathParam("id") String id) { auth.requireView(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } List<Map<String, Object>> result = new LinkedList<>(); Set<ClientModel> offlineClients = new UserSessionManager(session).findClientsWithOfflineToken(realm, user); for (ClientModel client : realm.getClients()) { UserConsentModel consent = user.getConsentByClient(client.getId()); boolean hasOfflineToken = offlineClients.contains(client); if (consent == null && !hasOfflineToken) { continue; } UserConsentRepresentation rep = (consent == null) ? null : ModelToRepresentation.toRepresentation(consent); Map<String, Object> currentRep = new HashMap<>(); currentRep.put("clientId", client.getClientId()); currentRep.put( "grantedProtocolMappers", (rep == null ? Collections.emptyMap() : rep.getGrantedProtocolMappers())); currentRep.put( "grantedRealmRoles", (rep == null ? Collections.emptyList() : rep.getGrantedRealmRoles())); currentRep.put( "grantedClientRoles", (rep == null ? Collections.emptyMap() : rep.getGrantedClientRoles())); List<Map<String, String>> additionalGrants = new LinkedList<>(); if (hasOfflineToken) { Map<String, String> offlineTokens = new HashMap<>(); offlineTokens.put("client", client.getId()); // TODO: translate offlineTokens.put("key", "Offline Token"); additionalGrants.add(offlineTokens); } currentRep.put("additionalGrants", additionalGrants); result.add(currentRep); } return result; }
/** * Add a social login provider to the user * * @param id User id * @param provider Social login provider id * @param rep * @return */ @Path("{id}/federated-identity/{provider}") @POST @NoCache public Response addFederatedIdentity( final @PathParam("id") String id, final @PathParam("provider") String provider, FederatedIdentityRepresentation rep) { auth.requireManage(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } if (session.users().getFederatedIdentity(user, provider, realm) != null) { return ErrorResponse.exists("User is already linked with provider"); } FederatedIdentityModel socialLink = new FederatedIdentityModel(provider, rep.getUserId(), rep.getUserName()); session.users().addFederatedIdentity(realm, user, socialLink); adminEvent.operation(OperationType.CREATE).resourcePath(uriInfo).representation(rep).success(); return Response.noContent().build(); }
@Path("{id}/role-mappings") public RoleMapperResource getRoleMappings(@PathParam("id") String id) { UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } auth.init(RealmAuth.Resource.USER); RoleMapperResource resource = new RoleMapperResource(realm, auth, user, adminEvent); ResteasyProviderFactory.getInstance().injectProperties(resource); return resource; }
/** * Send a update account email to the user * * <p>An email contains a link the user can click to perform a set of required actions. The * redirectUri and clientId parameters are optional. The default for the redirect is the account * client. * * @param id User is * @param redirectUri Redirect uri * @param clientId Client id * @param actions required actions the user needs to complete * @return */ @Path("{id}/execute-actions-email") @PUT @Consumes(MediaType.APPLICATION_JSON) public Response executeActionsEmail( @PathParam("id") String id, @QueryParam(OIDCLoginProtocol.REDIRECT_URI_PARAM) String redirectUri, @QueryParam(OIDCLoginProtocol.CLIENT_ID_PARAM) String clientId, List<String> actions) { auth.requireManage(); UserModel user = session.users().getUserById(id, realm); if (user == null) { return ErrorResponse.error("User not found", Response.Status.NOT_FOUND); } if (user.getEmail() == null) { return ErrorResponse.error("User email missing", Response.Status.BAD_REQUEST); } ClientSessionModel clientSession = createClientSession(user, redirectUri, clientId); for (String action : actions) { clientSession.addRequiredAction(action); } ClientSessionCode accessCode = new ClientSessionCode(realm, clientSession); accessCode.setAction(ClientSessionModel.Action.EXECUTE_ACTIONS.name()); try { UriBuilder builder = Urls.executeActionsBuilder(uriInfo.getBaseUri()); builder.queryParam("key", accessCode.getCode()); String link = builder.build(realm.getName()).toString(); long expiration = TimeUnit.SECONDS.toMinutes(realm.getAccessCodeLifespanUserAction()); this.session .getProvider(EmailTemplateProvider.class) .setRealm(realm) .setUser(user) .sendExecuteActions(link, expiration); // audit.user(user).detail(Details.EMAIL, user.getEmail()).detail(Details.CODE_ID, // accessCode.getCodeId()).success(); adminEvent.operation(OperationType.ACTION).resourcePath(uriInfo).success(); return Response.ok().build(); } catch (EmailException e) { logger.failedToSendActionsEmail(e); return ErrorResponse.error( "Failed to send execute actions email", Response.Status.INTERNAL_SERVER_ERROR); } }
/** * Remove TOTP from the user * * @param id User id */ @Path("{id}/remove-totp") @PUT @Consumes(MediaType.APPLICATION_JSON) public void removeTotp(@PathParam("id") String id) { auth.requireManage(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } user.setOtpEnabled(false); adminEvent.operation(OperationType.ACTION).resourcePath(uriInfo).success(); }
/** * Get social logins associated with the user * * @param id User id * @return */ @Path("{id}/federated-identity") @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public List<FederatedIdentityRepresentation> getFederatedIdentity( final @PathParam("id") String id) { auth.requireView(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } return getFederatedIdentities(user); }
private List<FederatedIdentityRepresentation> getFederatedIdentities(UserModel user) { Set<FederatedIdentityModel> identities = session.users().getFederatedIdentities(user, realm); List<FederatedIdentityRepresentation> result = new ArrayList<FederatedIdentityRepresentation>(); for (FederatedIdentityModel identity : identities) { for (IdentityProviderModel identityProviderModel : realm.getIdentityProviders()) { if (identityProviderModel.getAlias().equals(identity.getIdentityProvider())) { FederatedIdentityRepresentation rep = ModelToRepresentation.toRepresentation(identity); result.add(rep); } } } return result; }
/** * Create a new user * * <p>Username must be unique. * * @param uriInfo * @param rep * @return */ @POST @Consumes(MediaType.APPLICATION_JSON) public Response createUser(final @Context UriInfo uriInfo, final UserRepresentation rep) { auth.requireManage(); // Double-check duplicated username and email here due to federation if (session.users().getUserByUsername(rep.getUsername(), realm) != null) { return ErrorResponse.exists("User exists with same username"); } if (rep.getEmail() != null && session.users().getUserByEmail(rep.getEmail(), realm) != null) { return ErrorResponse.exists("User exists with same email"); } try { UserModel user = session.users().addUser(realm, rep.getUsername()); Set<String> emptySet = Collections.emptySet(); updateUserFromRep(user, rep, emptySet, realm, session); adminEvent .operation(OperationType.CREATE) .resourcePath(uriInfo, user.getId()) .representation(rep) .success(); if (session.getTransaction().isActive()) { session.getTransaction().commit(); } return Response.created(uriInfo.getAbsolutePathBuilder().path(user.getId()).build()).build(); } catch (ModelDuplicateException e) { if (session.getTransaction().isActive()) { session.getTransaction().setRollbackOnly(); } return ErrorResponse.exists("User exists with same username or email"); } }
/** * Get a user dedicated to the service account * * @return */ @Path("service-account-user") @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public UserRepresentation getServiceAccountUser() { auth.requireView(); if (client == null) { throw new NotFoundException("Could not find client"); } UserModel user = session.users().getServiceAccount(client); if (user == null) { if (client.isServiceAccountsEnabled()) { new ClientManager(new RealmManager(session)).enableServiceAccount(client); user = session.users().getServiceAccount(client); } else { throw new BadRequestException( "Service account not enabled for the client '" + client.getClientId() + "'"); } } return ModelToRepresentation.toRepresentation(session, realm, user); }
/** * Remove all user sessions associated with the user * * <p>Also send notification to all clients that have an admin URL to invalidate the sessions for * the particular user. * * @param id User id */ @Path("{id}/logout") @POST public void logout(final @PathParam("id") String id) { auth.requireManage(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } List<UserSessionModel> userSessions = session.sessions().getUserSessions(realm, user); for (UserSessionModel userSession : userSessions) { AuthenticationManager.backchannelLogout( session, realm, userSession, uriInfo, clientConnection, headers, true); } adminEvent.operation(OperationType.ACTION).resourcePath(uriInfo).success(); }
@DELETE @Path("{id}/groups/{groupId}") @NoCache public void removeMembership(@PathParam("id") String id, @PathParam("groupId") String groupId) { auth.requireManage(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } GroupModel group = session.realms().getGroupById(groupId, realm); if (group == null) { throw new NotFoundException("Group not found"); } if (user.isMemberOf(group)) user.leaveGroup(group); }
@GET @Path("{id}/groups") @NoCache @Produces(MediaType.APPLICATION_JSON) public List<GroupRepresentation> groupMembership(@PathParam("id") String id) { auth.requireView(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } List<GroupRepresentation> memberships = new LinkedList<>(); for (GroupModel group : user.getGroups()) { memberships.add(ModelToRepresentation.toRepresentation(group, false)); } return memberships; }
/** * Update the user * * @param id User id * @param rep * @return */ @Path("{id}") @PUT @Consumes(MediaType.APPLICATION_JSON) public Response updateUser(final @PathParam("id") String id, final UserRepresentation rep) { auth.requireManage(); try { UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } Set<String> attrsToRemove; if (rep.getAttributes() != null) { attrsToRemove = new HashSet<>(user.getAttributes().keySet()); attrsToRemove.removeAll(rep.getAttributes().keySet()); } else { attrsToRemove = Collections.emptySet(); } if (rep.isEnabled() != null && rep.isEnabled()) { UsernameLoginFailureModel failureModel = session.sessions().getUserLoginFailure(realm, rep.getUsername().toLowerCase()); if (failureModel != null) { failureModel.clearFailures(); } } updateUserFromRep(user, rep, attrsToRemove, realm, session); adminEvent .operation(OperationType.UPDATE) .resourcePath(uriInfo) .representation(rep) .success(); if (session.getTransaction().isActive()) { session.getTransaction().commit(); } return Response.noContent().build(); } catch (ModelDuplicateException e) { return ErrorResponse.exists("User exists with same username or email"); } catch (ModelReadOnlyException re) { return ErrorResponse.exists("User is read only!"); } }
/** * Get sessions associated with the user * * @param id User id * @return */ @Path("{id}/sessions") @GET @NoCache @Produces(MediaType.APPLICATION_JSON) public List<UserSessionRepresentation> getSessions(final @PathParam("id") String id) { auth.requireView(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } List<UserSessionModel> sessions = session.sessions().getUserSessions(realm, user); List<UserSessionRepresentation> reps = new ArrayList<UserSessionRepresentation>(); for (UserSessionModel session : sessions) { UserSessionRepresentation rep = ModelToRepresentation.toRepresentation(session); reps.add(rep); } return reps; }
/** * Delete the user * * @param id User id */ @Path("{id}") @DELETE @NoCache public Response deleteUser(final @PathParam("id") String id) { auth.requireManage(); UserModel user = session.users().getUserById(id, realm); if (user == null) { throw new NotFoundException("User not found"); } boolean removed = new UserManager(session).removeUser(realm, user); if (removed) { adminEvent.operation(OperationType.DELETE).resourcePath(uriInfo).success(); return Response.noContent().build(); } else { return ErrorResponse.error("User couldn't be deleted", Response.Status.BAD_REQUEST); } }