Search in sources :

Example 6 with RequestInfoForm

use of org.orcid.pojo.ajaxForm.RequestInfoForm in project ORCID-Source by ORCID.

the class OauthLoginController method authenticateAndAuthorize.

@RequestMapping(value = { "/oauth/custom/signin.json", "/oauth/custom/login.json" }, method = RequestMethod.POST)
@ResponseBody
public OauthAuthorizeForm authenticateAndAuthorize(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthAuthorizeForm form) {
    // Clean form errors
    form.setErrors(new ArrayList<String>());
    RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute(REQUEST_INFO_FORM);
    boolean willBeRedirected = false;
    if (form.getApproved()) {
        // Validate name and password
        validateUserNameAndPassword(form);
        if (form.getErrors().isEmpty()) {
            try {
                // Authenticate user
                copy2FAFields(form, request);
                Authentication auth = authenticateUser(request, form.getUserName().getValue(), form.getPassword().getValue());
                profileEntityManager.updateLastLoginDetails(auth.getName(), OrcidRequestUtil.getIpAddress(request));
                // Create authorization params
                SimpleSessionStatus status = new SimpleSessionStatus();
                Map<String, Object> model = new HashMap<String, Object>();
                Map<String, String> params = new HashMap<String, String>();
                Map<String, String> approvalParams = new HashMap<String, String>();
                fillOauthParams(requestInfoForm, params, approvalParams, form.getPersistentTokenEnabled(), form.isEmailAccessAllowed());
                // Authorize
                try {
                    authorizationEndpoint.authorize(model, params, status, auth);
                } catch (RedirectMismatchException rUriError) {
                    String redirectUri = this.getBaseUri() + REDIRECT_URI_ERROR;
                    // Set the client id
                    redirectUri = redirectUri.replace("{0}", requestInfoForm.getClientId());
                    // Set the response type if needed
                    if (!PojoUtil.isEmpty(requestInfoForm.getResponseType()))
                        redirectUri += "&response_type=" + requestInfoForm.getResponseType();
                    // Set the redirect uri
                    if (!PojoUtil.isEmpty(requestInfoForm.getRedirectUrl()))
                        redirectUri += "&redirect_uri=" + requestInfoForm.getRedirectUrl();
                    // Set the scope param
                    if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()))
                        redirectUri += "&scope=" + requestInfoForm.getScopesAsString();
                    // Copy the state param if present
                    if (!PojoUtil.isEmpty(requestInfoForm.getStateParam()))
                        redirectUri += "&state=" + requestInfoForm.getStateParam();
                    form.setRedirectUrl(redirectUri);
                    LOGGER.info("OauthLoginController being sent to client browser: " + form.getRedirectUrl());
                    return form;
                }
                // Approve
                RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
                form.setRedirectUrl(view.getUrl());
                willBeRedirected = true;
            } catch (AuthenticationException ae) {
                if (ae.getCause() instanceof DisabledException) {
                    // Handle this message in angular to allow AJAX action
                    form.getErrors().add("orcid.frontend.security.orcid_deactivated");
                } else if (ae.getCause() instanceof UnclaimedProfileExistsException) {
                    String email = PojoUtil.isEmpty(form.getUserName()) ? null : form.getUserName().getValue();
                    String resendEmailUrl = createResendClaimUrl(email, request);
                    String errorMessage = getMessage("orcid.frontend.security.unclaimed_exists_1");
                    errorMessage += "<a href=\"" + resendEmailUrl + "\">";
                    errorMessage += getMessage("orcid.frontend.security.unclaimed_exists_2");
                    errorMessage += "</a>" + getMessage("orcid.frontend.security.unclaimed_exists_3");
                    form.getErrors().add(errorMessage);
                } else if (ae instanceof VerificationCodeFor2FARequiredException) {
                    form.setVerificationCodeRequired(true);
                } else if (ae instanceof Bad2FAVerificationCodeException) {
                    form.getErrors().add(getMessage("orcid.frontend.security.2fa.bad_verification_code"));
                } else if (ae instanceof Bad2FARecoveryCodeException) {
                    form.getErrors().add(getMessage("orcid.frontend.security.2fa.bad_recovery_code"));
                } else {
                    form.getErrors().add(getMessage("orcid.frontend.security.bad_credentials"));
                }
            }
        }
    } else {
        form.setRedirectUrl(buildDenyRedirectUri(requestInfoForm.getRedirectUrl(), requestInfoForm.getStateParam()));
        willBeRedirected = true;
    }
    // not be redirected yet
    if (willBeRedirected) {
        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 form;
}
Also used : HashMap(java.util.HashMap) AuthenticationException(org.springframework.security.core.AuthenticationException) DisabledException(org.springframework.security.authentication.DisabledException) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) Bad2FAVerificationCodeException(org.orcid.frontend.web.exception.Bad2FAVerificationCodeException) UnclaimedProfileExistsException(org.orcid.core.security.UnclaimedProfileExistsException) VerificationCodeFor2FARequiredException(org.orcid.frontend.web.exception.VerificationCodeFor2FARequiredException) Bad2FARecoveryCodeException(org.orcid.frontend.web.exception.Bad2FARecoveryCodeException) Authentication(org.springframework.security.core.Authentication) RedirectMismatchException(org.springframework.security.oauth2.common.exceptions.RedirectMismatchException) RedirectView(org.springframework.web.servlet.view.RedirectView) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) SimpleSessionStatus(org.springframework.web.bind.support.SimpleSessionStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 7 with RequestInfoForm

use of org.orcid.pojo.ajaxForm.RequestInfoForm in project ORCID-Source by ORCID.

the class OauthRegistrationController method checkRegisterForm.

@RequestMapping(value = "/oauth/custom/register.json", method = RequestMethod.POST)
@ResponseBody
public OauthRegistrationForm checkRegisterForm(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthRegistrationForm form) {
    form.setErrors(new ArrayList<String>());
    RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute(REQUEST_INFO_FORM);
    if (form.getApproved()) {
        registrationController.validateRegistrationFields(request, form);
        registrationController.validateGrcaptcha(request, form);
    } else {
        SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
        String stateParam = null;
        if (savedRequest != null && savedRequest.getParameterMap() != null && savedRequest.getParameterValues("state") != null) {
            if (savedRequest.getParameterValues("state").length > 0)
                stateParam = savedRequest.getParameterValues("state")[0];
        }
        form.setRedirectUrl(buildDenyRedirectUri(requestInfoForm.getRedirectUrl(), stateParam));
    }
    return form;
}
Also used : HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 8 with RequestInfoForm

use of org.orcid.pojo.ajaxForm.RequestInfoForm in project ORCID-Source by ORCID.

the class OauthGenericCallsController method getEmptyAuthorizeForm.

@RequestMapping(value = "/oauth/custom/authorize/empty.json", method = RequestMethod.GET)
@ResponseBody
public OauthAuthorizeForm getEmptyAuthorizeForm(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
    OauthAuthorizeForm empty = new OauthAuthorizeForm();
    Text emptyText = Text.valueOf(StringUtils.EMPTY);
    empty.setPassword(emptyText);
    empty.setUserName(emptyText);
    RequestInfoForm requestInfoForm = getRequestInfoForm(request);
    if (requestInfoForm != null) {
        if (!PojoUtil.isEmpty(requestInfoForm.getUserId())) {
            empty.setUserName(Text.valueOf(requestInfoForm.getUserId()));
        }
    }
    return empty;
}
Also used : OauthAuthorizeForm(org.orcid.pojo.ajaxForm.OauthAuthorizeForm) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) Text(org.orcid.pojo.ajaxForm.Text) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 9 with RequestInfoForm

