use of org.orcid.core.security.aop.LockedException in project ORCID-Source by ORCID.
the class OrcidInfo method publicPreview.
@RequestMapping(value = { "/{orcid:(?:\\d{4}-){3,}\\d{3}[\\dX]}", "/{orcid:(?:\\d{4}-){3,}\\d{3}[\\dX]}/print" })
public ModelAndView publicPreview(HttpServletRequest request, @RequestParam(value = "page", defaultValue = "1") int pageNo, @RequestParam(value = "v", defaultValue = "0") int v, @RequestParam(value = "maxResults", defaultValue = "15") int maxResults, @PathVariable("orcid") String orcid) {
ProfileEntity profile = null;
try {
profile = profileEntityCacheManager.retrieve(orcid);
} catch (Exception e) {
return new ModelAndView("error-404");
}
try {
// Check if the profile is deprecated, non claimed or locked
orcidSecurityManager.checkProfile(orcid);
} catch (OrcidDeprecatedException | OrcidNotClaimedException | LockedException e) {
ModelAndView mav = new ModelAndView("public_profile_unavailable");
mav.addObject("effectiveUserOrcid", orcid);
String displayName = "";
if (e instanceof OrcidDeprecatedException) {
PersonalDetails publicPersonalDetails = personalDetailsManager.getPublicPersonalDetails(orcid);
if (publicPersonalDetails.getName() != null) {
Name name = publicPersonalDetails.getName();
if (name.getVisibility().equals(org.orcid.jaxb.model.common_v2.Visibility.PUBLIC)) {
if (name.getCreditName() != null && !PojoUtil.isEmpty(name.getCreditName().getContent())) {
displayName = name.getCreditName().getContent();
} else {
if (name.getGivenNames() != null && !PojoUtil.isEmpty(name.getGivenNames().getContent())) {
displayName = name.getGivenNames().getContent() + " ";
}
if (name.getFamilyName() != null && !PojoUtil.isEmpty(name.getFamilyName().getContent())) {
displayName += name.getFamilyName().getContent();
}
}
}
}
mav.addObject("deprecated", true);
mav.addObject("primaryRecord", profile.getPrimaryRecord().getId());
} else if (e instanceof OrcidNotClaimedException) {
displayName = localeManager.resolveMessage("orcid.reserved_for_claim");
} else {
mav.addObject("locked", true);
mav.addObject("isPublicProfile", true);
displayName = localeManager.resolveMessage("public_profile.deactivated.given_names") + " " + localeManager.resolveMessage("public_profile.deactivated.family_name");
}
if (!PojoUtil.isEmpty(displayName)) {
mav.addObject("title", getMessage("layout.public-layout.title", displayName, orcid));
mav.addObject("displayName", displayName);
}
return mav;
}
long lastModifiedTime = getLastModifiedTime(orcid);
ModelAndView mav = null;
if (request.getRequestURI().contains("/print")) {
mav = new ModelAndView("print_public_record");
mav.addObject("hideUserVoiceScript", true);
} else {
mav = new ModelAndView("public_profile_v3");
}
mav.addObject("isPublicProfile", true);
mav.addObject("effectiveUserOrcid", orcid);
mav.addObject("lastModifiedTime", lastModifiedTime);
boolean isProfileEmtpy = true;
HttpSession session = request.getSession(false);
if (session != null) {
session.removeAttribute(PUBLIC_WORKS_RESULTS_ATTRIBUTE);
}
PersonalDetails publicPersonalDetails = personalDetailsManager.getPublicPersonalDetails(orcid);
// Fill personal details
if (publicPersonalDetails != null) {
// Get display name
String displayName = "";
if (publicPersonalDetails.getName() != null) {
Name name = publicPersonalDetails.getName();
if (name.getVisibility().equals(org.orcid.jaxb.model.common_v2.Visibility.PUBLIC)) {
if (name.getCreditName() != null && !PojoUtil.isEmpty(name.getCreditName().getContent())) {
displayName = name.getCreditName().getContent();
} else {
if (name.getGivenNames() != null && !PojoUtil.isEmpty(name.getGivenNames().getContent())) {
displayName = name.getGivenNames().getContent() + " ";
}
if (name.getFamilyName() != null && !PojoUtil.isEmpty(name.getFamilyName().getContent())) {
displayName += name.getFamilyName().getContent();
}
}
}
}
if (!PojoUtil.isEmpty(displayName)) {
// <Published Name> (<ORCID iD>) - ORCID | Connecting Research
// and Researchers
mav.addObject("title", getMessage("layout.public-layout.title", displayName.trim(), orcid));
mav.addObject("displayName", displayName);
}
// Get biography
if (publicPersonalDetails.getBiography() != null) {
Biography bio = publicPersonalDetails.getBiography();
if (org.orcid.jaxb.model.common_v2.Visibility.PUBLIC.equals(bio.getVisibility()) && !PojoUtil.isEmpty(bio.getContent())) {
isProfileEmtpy = false;
mav.addObject("biography", bio);
}
}
// Fill other names
OtherNames publicOtherNames = publicPersonalDetails.getOtherNames();
if (publicOtherNames != null && publicOtherNames.getOtherNames() != null) {
Iterator<OtherName> it = publicOtherNames.getOtherNames().iterator();
while (it.hasNext()) {
OtherName otherName = it.next();
if (!org.orcid.jaxb.model.common_v2.Visibility.PUBLIC.equals(otherName.getVisibility())) {
it.remove();
}
}
}
Map<String, List<OtherName>> groupedOtherNames = groupOtherNames(publicOtherNames);
mav.addObject("publicGroupedOtherNames", groupedOtherNames);
}
// Fill biography elements
// Fill country
Addresses publicAddresses = addressManager.getPublicAddresses(orcid, lastModifiedTime);
Map<String, String> countryNames = new HashMap<String, String>();
if (publicAddresses != null && publicAddresses.getAddress() != null) {
Address publicAddress = null;
// The primary address will be the one with the lowest display index
for (Address address : publicAddresses.getAddress()) {
countryNames.put(address.getCountry().getValue().value(), getcountryName(address.getCountry().getValue().value()));
if (publicAddress == null) {
publicAddress = address;
}
}
if (publicAddress != null) {
mav.addObject("publicAddress", publicAddress);
mav.addObject("countryNames", countryNames);
Map<String, List<Address>> groupedAddresses = groupAddresses(publicAddresses);
mav.addObject("publicGroupedAddresses", groupedAddresses);
}
}
// Fill keywords
Keywords publicKeywords = keywordManager.getPublicKeywords(orcid, lastModifiedTime);
Map<String, List<Keyword>> groupedKeywords = groupKeywords(publicKeywords);
mav.addObject("publicGroupedKeywords", groupedKeywords);
// Fill researcher urls
ResearcherUrls publicResearcherUrls = researcherUrlManager.getPublicResearcherUrls(orcid, lastModifiedTime);
Map<String, List<ResearcherUrl>> groupedResearcherUrls = groupResearcherUrls(publicResearcherUrls);
mav.addObject("publicGroupedResearcherUrls", groupedResearcherUrls);
// Fill emails
Emails publicEmails = emailManager.getPublicEmails(orcid, lastModifiedTime);
Map<String, List<Email>> groupedEmails = groupEmails(publicEmails);
mav.addObject("publicGroupedEmails", groupedEmails);
// Fill external identifiers
PersonExternalIdentifiers publicPersonExternalIdentifiers = externalIdentifierManager.getPublicExternalIdentifiers(orcid, lastModifiedTime);
Map<String, List<PersonExternalIdentifier>> groupedExternalIdentifiers = groupExternalIdentifiers(publicPersonExternalIdentifiers);
mav.addObject("publicGroupedPersonExternalIdentifiers", groupedExternalIdentifiers);
LinkedHashMap<Long, WorkForm> minimizedWorksMap = new LinkedHashMap<>();
LinkedHashMap<Long, Affiliation> affiliationMap = new LinkedHashMap<>();
LinkedHashMap<Long, Funding> fundingMap = new LinkedHashMap<>();
LinkedHashMap<Long, PeerReview> peerReviewMap = new LinkedHashMap<>();
minimizedWorksMap = activityCacheManager.pubMinWorksMap(orcid, lastModifiedTime);
if (minimizedWorksMap.size() > 0) {
isProfileEmtpy = false;
} else {
mav.addObject("worksEmpty", true);
}
affiliationMap = affiliationMap(orcid, lastModifiedTime);
if (affiliationMap.size() > 0) {
isProfileEmtpy = false;
} else {
mav.addObject("affiliationsEmpty", true);
}
fundingMap = fundingMap(orcid, lastModifiedTime);
if (fundingMap.size() > 0)
isProfileEmtpy = false;
else {
mav.addObject("fundingEmpty", true);
}
peerReviewMap = peerReviewMap(orcid, lastModifiedTime);
if (peerReviewMap.size() > 0) {
isProfileEmtpy = false;
} else {
mav.addObject("peerReviewsEmpty", true);
}
ObjectMapper mapper = new ObjectMapper();
try {
String worksIdsJson = mapper.writeValueAsString(minimizedWorksMap.keySet());
String affiliationIdsJson = mapper.writeValueAsString(affiliationMap.keySet());
String fundingIdsJson = mapper.writeValueAsString(fundingMap.keySet());
String peerReviewIdsJson = mapper.writeValueAsString(peerReviewMap.keySet());
mav.addObject("workIdsJson", StringEscapeUtils.escapeEcmaScript(worksIdsJson));
mav.addObject("affiliationIdsJson", StringEscapeUtils.escapeEcmaScript(affiliationIdsJson));
mav.addObject("fundingIdsJson", StringEscapeUtils.escapeEcmaScript(fundingIdsJson));
mav.addObject("peerReviewIdsJson", StringEscapeUtils.escapeEcmaScript(peerReviewIdsJson));
mav.addObject("isProfileEmpty", isProfileEmtpy);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (!profile.isReviewed()) {
if (isProfileValidForIndex(profile)) {
int countTokens = orcidOauth2TokenService.findCountByUserName(orcid, lastModifiedTime);
if (!profile.isAccountNonLocked() || countTokens == 0 || (!CreationMethod.WEBSITE.value().equals(profile.getCreationMethod()) && !CreationMethod.DIRECT.value().equals(profile.getCreationMethod()))) {
mav.addObject("noIndex", true);
}
} else {
mav.addObject("noIndex", true);
}
}
return mav;
}
use of org.orcid.core.security.aop.LockedException in project ORCID-Source by ORCID.
the class OAuthErrorUtilsTest method testGetOAuthErrorForLockedException.
@Test
public void testGetOAuthErrorForLockedException() {
OAuthError error = OAuthErrorUtils.getOAuthError(new LockedException("message here"));
assertEquals(OAuthError.UNAUTHORIZED_CLIENT, error.getError());
assertEquals(Status.BAD_REQUEST, error.getResponseStatus());
assertEquals("message here", error.getErrorDescription());
}
use of org.orcid.core.security.aop.LockedException in project ORCID-Source by ORCID.
the class T2OrcidApiServiceVersionedDelegatorImpl method checkRecordStatus.
/**
* Checks if an account is deprecated
*
* @param orcidMessage
* OrcidMessage, for it we can get the orcid to check for
* deprecation
* @throws DeprecatedException
* if the account is deprecated
*/
public void checkRecordStatus(String orcid) {
ProfileEntity entity = profileEntityCacheManager.retrieve(orcid);
if (entity != null) {
if (entity.getPrimaryRecord() != null) {
Map<String, String> params = new HashMap<String, String>();
StringBuffer primary = new StringBuffer(orcidUrlManager.getBaseUrl()).append("/").append(entity.getPrimaryRecord().getId());
params.put(OrcidDeprecatedException.ORCID, primary.toString());
if (entity.getDeprecatedDate() != null) {
XMLGregorianCalendar calendar = DateUtils.convertToXMLGregorianCalendar(entity.getDeprecatedDate());
params.put(OrcidDeprecatedException.DEPRECATED_DATE, calendar.toString());
}
throw new OrcidDeprecatedException(params);
} else if (entity.getDeactivationDate() != null) {
DeactivatedException exception = new DeactivatedException(localeManager.resolveMessage("apiError.9044.developerMessage"));
exception.setOrcid(orcid);
throw exception;
} else if (!entity.isAccountNonLocked()) {
LockedException lockedException = new LockedException(localeManager.resolveMessage("apiError.9018.developerMessage"));
lockedException.setOrcid(orcid);
throw lockedException;
} else {
// Check if the user record is not claimed and not old enough
if ((entity.getClaimed() == null || Boolean.FALSE.equals(entity.getClaimed())) && !isOldEnough(entity)) {
// Let the creator access the profile even if it is not claimed and
// not old enough
SourceEntity currentSourceEntity = sourceManager.retrieveSourceEntity();
String profileSource = entity.getSource() == null ? null : entity.getSource().getSourceId();
String currentSource = currentSourceEntity == null ? null : currentSourceEntity.getSourceId();
// the profile source, throw an exception
if (profileSource == null || !Objects.equals(profileSource, currentSource)) {
throw new OrcidNotClaimedException(localeManager.resolveMessage("apiError.9036.developerMessage"));
}
}
}
}
}
use of org.orcid.core.security.aop.LockedException 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.core.security.aop.LockedException 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;
}
Aggregations