Example usage for org.springframework.web.bind.support SimpleSessionStatus SimpleSessionStatus

List of usage examples for org.springframework.web.bind.support SimpleSessionStatus SimpleSessionStatus

Introduction

In this page you can find the example usage for org.springframework.web.bind.support SimpleSessionStatus SimpleSessionStatus.

Prototype

SimpleSessionStatus

Source Link

Usage

From source file:org.orcid.frontend.web.controllers.OauthConfirmAccessController.java

@RequestMapping(value = "/confirm_access", method = RequestMethod.GET)
public ModelAndView loginGetHandler(HttpServletRequest request, HttpServletResponse response, ModelAndView mav,
        @RequestParam("client_id") String clientId, @RequestParam("scope") String scope,
        @RequestParam("redirect_uri") String redirectUri) {
    OrcidProfile profile = orcidProfileManager.retrieveOrcidProfile(getCurrentUserOrcid(),
            LoadOptions.BIO_ONLY);//from w  ww.j  a v  a2 s.  c  o m
    clientId = (clientId != null) ? clientId.trim() : clientId;
    scope = (scope != null) ? scope.trim().replaceAll(" +", " ") : scope;
    redirectUri = (redirectUri != null) ? redirectUri.trim() : redirectUri;

    Boolean justRegistered = (Boolean) request.getSession().getAttribute(OrcidOauth2Constants.JUST_REGISTERED);
    if (justRegistered != null) {
        request.getSession().removeAttribute(OrcidOauth2Constants.JUST_REGISTERED);
        mav.addObject(OrcidOauth2Constants.JUST_REGISTERED, justRegistered);
    }
    String clientName = "";
    String clientDescription = "";
    String clientGroupName = "";
    String clientWebsite = "";

    boolean usePersistentTokens = false;

    ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
    clientName = clientDetails.getClientName() == null ? "" : clientDetails.getClientName();
    clientDescription = clientDetails.getClientDescription() == null ? ""
            : clientDetails.getClientDescription();
    clientWebsite = clientDetails.getClientWebsite() == null ? "" : clientDetails.getClientWebsite();

    // validate client scopes
    try {
        authorizationEndpoint.validateScope(scope, clientDetails);
        orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
    } catch (InvalidScopeException ise) {
        String redirectUriWithParams = redirectUri;
        redirectUriWithParams += "?error=invalid_scope&error_description=" + ise.getMessage();
        RedirectView rView = new RedirectView(redirectUriWithParams);

        ModelAndView error = new ModelAndView();
        error.setView(rView);
        return error;
    } catch (LockedException le) {
        String redirectUriWithParams = redirectUri;
        redirectUriWithParams += "?error=client_locked&error_description=" + le.getMessage();
        RedirectView rView = new RedirectView(redirectUriWithParams);

        ModelAndView error = new ModelAndView();
        error.setView(rView);
        return error;
    }

    // Check if the client has persistent tokens enabled
    if (clientDetails.isPersistentTokensEnabled()) {
        usePersistentTokens = true;
    }

    if (usePersistentTokens) {
        boolean tokenAlreadyExists = tokenServices.tokenAlreadyExists(clientId, getEffectiveUserOrcid(),
                OAuth2Utils.parseParameterList(scope));
        if (tokenAlreadyExists) {
            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);

            // Check if the client have persistent tokens enabled
            requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "false");
            if (hasPersistenTokensEnabled(clientId)) {
                // Then check if the client granted the persistent token
                requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "true");
            }

            // 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);
            ModelAndView authCodeView = new ModelAndView();
            authCodeView.setView(view);
            return authCodeView;
        }
    }
    if (clientDetails.getClientType() == null) {
        clientGroupName = PUBLIC_MEMBER_NAME;
    } else if (!PojoUtil.isEmpty(clientDetails.getGroupProfileId())) {
        ProfileEntity groupProfile = profileEntityCacheManager.retrieve(clientDetails.getGroupProfileId());
        clientGroupName = groupProfile.getCreditName();
    }

    // If the group name is empty, use the same as the client name, since it
    // should be a SSO user
    if (StringUtils.isBlank(clientGroupName)) {
        clientGroupName = clientName;
    }
    mav.addObject("profile", profile);
    mav.addObject("client_name", clientName);
    mav.addObject("client_description", clientDescription);
    mav.addObject("client_group_name", clientGroupName);
    mav.addObject("client_website", clientWebsite);
    mav.addObject("scopes", ScopePathType.getScopesFromSpaceSeparatedString(scope));
    mav.addObject("scopesString", scope);
    mav.addObject("hideUserVoiceScript", true);
    mav.addObject("usePersistentTokens", usePersistentTokens);
    mav.setViewName("confirm-oauth-access");
    return mav;
}

