use of org.gluu.persist.exception.EntryPersistenceException in project oxTrust by GluuFederation.
the class PasswordResetAction method start.
public String start() throws ParseException {
if (StringHelper.isEmpty(guid)) {
sendExpirationError();
conversationService.endConversation();
return OxTrustConstants.RESULT_FAILURE;
}
setCode(guid);
PasswordResetRequest passwordResetRequest;
try {
passwordResetRequest = passwordResetService.findPasswordResetRequest(getGuid());
} catch (EntryPersistenceException ex) {
log.error("Failed to find password reset request by '{}'", guid, ex);
passwordResetRequest = null;
}
if (passwordResetRequest == null) {
sendExpirationError();
conversationService.endConversation();
return OxTrustConstants.RESULT_FAILURE;
}
PasswordResetRequest personPasswordResetRequest = passwordResetService.findActualPasswordResetRequest(passwordResetRequest.getPersonInum());
if (personPasswordResetRequest == null) {
sendExpirationError();
conversationService.endConversation();
return OxTrustConstants.RESULT_FAILURE;
}
if (!StringHelper.equalsIgnoreCase(guid, personPasswordResetRequest.getOxGuid())) {
sendExpirationError();
conversationService.endConversation();
return OxTrustConstants.RESULT_FAILURE;
}
this.request = personPasswordResetRequest;
Calendar requestCalendarExpiry = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
Calendar currentCalendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
requestCalendarExpiry.setTime(request.getCreationDate());
currentCalendar.add(Calendar.SECOND, -appConfiguration.getPasswordResetRequestExpirationTime());
if (requestCalendarExpiry.after(currentCalendar)) {
return checkSecurityQuetion();
} else {
facesMessages.add(FacesMessage.SEVERITY_ERROR, "Your link is not valid or your user is not allowed to perform a password reset. If you want to initiate a reset password procedure please fill this form.");
conversationService.endConversation();
return OxTrustConstants.RESULT_FAILURE;
}
}
use of org.gluu.persist.exception.EntryPersistenceException in project oxTrust by GluuFederation.
the class PersonImportAction method importPersons.
public String importPersons() throws Exception {
if (!fileDataToImport.isReady()) {
facesMessages.add(FacesMessage.SEVERITY_ERROR, "File to import is invalid");
return OxTrustConstants.RESULT_FAILURE;
}
log.debug("Attempting to add {} persons", fileDataToImport.getPersons().size());
try {
for (GluuCustomPerson person : fileDataToImport.getPersons()) {
this.person = person;
String result = initializePerson();
if (result.equals(OxTrustConstants.RESULT_SUCCESS)) {
result = save();
}
if (result.equals(OxTrustConstants.RESULT_SUCCESS)) {
log.debug("Added new person: {}", person.getUid());
} else {
log.debug("Failed to add new person: {}", person.getUid());
facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to add new person: '%s'", person.getUid());
}
}
} catch (EntryPersistenceException ex) {
log.error("Failed to add new person", ex);
facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to import users");
return OxTrustConstants.RESULT_FAILURE;
}
log.debug("All {} persons added successfully", fileDataToImport.getPersons().size());
oxTrustAuditService.audit(fileDataToImport.getPersons().size() + " USERS IMPORTED ", identity.getUser(), (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest());
facesMessages.add(FacesMessage.SEVERITY_INFO, "Users successfully imported");
removeFileToImport();
return OxTrustConstants.RESULT_SUCCESS;
}
use of org.gluu.persist.exception.EntryPersistenceException in project oxTrust by GluuFederation.
the class CleanUpTest method cleanUpPersons.
/**
* Test search
*
* @throws Exception
*/
// @Test
@Parameters(value = "test.keep.persons")
public void cleanUpPersons(String usedPersons) throws Exception {
System.out.println("cleanup person Test initialted ");
assertNotNull(usedPersons);
List<String> usedPersonsList = Arrays.asList(StringHelper.split(usedPersons, ",", true, false));
System.out.println("Used persons: " + usedPersonsList);
int personsResultSetSize = 50;
int countResults = 0;
int countRemoved = 0;
boolean existsMorePersons = true;
while (existsMorePersons && countResults < 10000) {
List<GluuCustomPerson> persons = personService.findAllPersons(new String[] { "inum" });
existsMorePersons = persons.size() == personsResultSetSize;
countResults += persons.size();
assertNotNull(persons);
System.out.println("Found persons: " + persons.size());
System.out.println("Total persons: " + countResults);
for (GluuCustomPerson person : persons) {
// String clientId = person.getClientId();
if (!usedPersonsList.contains(person.getInum())) {
try {
memberService.removePerson(person);
countRemoved++;
} catch (EntryPersistenceException ex) {
System.out.println("Failed to remove person: " + ex.getMessage());
}
}
}
}
System.out.println("Removed Persons: " + countRemoved);
}
use of org.gluu.persist.exception.EntryPersistenceException in project oxAuth by GluuFederation.
the class AuthorizeAction method checkPermissionGranted.
public void checkPermissionGranted() throws IOException {
if ((clientId == null) || clientId.isEmpty()) {
log.debug("Permission denied. client_id should be not empty.");
permissionDenied();
return;
}
Client client = null;
try {
client = clientService.getClient(clientId);
} catch (EntryPersistenceException ex) {
log.debug("Permission denied. Failed to find client by inum '{}' in LDAP.", clientId, ex);
permissionDenied();
return;
}
if (client == null) {
log.debug("Permission denied. Failed to find client_id '{}' in LDAP.", clientId);
permissionDenied();
return;
}
// Fix the list of scopes in the authorization page. oxAuth #739
Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
allowedScope = org.gluu.oxauth.model.util.StringUtils.implode(grantedScopes, " ");
SessionId session = getSession();
List<Prompt> prompts = Prompt.fromString(prompt, " ");
try {
redirectUri = authorizeRestWebServiceValidator.validateRedirectUri(client, redirectUri, state, session != null ? session.getSessionAttributes().get(SESSION_USER_CODE) : null, (HttpServletRequest) externalContext.getRequest());
} catch (WebApplicationException e) {
log.error(e.getMessage(), e);
permissionDenied();
return;
}
try {
session = sessionIdService.assertAuthenticatedSessionCorrespondsToNewRequest(session, acrValues);
} catch (AcrChangedException e) {
log.debug("There is already existing session which has another acr then {}, session: {}", acrValues, session.getId());
if (e.isForceReAuthentication()) {
session = handleAcrChange(session, prompts);
} else {
log.error("ACR is changed, please provide a supported and enabled acr value");
permissionDenied();
return;
}
}
if (session == null || StringUtils.isBlank(session.getUserDn()) || SessionIdState.AUTHENTICATED != session.getState()) {
Map<String, String> parameterMap = externalContext.getRequestParameterMap();
Map<String, String> requestParameterMap = requestParameterService.getAllowedParameters(parameterMap);
String redirectTo = "/login.xhtml";
boolean useExternalAuthenticator = externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE);
if (useExternalAuthenticator) {
List<String> acrValuesList = sessionIdService.acrValuesList(this.acrValues);
if (acrValuesList.isEmpty()) {
acrValuesList = Arrays.asList(defaultAuthenticationMode.getName());
}
CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.determineCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, acrValuesList);
if (customScriptConfiguration == null) {
log.error("Failed to get CustomScriptConfiguration. auth_step: {}, acr_values: {}", 1, this.acrValues);
permissionDenied();
return;
}
String acr = customScriptConfiguration.getName();
requestParameterMap.put(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, acr);
requestParameterMap.put("auth_step", Integer.toString(1));
String tmpRedirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, 1);
if (StringHelper.isNotEmpty(tmpRedirectTo)) {
log.trace("Redirect to person authentication login page: {}", tmpRedirectTo);
redirectTo = tmpRedirectTo;
}
}
// Store Remote IP
requestParameterMap.put(Constants.REMOTE_IP, getRemoteIp());
// User Code used in Device Authz flow
if (session != null && session.getSessionAttributes().containsKey(SESSION_USER_CODE)) {
String userCode = session.getSessionAttributes().get(SESSION_USER_CODE);
requestParameterMap.put(SESSION_USER_CODE, userCode);
}
// Create unauthenticated session
SessionId unauthenticatedSession = sessionIdService.generateUnauthenticatedSessionId(null, new Date(), SessionIdState.UNAUTHENTICATED, requestParameterMap, false);
unauthenticatedSession.setSessionAttributes(requestParameterMap);
unauthenticatedSession.addPermission(clientId, false);
// Copy ACR script parameters
if (appConfiguration.getKeepAuthenticatorAttributesOnAcrChange()) {
authenticationService.copyAuthenticatorExternalAttributes(session, unauthenticatedSession);
}
// #1030, fix for flow 4 - transfer previous session permissions to new session
if (session != null && session.getPermissionGrantedMap() != null && session.getPermissionGrantedMap().getPermissionGranted() != null) {
for (Map.Entry<String, Boolean> entity : session.getPermissionGrantedMap().getPermissionGranted().entrySet()) {
unauthenticatedSession.addPermission(entity.getKey(), entity.getValue());
}
// #1030, remove previous session
sessionIdService.remove(session);
}
// always persist is prompt is not none
boolean persisted = sessionIdService.persistSessionId(unauthenticatedSession, !prompts.contains(Prompt.NONE));
if (persisted && log.isTraceEnabled()) {
log.trace("Session '{}' persisted to LDAP", unauthenticatedSession.getId());
}
this.sessionId = unauthenticatedSession.getId();
cookieService.createSessionIdCookie(unauthenticatedSession, false);
cookieService.creatRpOriginIdCookie(redirectUri);
identity.setSessionId(unauthenticatedSession);
Map<String, Object> loginParameters = new HashMap<String, Object>();
if (requestParameterMap.containsKey(AuthorizeRequestParam.LOGIN_HINT)) {
loginParameters.put(AuthorizeRequestParam.LOGIN_HINT, requestParameterMap.get(AuthorizeRequestParam.LOGIN_HINT));
}
boolean enableRedirect = StringHelper.toBoolean(System.getProperty("gluu.enable-redirect", "false"), false);
if (!enableRedirect && redirectTo.toLowerCase().endsWith("xhtml")) {
if (redirectTo.toLowerCase().endsWith("postlogin.xhtml")) {
authenticator.authenticateWithOutcome();
} else {
authenticator.prepareAuthenticationForStep(unauthenticatedSession);
facesService.renderView(redirectTo);
}
} else {
facesService.redirectWithExternal(redirectTo, loginParameters);
}
return;
}
String userCode = session.getSessionAttributes().get(SESSION_USER_CODE);
if (StringUtils.isBlank(userCode) && StringUtils.isBlank(redirectionUriService.validateRedirectionUri(clientId, redirectUri))) {
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.setResponseStatus(HttpServletResponse.SC_BAD_REQUEST);
externalContext.setResponseContentType(MediaType.APPLICATION_JSON);
externalContext.getResponseOutputWriter().write(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST_REDIRECT_URI, state, ""));
facesContext.responseComplete();
}
if (log.isTraceEnabled()) {
log.trace("checkPermissionGranted, userDn = " + session.getUserDn());
}
if (prompts.contains(Prompt.SELECT_ACCOUNT)) {
Map requestParameterMap = requestParameterService.getAllowedParameters(externalContext.getRequestParameterMap());
facesService.redirect("/selectAccount.xhtml", requestParameterMap);
return;
}
if (prompts.contains(Prompt.NONE) && prompts.size() > 1) {
invalidRequest();
return;
}
ExternalPostAuthnContext postAuthnContext = new ExternalPostAuthnContext(client, session, (HttpServletRequest) externalContext.getRequest(), (HttpServletResponse) externalContext.getResponse());
final boolean forceAuthorization = externalPostAuthnService.externalForceAuthorization(client, postAuthnContext);
final boolean hasConsentPrompt = prompts.contains(Prompt.CONSENT);
if (!hasConsentPrompt && !forceAuthorization) {
if (appConfiguration.getTrustedClientEnabled() && client.getTrustedClient()) {
// if trusted client = true, then skip authorization page and grant access directly
permissionGranted(session);
return;
} else if (ServerUtil.isTrue(appConfiguration.getSkipAuthorizationForOpenIdScopeAndPairwiseId()) && SubjectType.PAIRWISE.toString().equals(client.getSubjectType()) && hasOnlyOpenidScope()) {
// If a client has only openid scope and pairwise id, person should not have to authorize. oxAuth-743
permissionGranted(session);
return;
}
final User user = sessionIdService.getUser(session);
ClientAuthorization clientAuthorization = clientAuthorizationsService.find(user.getAttribute("inum"), client.getClientId());
if (clientAuthorization != null && clientAuthorization.getScopes() != null && Arrays.asList(clientAuthorization.getScopes()).containsAll(org.gluu.oxauth.model.util.StringUtils.spaceSeparatedToList(scope))) {
permissionGranted(session);
return;
}
}
if (externalConsentGatheringService.isEnabled()) {
if (consentGatherer.isConsentGathered()) {
log.trace("Consent-gathered flow passed successfully");
permissionGranted(session);
return;
}
log.trace("Starting external consent-gathering flow");
boolean result = consentGatherer.configure(session.getUserDn(), clientId, state);
if (!result) {
log.error("Failed to initialize external consent-gathering flow.");
permissionDenied();
return;
}
}
}
use of org.gluu.persist.exception.EntryPersistenceException in project oxAuth by GluuFederation.
the class AuthorizeAction method getRequestedClaims.
public List<String> getRequestedClaims() {
Set<String> result = new HashSet<String>();
String requestJwt = request;
if (StringUtils.isBlank(requestJwt) && StringUtils.isNotBlank(requestUri)) {
try {
URI reqUri = new URI(requestUri);
String reqUriHash = reqUri.getFragment();
String reqUriWithoutFragment = reqUri.getScheme() + ":" + reqUri.getSchemeSpecificPart();
javax.ws.rs.client.Client clientRequest = ClientBuilder.newClient();
try {
Response clientResponse = clientRequest.target(reqUriWithoutFragment).request().buildGet().invoke();
clientRequest.close();
int status = clientResponse.getStatus();
if (status == 200) {
String entity = clientResponse.readEntity(String.class);
if (StringUtils.isBlank(reqUriHash)) {
requestJwt = entity;
} else {
String hash = Base64Util.base64urlencode(JwtUtil.getMessageDigestSHA256(entity));
if (StringUtils.equals(reqUriHash, hash)) {
requestJwt = entity;
}
}
}
} finally {
clientRequest.close();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
if (StringUtils.isNotBlank(requestJwt)) {
try {
Client client = clientService.getClient(clientId);
if (client != null) {
JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(appConfiguration, cryptoProvider, request, client);
if (jwtAuthorizationRequest.getUserInfoMember() != null) {
for (Claim claim : jwtAuthorizationRequest.getUserInfoMember().getClaims()) {
result.add(claim.getName());
}
}
if (jwtAuthorizationRequest.getIdTokenMember() != null) {
for (Claim claim : jwtAuthorizationRequest.getIdTokenMember().getClaims()) {
result.add(claim.getName());
}
}
}
} catch (EntryPersistenceException | InvalidJwtException e) {
log.error(e.getMessage(), e);
}
}
return new ArrayList<>(result);
}
Aggregations