use of org.orcid.pojo.ajaxForm.RequestInfoForm in project ORCID-Source by ORCID.

the class OauthRegistrationControllerTest method testStripHtmlFromNames.

@SuppressWarnings("unchecked")
@Test
public void testStripHtmlFromNames() throws UnsupportedEncodingException {
    HttpSession session = mock(HttpSession.class);
    RequestInfoForm rf = new RequestInfoForm();
    RedirectView mv = new RedirectView();
    when(servletRequest.getSession()).thenReturn(session);
    when(servletRequest.getSession().getAttribute("requestInfoForm")).thenReturn(rf);
    when(authorizationEndpoint.approveOrDeny(Matchers.anyMap(), Matchers.anyMap(), Matchers.any(SessionStatus.class), Matchers.any(Principal.class))).thenReturn(mv);
    when(authenticationManager.authenticate(Matchers.any(Authentication.class))).thenAnswer(new Answer<Authentication>() {

        @Override
        public Authentication answer(InvocationOnMock invocation) throws Throwable {
            OrcidOAuth2Authentication mockedAuthentication = mock(OrcidOAuth2Authentication.class);
            return mockedAuthentication;
        }
    });
    Text email = Text.valueOf(System.currentTimeMillis() + "@test.orcid.org");
    OauthRegistrationForm reg = new OauthRegistrationForm();
    org.orcid.pojo.ajaxForm.Visibility fv = new org.orcid.pojo.ajaxForm.Visibility();
    fv.setVisibility(org.orcid.jaxb.model.v3.dev1.common.Visibility.PUBLIC);
    reg.setActivitiesVisibilityDefault(fv);
    reg.setEmail(email);
    reg.setEmailConfirm(email);
    reg.setFamilyNames(Text.valueOf("<button onclick=\"alert('hello')\">Family Name</button>"));
    reg.setGivenNames(Text.valueOf("<button onclick=\"alert('hello')\">Given Names</button>"));
    reg.setPassword(Text.valueOf("1234abcd"));
    reg.setPasswordConfirm(Text.valueOf("1234abcd"));
    reg.setValNumClient(2L);
    reg.setValNumServer(4L);
    reg.setApproved(true);
    Checkbox c = new Checkbox();
    c.setValue(true);
    reg.setTermsOfUse(c);
    reg.setCreationType(Text.valueOf(CreationMethod.DIRECT.value()));
    reg.setPersistentTokenEnabled(true);
    oauthRegistrationController.registerAndAuthorize(servletRequest, servletResponse, reg);
    ArgumentCaptor<HttpServletRequest> argument1 = ArgumentCaptor.forClass(HttpServletRequest.class);
    ArgumentCaptor<Registration> argument2 = ArgumentCaptor.forClass(Registration.class);
    ArgumentCaptor<Boolean> argument3 = ArgumentCaptor.forClass(Boolean.class);
    ArgumentCaptor<Locale> argument4 = ArgumentCaptor.forClass(Locale.class);
    ArgumentCaptor<String> argument5 = ArgumentCaptor.forClass(String.class);
    verify(registrationController).createMinimalRegistration(argument1.capture(), argument2.capture(), argument3.capture(), argument4.capture(), argument5.capture());
    assertNotNull(argument2.getValue());
    Registration registration = argument2.getValue();
    assertEquals(email.getValue(), registration.getEmail().getValue());
    assertEquals("Given Names", registration.getGivenNames().getValue());
    assertEquals("Family Name", registration.getFamilyNames().getValue());
}
Also used : Locale(java.util.Locale) HttpServletRequest(javax.servlet.http.HttpServletRequest) OauthRegistrationForm(org.orcid.pojo.ajaxForm.OauthRegistrationForm) Checkbox(org.orcid.pojo.ajaxForm.Checkbox) Registration(org.orcid.pojo.ajaxForm.Registration) SessionStatus(org.springframework.web.bind.support.SessionStatus) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) HttpSession(javax.servlet.http.HttpSession) Text(org.orcid.pojo.ajaxForm.Text) OrcidOAuth2Authentication(org.orcid.core.oauth.OrcidOAuth2Authentication) OrcidOAuth2Authentication(org.orcid.core.oauth.OrcidOAuth2Authentication) Authentication(org.springframework.security.core.Authentication) InvocationOnMock(org.mockito.invocation.InvocationOnMock) RedirectView(org.springframework.web.servlet.view.RedirectView) Principal(java.security.Principal) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test)