From source file:org.orcid.frontend.web.controllers.OauthConfirmAccessController.java

@RequestMapping(value = { "/custom/signin.json", "/custom/login.json" }, method = RequestMethod.POST)
public @ResponseBody OauthAuthorizeForm authenticateAndAuthorize(HttpServletRequest request,
        HttpServletResponse response, @RequestBody OauthAuthorizeForm form) {
    // Clean form errors
    form.setErrors(new ArrayList<String>());
    boolean willBeRedirected = false;

    if (form.getApproved()) {
        // Validate name and password
        validateUserNameAndPassword(form);
        if (form.getErrors().isEmpty()) {
            try {
                // Authenticate user
                Authentication auth = authenticateUser(request, form);
                // 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>();

                // Set params
                setOauthParams(form, params, approvalParams, false);

                // 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}", form.getClientId().getValue());
                    // Set the response type if needed
                    if (!PojoUtil.isEmpty(form.getResponseType()))
                        redirectUri += "&response_type=" + form.getResponseType().getValue();
                    // Set the redirect uri
                    if (!PojoUtil.isEmpty(form.getRedirectUri()))
                        redirectUri += "&redirect_uri=" + form.getRedirectUri().getValue();
                    // Set the scope param
                    if (!PojoUtil.isEmpty(form.getScope()))
                        redirectUri += "&scope=" + form.getScope().getValue();
                    // Copy the state param if present
                    if (params != null && params.containsKey("state"))
                        redirectUri += "&state=" + params.get("state");
                    form.setRedirectUri(Text.valueOf(redirectUri));
                    LOGGER.info(/*from w  w  w. jav a2  s .  co  m*/
                            "OauthConfirmAccessController form.getRedirectUri being sent to client browser: "
                                    + form.getRedirectUri());
                    return form;
                }
                // Approve
                RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model,
                        status, auth);
                form.setRedirectUri(Text.valueOf(view.getUrl()));
                willBeRedirected = true;
            } catch (AuthenticationException ae) {
                form.getErrors().add(getMessage("orcid.frontend.security.bad_credentials"));
            }
        }
    } else {
        String stateParam = null;

        if (!PojoUtil.isEmpty(form.getStateParam())) {
            stateParam = form.getStateParam().getValue();
        }
        form.setRedirectUri(Text.valueOf(buildDenyRedirectUri(form.getRedirectUri().getValue(), stateParam)));
        willBeRedirected = true;
    }

    // If there was an authentication error, dont log since the user will
    // not be redirected yet
    if (willBeRedirected) {
        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: "
                + form.getRedirectUri());
    }
    return form;
}

From source file:org.orcid.frontend.web.controllers.OauthConfirmAccessController.java

