use of org.orcid.pojo.ajaxForm.RequestInfoForm in project ORCID-Source by ORCID.
the class OauthAuthorizeController method authorize.
@RequestMapping(value = { "/oauth/custom/authorize.json" }, method = RequestMethod.POST)
@ResponseBody
public RequestInfoForm authorize(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthAuthorizeForm form) {
RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute(REQUEST_INFO_FORM);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
AuthorizationRequest authorizationRequest = (AuthorizationRequest) request.getSession().getAttribute("authorizationRequest");
Map<String, String> requestParams = new HashMap<String, String>(authorizationRequest.getRequestParameters());
Map<String, String> approvalParams = new HashMap<String, String>();
// Add the persistent token information
if (form.getApproved()) {
requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
} else {
requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "false");
approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "false");
}
requestParams.put(OrcidOauth2Constants.TOKEN_VERSION, OrcidOauth2Constants.PERSISTENT_TOKEN);
// Check if the client have persistent tokens enabled
requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "false");
if (hasPersistenTokensEnabled(requestInfoForm.getClientId()))
// Then check if the client granted the persistent token
if (form.getPersistentTokenEnabled())
requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "true");
// strip /email/read-private scope if user has not consented
if (requestInfoForm.containsEmailReadPrivateScope() && !form.isEmailAccessAllowed()) {
requestInfoForm.removeEmailReadPrivateScope();
requestParams.put(OrcidOauth2Constants.SCOPE_PARAM, requestInfoForm.getScopesAsString());
}
// Session status
SimpleSessionStatus status = new SimpleSessionStatus();
authorizationRequest.setRequestParameters(requestParams);
// Authorization request model
Map<String, Object> model = new HashMap<String, Object>();
model.put("authorizationRequest", authorizationRequest);
// Approve
RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
requestInfoForm.setRedirectUrl(view.getUrl());
if (new HttpSessionRequestCache().getRequest(request, response) != null)
new HttpSessionRequestCache().removeRequest(request, response);
LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: " + requestInfoForm.getRedirectUrl());
return requestInfoForm;
}
use of org.orcid.pojo.ajaxForm.RequestInfoForm in project ORCID-Source by ORCID.
the class LoginController method handleOauthSignIn.
private ModelAndView handleOauthSignIn(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
String queryString = request.getQueryString();
String redirectUri = null;
// Get and save the request information form
RequestInfoForm requestInfoForm = generateRequestInfoForm(queryString);
request.getSession().setAttribute(REQUEST_INFO_FORM, requestInfoForm);
// Save also the original query string
request.getSession().setAttribute(OrcidOauth2Constants.OAUTH_QUERY_STRING, queryString);
// Save a flag to indicate this is a request from the new
request.getSession().setAttribute(OrcidOauth2Constants.OAUTH_2SCREENS, true);
// Redirect URI
redirectUri = requestInfoForm.getRedirectUrl();
// Check that the client have the required permissions
// Get client name
String clientId = requestInfoForm.getClientId();
if (PojoUtil.isEmpty(clientId)) {
String redirectUriWithParams = redirectUri + "?error=invalid_client&error_description=invalid client_id";
return new ModelAndView(new RedirectView(redirectUriWithParams));
}
// Validate client details
ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
try {
orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
} catch (LockedException e) {
String redirectUriWithParams = redirectUri + "?error=client_locked&error_description=" + e.getMessage();
return new ModelAndView(new RedirectView(redirectUriWithParams));
}
// validate client scopes
try {
authorizationEndpoint.validateScope(requestInfoForm.getScopesAsString(), clientDetails, requestInfoForm.getResponseType());
} catch (InvalidScopeException e) {
String redirectUriWithParams = redirectUri + "?error=invalid_scope&error_description=" + e.getMessage();
return new ModelAndView(new RedirectView(redirectUriWithParams));
}
// handle openID behaviour
if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()) && ScopePathType.getScopesFromSpaceSeparatedString(requestInfoForm.getScopesAsString()).contains(ScopePathType.OPENID)) {
String prompt = request.getParameter(OrcidOauth2Constants.PROMPT);
if (prompt != null && prompt.equals(OrcidOauth2Constants.PROMPT_NONE)) {
String redirectUriWithParams = requestInfoForm.getRedirectUrl();
redirectUriWithParams += "?error=login_required";
RedirectView rView = new RedirectView(redirectUriWithParams);
ModelAndView error = new ModelAndView();
error.setView(rView);
return error;
}
}
ModelAndView mav = new ModelAndView("login");
boolean showLogin = false;
// orcid and email take precedence over show_login param
if (PojoUtil.isEmpty(requestInfoForm.getUserOrcid()) && PojoUtil.isEmpty(requestInfoForm.getUserEmail()) && queryString.toLowerCase().contains("show_login=false")) {
showLogin = false;
} else if (PojoUtil.isEmpty(requestInfoForm.getUserOrcid()) && PojoUtil.isEmpty(requestInfoForm.getUserEmail())) {
showLogin = true;
} else if (!PojoUtil.isEmpty(requestInfoForm.getUserOrcid()) && profileEntityManager.orcidExists(requestInfoForm.getUserOrcid())) {
mav.addObject("oauth_userId", requestInfoForm.getUserOrcid());
showLogin = true;
} else if (!PojoUtil.isEmpty(requestInfoForm.getUserEmail())) {
mav.addObject("oauth_userId", requestInfoForm.getUserEmail());
if (emailManagerReadOnly.emailExists(requestInfoForm.getUserEmail())) {
showLogin = true;
}
}
mav.addObject("showLogin", String.valueOf(showLogin));
mav.addObject("hideUserVoiceScript", true);
mav.addObject("oauth2Screens", true);
return mav;
}
use of org.orcid.pojo.ajaxForm.RequestInfoForm in project ORCID-Source by ORCID.
the class OauthAuthorizeController method loginGetHandler.
/**
* This is called if user is already logged in.
* Checks permissions have been granted to client and generates access code.
*
* @param request
* @param response
* @param mav
* @return
* @throws UnsupportedEncodingException
*/
@RequestMapping(value = "/oauth/confirm_access", method = RequestMethod.GET)
public ModelAndView loginGetHandler(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) throws UnsupportedEncodingException {
// Get and save the request information form
RequestInfoForm requestInfoForm = generateRequestInfoForm(request);
request.getSession().setAttribute(REQUEST_INFO_FORM, requestInfoForm);
Boolean justRegistered = (Boolean) request.getSession().getAttribute(OrcidOauth2Constants.JUST_REGISTERED);
if (justRegistered != null) {
request.getSession().removeAttribute(OrcidOauth2Constants.JUST_REGISTERED);
mav.addObject(OrcidOauth2Constants.JUST_REGISTERED, justRegistered);
}
boolean usePersistentTokens = false;
ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(requestInfoForm.getClientId());
// validate client scopes
try {
authorizationEndpoint.validateScope(requestInfoForm.getScopesAsString(), clientDetails, requestInfoForm.getResponseType());
orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
} catch (InvalidScopeException | LockedException e) {
String redirectUriWithParams = requestInfoForm.getRedirectUrl();
if (e instanceof InvalidScopeException) {
redirectUriWithParams += "?error=invalid_scope&error_description=" + e.getMessage();
} else {
redirectUriWithParams += "?error=client_locked&error_description=" + e.getMessage();
}
RedirectView rView = new RedirectView(redirectUriWithParams);
ModelAndView error = new ModelAndView();
error.setView(rView);
return error;
}
// Add check for prompt=login and max_age here. This is a MUST in the openid spec.
// Add check for prompt=confirm here. This is a SHOULD in the openid spec.
boolean forceConfirm = false;
if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()) && ScopePathType.getScopesFromSpaceSeparatedString(requestInfoForm.getScopesAsString()).contains(ScopePathType.OPENID)) {
String prompt = request.getParameter(OrcidOauth2Constants.PROMPT);
String maxAge = request.getParameter(OrcidOauth2Constants.MAX_AGE);
String orcid = getEffectiveUserOrcid();
if (maxAge != null) {
// if maxAge+lastlogin > now, force login. max_age is in seconds.
// is also on the entity.
java.util.Date authTime = profileEntityManager.getLastLogin(orcid);
try {
long max = Long.parseLong(maxAge);
if (authTime == null || ((authTime.getTime() + (max * 1000)) < (new java.util.Date()).getTime())) {
return oauthLoginController.loginGetHandler(request, response, new ModelAndView());
}
} catch (NumberFormatException e) {
// ignore
}
}
if (prompt != null && prompt.equals(OrcidOauth2Constants.PROMPT_CONFIRM)) {
forceConfirm = true;
} else if (prompt != null && prompt.equals(OrcidOauth2Constants.PROMPT_LOGIN)) {
request.getParameterMap().remove(OrcidOauth2Constants.PROMPT);
return oauthLoginController.loginGetHandler(request, response, new ModelAndView());
}
}
// Check if the client has persistent tokens enabled
if (clientDetails.isPersistentTokensEnabled()) {
usePersistentTokens = true;
}
if (!forceConfirm && usePersistentTokens) {
boolean tokenLongLifeAlreadyExists = tokenServices.longLifeTokenExist(requestInfoForm.getClientId(), getEffectiveUserOrcid(), OAuth2Utils.parseParameterList(requestInfoForm.getScopesAsString()));
if (tokenLongLifeAlreadyExists) {
AuthorizationRequest authorizationRequest = (AuthorizationRequest) request.getSession().getAttribute("authorizationRequest");
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Map<String, String> requestParams = new HashMap<String, String>();
copyRequestParameters(request, requestParams);
Map<String, String> approvalParams = new HashMap<String, String>();
requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
requestParams.put(OrcidOauth2Constants.TOKEN_VERSION, OrcidOauth2Constants.PERSISTENT_TOKEN);
boolean hasPersistent = hasPersistenTokensEnabled(requestInfoForm.getClientId());
// Don't let non persistent clients persist
if (!hasPersistent && "true".equals(requestParams.get(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN))) {
requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "false");
}
// default to client default if not set
if (requestParams.get(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN) == null) {
if (hasPersistent)
requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "true");
else
requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "false");
}
// Session status
SimpleSessionStatus status = new SimpleSessionStatus();
authorizationRequest.setRequestParameters(requestParams);
// Authorization request model
Map<String, Object> model = new HashMap<String, Object>();
model.put("authorizationRequest", authorizationRequest);
// Approve using the spring authorization endpoint code.
// note this will also handle generting implicit tokens via getTokenGranter().grant("implicit",new ImplicitTokenRequest(tokenRequest, storedOAuth2Request));
RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
ModelAndView authCodeView = new ModelAndView();
authCodeView.setView(view);
return authCodeView;
}
}
if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()) && ScopePathType.getScopesFromSpaceSeparatedString(requestInfoForm.getScopesAsString()).contains(ScopePathType.OPENID)) {
String prompt = request.getParameter(OrcidOauth2Constants.PROMPT);
if (prompt != null && prompt.equals(OrcidOauth2Constants.PROMPT_NONE)) {
String redirectUriWithParams = requestInfoForm.getRedirectUrl();
redirectUriWithParams += "?error=interaction_required";
RedirectView rView = new RedirectView(redirectUriWithParams);
ModelAndView error = new ModelAndView();
error.setView(rView);
return error;
}
}
mav.addObject("hideUserVoiceScript", true);
mav.addObject("originalOauth2Process", true);
mav.setViewName("confirm-oauth-access");
return mav;
}
use of org.orcid.pojo.ajaxForm.RequestInfoForm in project ORCID-Source by ORCID.
the class OauthControllerBase method generateRequestInfoForm.
private RequestInfoForm generateRequestInfoForm(String clientId, String scopesString, String redirectUri, String responseType, String stateParam, String email, String orcid, String givenNames, String familyNames, String nonce, String maxAge) throws UnsupportedEncodingException {
RequestInfoForm infoForm = new RequestInfoForm();
// If the user is logged in
String loggedUserOrcid = getEffectiveUserOrcid();
if (!PojoUtil.isEmpty(loggedUserOrcid)) {
infoForm.setUserOrcid(loggedUserOrcid);
ProfileEntity profile = profileEntityCacheManager.retrieve(loggedUserOrcid);
String creditName = "";
RecordNameEntity recordName = profile.getRecordNameEntity();
if (recordName != null) {
if (!PojoUtil.isEmpty(profile.getRecordNameEntity().getCreditName())) {
creditName = profile.getRecordNameEntity().getCreditName();
} else {
creditName = PojoUtil.isEmpty(profile.getRecordNameEntity().getGivenNames()) ? "" : profile.getRecordNameEntity().getGivenNames();
creditName += PojoUtil.isEmpty(profile.getRecordNameEntity().getFamilyName()) ? "" : " " + profile.getRecordNameEntity().getFamilyName();
creditName = creditName.trim();
}
}
if (!PojoUtil.isEmpty(creditName)) {
infoForm.setUserName(URLDecoder.decode(creditName, "UTF-8").trim());
}
}
Set<ScopePathType> scopes = new HashSet<ScopePathType>();
if (!PojoUtil.isEmpty(clientId) && !PojoUtil.isEmpty(scopesString)) {
scopesString = URLDecoder.decode(scopesString, "UTF-8").trim();
scopesString = scopesString.replaceAll(" +", " ");
scopes = ScopePathType.getScopesFromSpaceSeparatedString(scopesString);
} else {
throw new InvalidRequestException("Unable to find parameters");
}
for (ScopePathType theScope : scopes) {
ScopeInfoForm scopeInfoForm = new ScopeInfoForm();
scopeInfoForm.setValue(theScope.value());
scopeInfoForm.setName(theScope.name());
try {
scopeInfoForm.setDescription(getMessage(ScopePathType.class.getName() + '.' + theScope.name()));
scopeInfoForm.setLongDescription(getMessage(ScopePathType.class.getName() + '.' + theScope.name() + ".longDesc"));
} catch (NoSuchMessageException e) {
LOGGER.warn("Unable to find key message for scope: " + theScope.name() + " " + theScope.value());
}
infoForm.getScopes().add(scopeInfoForm);
}
// Check if the client has persistent tokens enabled
ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
if (clientDetails.isPersistentTokensEnabled()) {
infoForm.setClientHavePersistentTokens(true);
}
// If client details is ok, continue
String clientName = clientDetails.getClientName() == null ? "" : clientDetails.getClientName();
String clientEmailRequestReason = clientDetails.getEmailAccessReason() == null ? "" : clientDetails.getEmailAccessReason();
String clientDescription = clientDetails.getClientDescription() == null ? "" : clientDetails.getClientDescription();
String memberName = "";
// If client type is null it means it is a public client
if (ClientType.PUBLIC_CLIENT.equals(clientDetails.getClientType())) {
memberName = PUBLIC_MEMBER_NAME;
} else if (!PojoUtil.isEmpty(clientDetails.getGroupProfileId())) {
ProfileEntity groupProfile = profileEntityCacheManager.retrieve(clientDetails.getGroupProfileId());
if (groupProfile.getRecordNameEntity() != null) {
memberName = groupProfile.getRecordNameEntity().getCreditName();
}
}
// name, since it should be a SSO user
if (StringUtils.isBlank(memberName)) {
memberName = clientName;
}
if (!PojoUtil.isEmpty(email) || !PojoUtil.isEmpty(orcid)) {
// Check if orcid exists, if so, show login screen
if (!PojoUtil.isEmpty(orcid)) {
orcid = orcid.trim();
if (orcidProfileManager.exists(orcid)) {
infoForm.setUserId(orcid);
}
} else {
// Check if email exists, if so, show login screen
if (!PojoUtil.isEmpty(email)) {
email = email.trim();
if (emailManager.emailExists(email)) {
infoForm.setUserId(email);
}
}
}
}
infoForm.setUserEmail(email);
if (PojoUtil.isEmpty(loggedUserOrcid))
infoForm.setUserOrcid(orcid);
infoForm.setUserGivenNames(givenNames);
infoForm.setUserFamilyNames(familyNames);
infoForm.setClientId(clientId);
infoForm.setClientDescription(clientDescription);
infoForm.setClientName(clientName);
infoForm.setClientEmailRequestReason(clientEmailRequestReason);
infoForm.setMemberName(memberName);
infoForm.setRedirectUrl(redirectUri);
infoForm.setStateParam(stateParam);
infoForm.setResponseType(responseType);
infoForm.setNonce(nonce);
return infoForm;
}
use of org.orcid.pojo.ajaxForm.RequestInfoForm in project ORCID-Source by ORCID.
the class OauthLoginController method loginGetHandler.
@RequestMapping(value = { "/oauth/signin", "/oauth/login" }, method = RequestMethod.GET)
public ModelAndView loginGetHandler(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) throws UnsupportedEncodingException {
String url = request.getQueryString();
// default to Reg
boolean showLogin = showLoginDefault;
// Get and save the request information form
RequestInfoForm requestInfoForm = generateRequestInfoForm(url);
request.getSession().setAttribute(REQUEST_INFO_FORM, requestInfoForm);
if (url.toLowerCase().contains("show_login=true"))
showLogin = true;
else if (url.toLowerCase().contains("show_login=false"))
showLogin = false;
// Check if userId is set so we should show the login screen
if (!PojoUtil.isEmpty(requestInfoForm.getUserId())) {
showLogin = true;
}
// Check that the client have the required permissions
// Get client name
ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(requestInfoForm.getClientId());
// validate client scopes
try {
authorizationEndpoint.validateScope(requestInfoForm.getScopesAsString(), clientDetails, requestInfoForm.getResponseType());
orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
} catch (InvalidScopeException | LockedException e) {
String redirectUriWithParams = requestInfoForm.getRedirectUrl();
if (e instanceof InvalidScopeException) {
redirectUriWithParams += "?error=invalid_scope&error_description=" + e.getMessage();
} else {
redirectUriWithParams += "?error=client_locked&error_description=" + e.getMessage();
}
RedirectView rView = new RedirectView(redirectUriWithParams);
ModelAndView error = new ModelAndView();
error.setView(rView);
return error;
}
// handle openID behaviour
if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()) && ScopePathType.getScopesFromSpaceSeparatedString(requestInfoForm.getScopesAsString()).contains(ScopePathType.OPENID)) {
String prompt = request.getParameter(OrcidOauth2Constants.PROMPT);
if (prompt != null && prompt.equals(OrcidOauth2Constants.PROMPT_NONE)) {
String redirectUriWithParams = requestInfoForm.getRedirectUrl();
redirectUriWithParams += "?error=login_required";
RedirectView rView = new RedirectView(redirectUriWithParams);
ModelAndView error = new ModelAndView();
error.setView(rView);
return error;
}
}
mav.addObject("hideUserVoiceScript", true);
mav.addObject("showLogin", String.valueOf(showLogin));
mav.addObject("originalOauth2Process", true);
mav.setViewName("oauth_login");
return mav;
}
Aggregations