Example 10 with RequestInfoForm

use of org.orcid.pojo.ajaxForm.RequestInfoForm in project ORCID-Source by ORCID.

the class OauthRegistrationController method registerAndAuthorize.

@RequestMapping(value = "/oauth/custom/registerConfirm.json", method = RequestMethod.POST)
@ResponseBody
public RequestInfoForm registerAndAuthorize(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthRegistrationForm form) {
    RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute(REQUEST_INFO_FORM);
    if (form.getApproved()) {
        boolean usedCaptcha = false;
        // block google.
        if (form.getGrecaptchaWidgetId().getValue() != null) {
            // to the login page
            if (request.getSession().getAttribute(RegistrationController.GRECAPTCHA_SESSION_ATTRIBUTE_NAME) == null || PojoUtil.isEmpty(form.getGrecaptcha()) || !form.getGrecaptcha().getValue().equals(request.getSession().getAttribute(RegistrationController.GRECAPTCHA_SESSION_ATTRIBUTE_NAME))) {
                String redirectUri = this.getBaseUri() + REDIRECT_URI_ERROR;
                // Set the client id
                redirectUri = redirectUri.replace("{0}", requestInfoForm.getClientId());
                // Set the response type if needed
                if (!PojoUtil.isEmpty(requestInfoForm.getResponseType()))
                    redirectUri += "&response_type=" + requestInfoForm.getResponseType();
                // Set the redirect uri
                if (!PojoUtil.isEmpty(requestInfoForm.getRedirectUrl()))
                    redirectUri += "&redirect_uri=" + requestInfoForm.getRedirectUrl();
                // remove email access scope if present but not granted
                if (requestInfoForm.containsEmailReadPrivateScope() && !form.isEmailAccessAllowed()) {
                    requestInfoForm.removeEmailReadPrivateScope();
                }
                // Set the scope param
                if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()))
                    redirectUri += "&scope=" + requestInfoForm.getScopesAsString();
                // Copy the state param if present
                if (!PojoUtil.isEmpty(requestInfoForm.getStateParam()))
                    redirectUri += "&state=" + requestInfoForm.getStateParam();
                requestInfoForm.setRedirectUrl(redirectUri);
                SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
                if (savedRequest != null)
                    LOGGER.info("OauthConfirmAccessController original request: " + savedRequest.getRedirectUrl());
                LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: " + requestInfoForm.getRedirectUrl());
                return requestInfoForm;
            }
            usedCaptcha = true;
        }
        // Remove the session hash if needed
        if (request.getSession().getAttribute(RegistrationController.GRECAPTCHA_SESSION_ATTRIBUTE_NAME) != null) {
            request.getSession().removeAttribute(RegistrationController.GRECAPTCHA_SESSION_ATTRIBUTE_NAME);
        }
        // Strip any html code from names before validating them
        if (!PojoUtil.isEmpty(form.getFamilyNames())) {
            form.getFamilyNames().setValue(OrcidStringUtils.stripHtml(form.getFamilyNames().getValue()));
        }
        if (!PojoUtil.isEmpty(form.getGivenNames())) {
            form.getGivenNames().setValue(OrcidStringUtils.stripHtml(form.getGivenNames().getValue()));
        }
        // Check there are no errors
        registrationController.validateRegistrationFields(request, form);
        if (form.getErrors().isEmpty()) {
            // Register user
            try {
                // Locale
                Locale locale = RequestContextUtils.getLocale(request);
                // Ip
                String ip = OrcidRequestUtil.getIpAddress(request);
                registrationController.createMinimalRegistration(request, form, usedCaptcha, locale, ip);
            } catch (Exception e) {
                requestInfoForm.getErrors().add(getMessage("register.error.generalError"));
                return requestInfoForm;
            }
            // Authenticate user
            String email = form.getEmail().getValue();
            String password = form.getPassword().getValue();
            Authentication auth = authenticateUser(request, email, password);
            // Create authorization params
            SimpleSessionStatus status = new SimpleSessionStatus();
            Map<String, Object> model = new HashMap<String, Object>();
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String> approvalParams = new HashMap<String, String>();
            fillOauthParams(requestInfoForm, params, approvalParams, form.getPersistentTokenEnabled(), form.isEmailAccessAllowed());
            // Authorize
            try {
                authorizationEndpoint.authorize(model, params, status, auth);
            } catch (RedirectMismatchException rUriError) {
                String redirectUri = this.getBaseUri() + REDIRECT_URI_ERROR;
                // Set the client id
                redirectUri = redirectUri.replace("{0}", requestInfoForm.getClientId());
                // Set the response type if needed
                if (!PojoUtil.isEmpty(requestInfoForm.getResponseType()))
                    redirectUri += "&response_type=" + requestInfoForm.getResponseType();
                // Set the redirect uri
                if (!PojoUtil.isEmpty(requestInfoForm.getRedirectUrl()))
                    redirectUri += "&redirect_uri=" + requestInfoForm.getRedirectUrl();
                // Set the scope param
                if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()))
                    redirectUri += "&scope=" + requestInfoForm.getScopesAsString();
                // Copy the state param if present
                if (!PojoUtil.isEmpty(requestInfoForm.getStateParam()))
                    redirectUri += "&state=" + requestInfoForm.getStateParam();
                requestInfoForm.setRedirectUrl(redirectUri);
                LOGGER.info("OauthRegisterController being sent to client browser: " + requestInfoForm.getRedirectUrl());
                return requestInfoForm;
            }
            Boolean isOauth2ScreensRequest = (Boolean) request.getSession().getAttribute(OrcidOauth2Constants.OAUTH_2SCREENS);
            if (isOauth2ScreensRequest != null && isOauth2ScreensRequest) {
                // Just redirect to the authorization screen
                String queryString = (String) request.getSession().getAttribute(OrcidOauth2Constants.OAUTH_QUERY_STRING);
                requestInfoForm.setRedirectUrl(orcidUrlManager.getBaseUrl() + "/oauth/authorize?" + queryString);
                request.getSession().removeAttribute(OrcidOauth2Constants.OAUTH_2SCREENS);
            } else {
                // Approve
                RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
                requestInfoForm.setRedirectUrl(view.getUrl());
            }
        }
    } else {
        requestInfoForm.setRedirectUrl(buildDenyRedirectUri(requestInfoForm.getRedirectUrl(), requestInfoForm.getStateParam()));
    }
    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;
}
Also used : Locale(java.util.Locale) HashMap(java.util.HashMap) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) RedirectMismatchException(org.springframework.security.oauth2.common.exceptions.RedirectMismatchException) Authentication(org.springframework.security.core.Authentication) RedirectMismatchException(org.springframework.security.oauth2.common.exceptions.RedirectMismatchException) RedirectView(org.springframework.web.servlet.view.RedirectView) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) SimpleSessionStatus(org.springframework.web.bind.support.SimpleSessionStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

RequestInfoForm (org.orcid.pojo.ajaxForm.RequestInfoForm)11 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)8 RedirectView (org.springframework.web.servlet.view.RedirectView)7 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)6 Authentication (org.springframework.security.core.Authentication)5 HashMap (java.util.HashMap)4 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)4 HttpSessionRequestCache (org.springframework.security.web.savedrequest.HttpSessionRequestCache)4 SimpleSessionStatus (org.springframework.web.bind.support.SimpleSessionStatus)4 LockedException (org.orcid.core.security.aop.LockedException)3 InvalidScopeException (org.springframework.security.oauth2.common.exceptions.InvalidScopeException)3 ModelAndView (org.springframework.web.servlet.ModelAndView)3 Locale (java.util.Locale)2 Registration (org.orcid.pojo.ajaxForm.Registration)2 Text (org.orcid.pojo.ajaxForm.Text)2 RedirectMismatchException (org.springframework.security.oauth2.common.exceptions.RedirectMismatchException)2 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)2 SavedRequest (org.springframework.security.web.savedrequest.SavedRequest)2 Principal (java.security.Principal)1 HashSet (java.util.HashSet)1