@RequestMapping(value = "/custom/registerConfirm.json", method = RequestMethod.POST)
public @ResponseBody OauthRegistrationForm registerAndAuthorize(HttpServletRequest request,
        HttpServletResponse response, @RequestBody OauthRegistrationForm form) {
    if (form.getApproved()) {
        boolean usedCaptcha = false;

        // If recatcha wasn't loaded do nothing. This is for countries that
        // block google.
        if (form.getGrecaptchaWidgetId().getValue() != null) {
            // If the captcha verified key is not in the session, redirect
            // to
            // the login page
            if (request.getSession()
                    .getAttribute(RegistrationController.GRECAPTCHA_SESSION_ATTRIBUTE_NAME) == null
                    || PojoUtil.isEmpty(form.getGrecaptcha())
                    || !encryptionManager.encryptForExternalUse(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}", form.getClientId().getValue());
                // Set the response type if needed
                if (!PojoUtil.isEmpty(form.getResponseType()))
                    redirectUri += "&response_type=" + form.getResponseType().getValue();
                // Set the redirect uri
                if (!PojoUtil.isEmpty(form.getRedirectUri()))
                    redirectUri += "&redirect_uri=" + form.getRedirectUri().getValue();
                // Set the scope param
                if (!PojoUtil.isEmpty(form.getScope()))
                    redirectUri += "&scope=" + form.getScope().getValue();
                // Copy the state param if present
                if (!PojoUtil.isEmpty(request.getParameter("state")))
                    redirectUri += "&state=" + request.getParameter("state");
                form.setRedirectUri(Text.valueOf(redirectUri));
                SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
                if (savedRequest != null)
                    LOGGER.info(//from   ww  w .  j  ava 2  s. c o m
                            "OauthConfirmAccessController original request: " + savedRequest.getRedirectUrl());
                LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: "
                        + form.getRedirectUri());
                return form;
            }

            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);
        }

        // Check there are no errors
        registrationController.validateRegistrationFields(request, form);
        if (form.getErrors().isEmpty()) {
            // Register user
            registrationController.createMinimalRegistration(request,
                    RegistrationController.toProfile(form, request), usedCaptcha);
            // 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>();
            // Set params
            setOauthParams(form, params, approvalParams, true);

            // 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}", form.getClientId().getValue());
                // Set the response type if needed
                if (!PojoUtil.isEmpty(form.getResponseType()))
                    redirectUri += "&response_type=" + form.getResponseType().getValue();
                // Set the redirect uri
                if (!PojoUtil.isEmpty(form.getRedirectUri()))
                    redirectUri += "&redirect_uri=" + form.getRedirectUri().getValue();
                // Set the scope param
                if (!PojoUtil.isEmpty(form.getScope()))
                    redirectUri += "&scope=" + form.getScope().getValue();
                // Copy the state param if present
                if (params != null && params.containsKey("state"))
                    redirectUri += "&state=" + params.get("state");
                form.setRedirectUri(Text.valueOf(redirectUri));
                LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: "
                        + form.getRedirectUri());
                return form;
            }
            // Approve
            RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model,
                    status, auth);
            form.setRedirectUri(Text.valueOf(view.getUrl()));
        }
    } else {
        form.setRedirectUri(Text.valueOf(
                buildDenyRedirectUri(form.getRedirectUri().getValue(), request.getParameter("state"))));
    }

    SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
    if (savedRequest != null) {
        if (savedRequest != null)
            LOGGER.info("OauthConfirmAccessController original request: " + savedRequest.getRedirectUrl());
        LOGGER.info("OauthConfirmAccessController original request: " + savedRequest.getRedirectUrl());
    }
    LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: "
            + form.getRedirectUri());
    return form;
}

From source file:org.orcid.frontend.web.controllers.OauthConfirmAccessController.java

@RequestMapping(value = { "/custom/authorize.json" }, method = RequestMethod.POST)
public @ResponseBody OauthAuthorizeForm authorize(HttpServletRequest request, HttpServletResponse response,
        @RequestBody OauthAuthorizeForm 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 {//from   w w  w .  j  a  va2s  . c om
        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(form.getClientId().getValue()))
        // Then check if the client granted the persistent token
        if (form.getPersistentTokenEnabled())
            requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "true");

    // 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);
    form.setRedirectUri(Text.valueOf(view.getUrl()));
    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: "
            + form.getRedirectUri());
    return form;
}