Example usage for com.vaadin.server VaadinSession getCurrent

List of usage examples for com.vaadin.server VaadinSession getCurrent

Introduction

In this page you can find the example usage for com.vaadin.server VaadinSession getCurrent.

Prototype

public static VaadinSession getCurrent() 

Source Link

Document

Gets the currently used session.

Usage

From source file:edu.kit.dama.ui.admin.AdminUIMainView.java

License:Apache License

private void setupLandingPage(VaadinRequest request) {
    String oid = (String) request.getParameter("oid");
    IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
    DigitalObject result = null;/*from   w  w w .j  a  v a 2s . co  m*/
    Role viewRole = Role.GUEST;
    boolean objectNotFound = false;
    boolean extendedAccess = false;
    try {
        mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
        //check if object exists
        result = mdm.findSingleResult("SELECT o FROM DigitalObject o WHERE o.digitalObjectIdentifier=?1",
                new Object[] { oid }, DigitalObject.class);
        if (result == null) {
            //object does not exist
            objectNotFound = true;
        } else {
            //object does exist, check permission for current context
            try {
                viewRole = ResourceServiceLocal.getSingleton().getGrantRole(result.getSecurableResourceId(),
                        UIHelper.getSessionContext().getUserId(), AuthorizationContext.factorySystemContext());
            } catch (UnsupportedOperationException | EntityNotFoundException nogrants) {
                //no grant found, check group role
                try {
                    viewRole = (Role) ResourceServiceLocal.getSingleton().getReferenceRestriction(
                            new ReferenceId(result.getSecurableResourceId(), UIHelper.getSessionGroupId()),
                            AuthorizationContext.factorySystemContext());
                } catch (EntityNotFoundException ex) {
                    viewRole = Role.NO_ACCESS;
                }
            }
        }

        if (objectNotFound) {
            //object not found, if user logged in, show error...otherwise show login page
            if (UIHelper.getSessionUser().getDistinguishedName().equals(Constants.WORLD_USER_ID)) {
                VaadinSession.getCurrent().setAttribute("from",
                        UIHelper.getWebAppUrl().toString() + "?landing&oid=" + oid);
                updateView(VIEW.LOGIN);
                return;
            } else {
                throw new UnauthorizedAccessAttemptException("No object found for object id " + oid);
            }
        } else {
            //object not found, if role >= GUEST, show landing page...otherwise show login page if anonymous access
            if (!viewRole.atLeast(Role.GUEST)) {
                VaadinSession.getCurrent().setAttribute("from",
                        UIHelper.getWebAppUrl().toString() + "?landing&oid=" + oid);
                updateView(VIEW.LOGIN);
                return;
            }
        }
        //http://localhost:8080/KITDM/?landing&oid=3b1243b2-df09-4a98-ad87-21b7cda74be9catch (UnauthorizedAccessAttemptException | ParserConfigurationException ex) {
    } catch (UnauthorizedAccessAttemptException ex) {
        //not found, should result in error page
        LOGGER.error("Failed to access digital object with id " + oid, ex);
        result = null;
    } finally {
        mdm.close();
    }

    if (landingPage == null) {
        landingPage = new LandingPageComponent();
    }
    landingPage.update(result, extendedAccess);
    updateView(VIEW.LANDING);
}

From source file:edu.kit.dama.ui.admin.AdminUIMainView.java

License:Apache License

/**
 * Setup the login form including its logic.
 *///from  w w  w.java 2s. c  o m
private void setupLoginForm(AbstractLoginComponent.AUTH_MODE type, String pendingAuth, VaadinRequest request) {
    ComboBox authSelection = new ComboBox();
    authSelection.setWidth("400px");
    authSelection.setNullSelectionAllowed(false);
    authSelection.setStyleName("auth_selection");
    Label spacer = new Label("<br/>", ContentMode.HTML);
    spacer.setWidth("400px");

    String orcidClientId = DataManagerSettings.getSingleton()
            .getStringProperty(OrcidLoginComponent.ORCID_CLIENT_ID_PROPERTY, null);
    String orcidClientSecret = DataManagerSettings.getSingleton()
            .getStringProperty(OrcidLoginComponent.ORCID_CLIENT_SECRET_PROPERTY, null);

    /// String b2AccessClientId = DataManagerSettings.getSingleton().getStringProperty(B2AccessLoginComponent.B2ACCESS_CLIENT_ID_PROPERTY, null);
    // String b2AccessClientSecret = DataManagerSettings.getSingleton().getStringProperty(B2AccessLoginComponent.B2ACCESS_CLIENT_SECRET_PROPERTY, null);
    List<AbstractLoginComponent> components = new ArrayList<>();

    if (orcidClientId != null && !orcidClientId.equals("ORCID_CLIENT_ID") && orcidClientSecret != null
            && !orcidClientSecret.equals("ORCID_CLIENT_SECRET")) {
        components.add(new OrcidLoginComponent());
    }

    /*B2Access is currently not supported. 
    if (b2AccessClientId != null && b2AccessClientSecret != null) {
    components.add(new B2AccessLoginComponent());
    }*/
    components.add(new EmailPasswordLoginComponent());

    loginComponents = components.toArray(new AbstractLoginComponent[] {});

    //default login component has index 0
    loginComponent = loginComponents[0];
    for (AbstractLoginComponent component : loginComponents) {
        //add new login component
        authSelection.addItem(component.getLoginIdentifier());
        authSelection.setItemCaption(component.getLoginIdentifier(), component.getLoginLabel());

        if (pendingAuth != null && pendingAuth.equals(component.getLoginIdentifier())) {
            //login or registration process in pending, continue process
            loginComponent = component;
            try {
                switch (type) {
                case REGISTRATION:
                    loginComponent.doRegistration(request);
                    break;
                default:
                    loginComponent.doLogin(request);
                    break;
                }

            } catch (UnauthorizedAccessAttemptException ex) {
                //failed to continue auth...cancel.
                String message = "Failed to continue pending "
                        + (AbstractLoginComponent.AUTH_MODE.LOGIN.equals(type) ? "login" : "registration")
                        + " for authentication #" + pendingAuth + ".";
                LOGGER.error(message, ex);
                UIComponentTools.showError(message);
                VaadinSession.getCurrent().setAttribute("auth_pending", null);
                VaadinSession.getCurrent().setAttribute("registration_pending", null);
                loginComponent.reset();
            }
        }
    }

    authSelection.select(loginComponent.getLoginIdentifier());

    authSelection.addValueChangeListener((Property.ValueChangeEvent event) -> {
        String value = (String) event.getProperty().getValue();
        if (value != null) {
            for (AbstractLoginComponent component : loginComponents) {
                if (value.equals(component.getLoginIdentifier())) {
                    loginForm.replaceComponent(loginComponent, component);
                    loginComponent = component;
                }
            }
        }
    });

    loginForm = new VerticalLayout(authSelection, spacer, loginComponent);
    loginForm.setComponentAlignment(authSelection, Alignment.TOP_CENTER);
    loginForm.setComponentAlignment(spacer, Alignment.TOP_CENTER);
    loginForm.setComponentAlignment(loginComponent, Alignment.TOP_CENTER);
}

From source file:edu.kit.dama.ui.admin.login.B2AccessLoginComponent.java

License:Apache License

@Override
public void doLogin(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    String clientId = DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_ID_PROPERTY, null);
    String clientSecret = DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_SECRET_PROPERTY,
            null);//from  w w w  . j a v a2  s .co  m

    if (request == null) {
        //set auth_pending attribute in order to be able to finish authentication later
        VaadinSession.getCurrent().setAttribute("auth_pending", getLoginIdentifier());
        Page.getCurrent()
                .setLocation("https://unity.eudat-aai.fz-juelich.de:8443/oauth2-as/oauth2-authz?client_id="
                        + clientId + "&response_type=code&scope=/authenticate&redirect_uri="
                        + UIHelper.getWebAppUrl().toString());
    } else {
        //delete auth_pending attribute as we'll finish now or never
        VaadinSession.getCurrent().setAttribute("auth_pending", null);
        //obtain remaining information and do redirect
        //do actual login
        LOGGER.debug("Obtaining OAuth2 code from URL parameter.");
        String code = request.getParameter("code");

        MultivaluedMap formData = new MultivaluedMapImpl();
        formData.putSingle("client_id", clientId);
        formData.putSingle("client_secret", clientSecret);
        formData.putSingle("grant_type", "authorization_code");
        formData.putSingle("redirect_uri", UIHelper.getWebAppUrl().toString());
        formData.putSingle("code", code);

        ClientConfig config = new DefaultClientConfig();
        IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
        mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { TRUST_MANAGER }, new SecureRandom());

            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new HTTPSProperties(VERIFIER, ctx));
            Client client = Client.create(config);
            WebResource webResource = client
                    .resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/token");
            webResource.addFilter(new HTTPBasicAuthFilter("KITDM", "0kudH2O."));

            LOGGER.debug("Obtaining access token.");
            ClientResponse response = webResource.header("Content-Type", "application/x-www-form-urlencoded")
                    .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, formData);

            if (response.getStatus() == 200) {
                LOGGER.debug("Response status is HTTP 200. Parsing JSON response.");
                String responseData = response.getEntity(String.class);
                JSONObject responseObject = new JSONObject(responseData);
                String access_token = responseObject.getString("access_token");
                webResource = client.resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/userinfo");
                LOGGER.debug("Accessing B2Access UserInfo at {}." + webResource.getURI());
                response = webResource.header("Content-Type", "application/x-www-form-urlencoded")
                        .accept(MediaType.APPLICATION_JSON).header("Authorization", "Bearer " + access_token)
                        .get(ClientResponse.class);

                if (response.getStatus() == 200) {
                    JSONObject userInfoResponse = new JSONObject(response.getEntity(String.class));
                    String userId = userInfoResponse.getString("sub");
                    UserData result = mdm.findSingleResult(
                            "Select u FROM UserData u WHERE u.distinguishedName=?1", new Object[] { userId },
                            UserData.class);
                    if (result != null) {
                        LOGGER.debug("User with distinguished name {} found. Logging in and redirecting user.",
                                userId);
                        UIHelper.login(new UserId(result.getDistinguishedName()),
                                new GroupId(Constants.USERS_GROUP_ID));
                    } else {
                        LOGGER.warn("No user found for ORCiD {}. Login denied.", userId);
                        throw new UnauthorizedAccessAttemptException(
                                "No user found for ORCiD '" + userId + "'.");
                    }
                } else {
                    //failed, not enough information to proceed!
                }
            } else {
                throw new HttpException("Failed to obtain access token from ORCiD service. Status is "
                        + response.getStatus() + ", response data is: " + response.getEntity(String.class));
            }

            //{"access_token":"84e8f8d0-1df6-43af-9456-6619ef514aed","token_type":"bearer","refresh_token":"2f5116b4-f046-4f69-99c5-097e6066a132","expires_in":631138518,"scope":"/authenticate","name":"Thomas Jejkal","orcid":"0000-0003-2804-688X"}
            //https://pub.orcid.org/v1.2/0000-0003-2804-688X/orcid-bio
        } catch (NoSuchAlgorithmException | KeyManagementException | HttpException ex) {
            LOGGER.error("Failed to access B2Access service.", ex);
            throw new UnauthorizedAccessAttemptException("Failed to login via B2Access.", ex);
        } finally {
            mdm.close();
        }

        String fromPage = (String) VaadinSession.getCurrent().getAttribute("from");
        if (fromPage != null) {
            VaadinSession.getCurrent().setAttribute("from", null);
            Page.getCurrent().setLocation(fromPage);
        } else {
            Page.getCurrent().setLocation(UIHelper.getWebAppUrl().toString());
        }
    }
}

From source file:edu.kit.dama.ui.admin.login.B2AccessLoginComponent.java

License:Apache License

@Override
public void doRegistration(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    String clientId = DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_ID_PROPERTY, null);
    String clientSecret = DataManagerSettings.getSingleton().getStringProperty(B2ACCESS_CLIENT_SECRET_PROPERTY,
            null);//from w  w  w. j  av  a 2s . c  om

    UserData result = new UserData();
    if (request == null) {
        VaadinSession.getCurrent().setAttribute("registration_pending", getLoginIdentifier());
        Page.getCurrent()
                .setLocation("https://unity.eudat-aai.fz-juelich.de:8443/oauth2-as/oauth2-authz?client_id="
                        + clientId + "&response_type=code&scope=write&redirect_uri="
                        + UIHelper.getWebAppUrl().toString());
    } else {
        //delete auth_pending attribute as we'll finish now or never
        VaadinSession.getCurrent().setAttribute("registration_pending", null);
        //obtain remaining information and do redirect
        //do actual login
        LOGGER.debug("Obtaining OAuth2 code from URL parameter.");
        String code = request.getParameter("code");

        MultivaluedMap formData = new MultivaluedMapImpl();
        formData.putSingle("client_id", clientId);
        formData.putSingle("client_secret", clientSecret);
        formData.putSingle("grant_type", "authorization_code");
        formData.putSingle("redirect_uri", UIHelper.getWebAppUrl().toString());
        formData.putSingle("code", code);

        ClientConfig config = new DefaultClientConfig();
        IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
        mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { TRUST_MANAGER }, new SecureRandom());
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new HTTPSProperties(VERIFIER, ctx));
            Client client = Client.create(config);
            WebResource webResource = client
                    .resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/token");
            webResource.addFilter(new HTTPBasicAuthFilter("KITDM", "0kudH2O."));

            LOGGER.debug("Obtaining access token.");
            ClientResponse response = webResource.header("Content-Type", "application/x-www-form-urlencoded")
                    .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, formData);

            if (response.getStatus() == 200) {
                String responseData = response.getEntity(String.class);
                JSONObject responseObject = new JSONObject(responseData);
                String access_token = responseObject.getString("access_token");
                webResource = client.resource("https://unity.eudat-aai.fz-juelich.de:8443/oauth2/userinfo");

                LOGGER.debug("Accessing B2Access UserInfo at {}." + webResource.getURI());
                response = webResource.header("Content-Type", "application/x-www-form-urlencoded")
                        .accept(MediaType.APPLICATION_JSON).header("Authorization", "Bearer " + access_token)
                        .get(ClientResponse.class);

                if (response.getStatus() == 200) {
                    JSONObject userInfoResponse = new JSONObject(response.getEntity(String.class));
                    try {
                        String userId = userInfoResponse.getString("sub");
                        List<UserData> existingUsers = mdm.findResultList(
                                "Select u FROM UserData u WHERE u.distinguishedName=?1",
                                new Object[] { userId }, UserData.class);
                        if (!existingUsers.isEmpty()) {
                            //user for B2Access subject already exists...unable to continue
                            throw new UnauthorizedAccessAttemptException(
                                    "There is already a user registered for the obtained B2Access id '" + userId
                                            + "'.");
                        }
                        result.setDistinguishedName(userId);
                    } catch (JSONException ex) {
                        //failed, not enough information to proceed!
                    }
                } else {
                    //failed, not enough information to proceed!
                }
            } else {
                //failed, not enough information to proceed!
            }
        } catch (NoSuchAlgorithmException | KeyManagementException | JSONException ex) {
            LOGGER.error("Failed to collect information from B2Access service.", ex);
            throw new UnauthorizedAccessAttemptException("Failed to collect information from B2Access service.",
                    ex);
        } finally {
            mdm.close();
        }
        setup(AUTH_MODE.REGISTRATION, result);
    }
}

From source file:edu.kit.dama.ui.admin.login.EmailPasswordLoginComponent.java

License:Apache License

@Override
public void doLogin(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    if (!UIUtils7.validate(loginForm)) {
        throw new UnauthorizedAccessAttemptException("Login Failed. Please correct the error(s) above.");
    }/*from w  w  w . j  av a  2  s .  c  o m*/
    String userMail = email.getValue();
    String userPassword = password.getValue();

    if (userMail == null || password == null) {
        throw new UnauthorizedAccessAttemptException("Please provide username and password.");
    }

    IMetaDataManager manager = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
    manager.setAuthorizationContext(AuthorizationContext.factorySystemContext());
    try {
        LOGGER.debug("Getting access token for user {}", userMail);
        ServiceAccessToken token = ServiceAccessUtil.getAccessToken(manager, userMail,
                Constants.MAIN_LOGIN_SERVICE_ID);
        if (token == null) {
            throw new UnauthorizedAccessAttemptException(
                    "Login Failed. No login information found for email " + userMail + ".");
        } else {
            LOGGER.debug("Access token sucessfully obtained. Checking password.");
        }

        if (!userPassword.equals(token.getSecret())) {
            throw new UnauthorizedAccessAttemptException(
                    "Login Failed. Wrong password for email " + userMail + ".");
        } else {
            LOGGER.debug("Password is correct. Getting user information.");
            //login successful
            UserData template = new UserData();
            template.setDistinguishedName(token.getUserId());
            List<UserData> result = manager.find(template, template);
            if (result.isEmpty() || result.size() > 1) {
                throw new Exception("Invalid number of user entries (" + result.size() + ") found for userId "
                        + token.getUserId() + ". Please contact a system administrator.");
            }
            LOGGER.debug("User information obtained. Setting logged in user and updating main layout.");
            //do actual login
            UIHelper.login(new UserId(result.get(0).getDistinguishedName()),
                    new GroupId(Constants.USERS_GROUP_ID));
        }
    } catch (Exception ex) {
        LOGGER.error("Failed to access login database.", ex);
        throw new UnauthorizedAccessAttemptException(
                "Login failed due to an internal error. Please contact an administrator.");
    } finally {
        manager.close();
    }

    String fromPage = (String) VaadinSession.getCurrent().getAttribute("from");
    if (fromPage != null) {
        VaadinSession.getCurrent().setAttribute("from", null);
        Page.getCurrent().setLocation(fromPage);
    } else {
        Page.getCurrent().setLocation(UIHelper.getWebAppUrl().toString());
    }
}

From source file:edu.kit.dama.ui.admin.login.OrcidLoginComponent.java

License:Apache License

@Override
public void doLogin(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    String clientId = DataManagerSettings.getSingleton().getStringProperty(ORCID_CLIENT_ID_PROPERTY, null);
    String clientSecret = DataManagerSettings.getSingleton().getStringProperty(ORCID_CLIENT_SECRET_PROPERTY,
            null);//from ww w.  j ava  2  s  . c om

    if (request == null) {
        //set auth_pending attribute in order to be able to finish authentication later
        VaadinSession.getCurrent().setAttribute("auth_pending", getLoginIdentifier());
        Page.getCurrent().setLocation("https://orcid.org/oauth/authorize?client_id=" + clientId
                + "&response_type=code&scope=/authenticate&redirect_uri=" + UIHelper.getWebAppUrl().toString());
    } else {
        //delete auth_pending attribute as we'll finish now or never
        VaadinSession.getCurrent().setAttribute("auth_pending", null);
        //obtain remaining information and do redirect
        //do actual login
        LOGGER.debug("Obtaining OAuth2 code from URL parameter.");
        String code = request.getParameter("code");

        MultivaluedMap formData = new MultivaluedMapImpl();
        formData.putSingle("client_id", clientId);
        formData.putSingle("client_secret", clientSecret);
        formData.putSingle("grant_type", "authorization_code");
        formData.putSingle("redirect_uri", UIHelper.getWebAppUrl().toString());
        formData.putSingle("code", code);

        ClientConfig config = new DefaultClientConfig();
        IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
        mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { TRUST_MANAGER }, new SecureRandom());
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new HTTPSProperties(VERIFIER, ctx));
            Client client = Client.create(config);
            URI resourceUri = new URL("https://orcid.org/oauth/token").toURI();
            WebResource webResource = client.resource(resourceUri);

            LOGGER.debug("Requesting OAuth2 access token.");
            ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class,
                    formData);
            if (response.getStatus() == 200) {
                LOGGER.debug("Response status is HTTP 200. Parsing JSON response.");
                String responseData = response.getEntity(String.class);

                JSONObject responseObject = new JSONObject(responseData);
                String orcid = responseObject.getString("orcid");
                //   String accessToken = responseObject.getString("access_token");
                LOGGER.debug("Obtained ORCiD is {}.", orcid);

                ServiceAccessToken result = mdm.findSingleResult(
                        "Select t FROM ServiceAccessToken t WHERE t.tokenKey=?1",
                        new Object[] { CryptUtil.stringToSHA1(orcid) }, ServiceAccessToken.class);

                if (result != null) {
                    LOGGER.debug("User with id {} found. Logging in and redirecting user.", result.getUserId());
                    UIHelper.login(new UserId(result.getUserId()), new GroupId(Constants.USERS_GROUP_ID));
                } else {
                    LOGGER.warn("No user found for ORCiD {}. Login denied.", orcid);
                    throw new UnauthorizedAccessAttemptException(
                            "No login credential found for ORCiD '" + orcid + "'.");
                }
            } else {
                throw new HttpException("Failed to obtain access token from ORCiD service. Status is "
                        + response.getStatus() + ", response data is: " + response.getEntity(String.class));
            }

            //{"access_token":"84e8f8d0-1df6-43af-9456-6619ef514aed","token_type":"bearer","refresh_token":"2f5116b4-f046-4f69-99c5-097e6066a132","expires_in":631138518,"scope":"/authenticate","name":"Thomas Jejkal","orcid":"0000-0003-2804-688X"}
            //https://pub.orcid.org/v1.2/0000-0003-2804-688X/orcid-bio
        } catch (NoSuchAlgorithmException | KeyManagementException | MalformedURLException | URISyntaxException
                | HttpException ex) {
            LOGGER.error("Failed to access ORCiD service.", ex);
            throw new UnauthorizedAccessAttemptException("Failed to login via ORCiD.", ex);
        } finally {
            mdm.close();
        }

        String fromPage = (String) VaadinSession.getCurrent().getAttribute("from");
        if (fromPage != null) {
            VaadinSession.getCurrent().setAttribute("from", null);
            Page.getCurrent().setLocation(fromPage);
        } else {
            Page.getCurrent().setLocation(UIHelper.getWebAppUrl().toString());
        }
    }
}

From source file:edu.kit.dama.ui.admin.login.OrcidLoginComponent.java

License:Apache License

@Override
public void doRegistration(VaadinRequest request) throws UnauthorizedAccessAttemptException {
    String clientId = DataManagerSettings.getSingleton().getStringProperty(ORCID_CLIENT_ID_PROPERTY, null);
    String clientSecret = DataManagerSettings.getSingleton().getStringProperty(ORCID_CLIENT_SECRET_PROPERTY,
            null);/*from   w ww.j  av a2s .  co m*/

    UserData result = new UserData();
    if (request == null) {
        VaadinSession.getCurrent().setAttribute("registration_pending", getLoginIdentifier());
        Page.getCurrent().setLocation("https://orcid.org/oauth/authorize?client_id=" + clientId
                + "&response_type=code&scope=/authenticate&redirect_uri=" + UIHelper.getWebAppUrl().toString());
    } else {
        //delete auth_pending attribute as we'll finish now or never
        VaadinSession.getCurrent().setAttribute("registration_pending", null);
        //obtain remaining information and do redirect
        //do actual login
        LOGGER.debug("Obtaining OAuth2 code from URL parameter.");
        String code = request.getParameter("code");

        MultivaluedMap formData = new MultivaluedMapImpl();
        formData.putSingle("client_id", clientId);
        formData.putSingle("client_secret", clientSecret);
        formData.putSingle("grant_type", "authorization_code");
        formData.putSingle("redirect_uri", UIHelper.getWebAppUrl().toString());
        formData.putSingle("code", code);

        ClientConfig config = new DefaultClientConfig();
        IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
        mdm.setAuthorizationContext(AuthorizationContext.factorySystemContext());
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] { TRUST_MANAGER }, new SecureRandom());
            config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                    new HTTPSProperties(VERIFIER, ctx));
            Client client = Client.create(config);
            WebResource webResource = client.resource("https://orcid.org/oauth/token");
            LOGGER.debug("Obtaining access token.");
            ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class,
                    formData);

            if (response.getStatus() == 200) {
                String responseData = response.getEntity(String.class);
                JSONObject responseObject = new JSONObject(responseData);
                String orcid = responseObject.getString("orcid");
                List<UserData> existingUsers = mdm.findResultList(
                        "Select u FROM UserData u WHERE u.distinguishedName=?1", new Object[] { orcid },
                        UserData.class);
                if (!existingUsers.isEmpty()) {
                    //user for ORCiD already exists...unable to continue
                    throw new UnauthorizedAccessAttemptException(
                            "There is already a user registered for ORCiD " + orcid + ".");
                }

                LOGGER.debug("Requesting registration information for ORCiD {}.", orcid);
                result.setDistinguishedName(orcid);

                String access_token = responseObject.getString("access_token");
                //https://pub.orcid.org/v1.2/0000-0003-2804-688X/orcid-bio
                webResource = client.resource("https://pub.orcid.org/v1.2/" + orcid + "/orcid-bio");
                LOGGER.debug("Accessing ORCiD service at {}." + webResource.getURI());
                response = webResource.accept(MediaType.APPLICATION_JSON)
                        .header("Authentication", "Bearer " + access_token).get(ClientResponse.class);
                if (response.getStatus() == 200) {
                    JSONObject orcidResponse = new JSONObject(response.getEntity(String.class));
                    //Sample response with mail visible
                    //{"message-version":"1.2","orcid-profile":{"orcid":null,"orcid-id":null,"orcid-identifier":{"value":null,"uri":"http://orcid.org/0000-0003-2804-688X","path":"0000-0003-2804-688X","host":"orcid.org"},"orcid-deprecated":null,"orcid-preferences":{"locale":"EN"},"orcid-history":{"creation-method":"DIRECT","completion-date":null,"submission-date":{"value":1432891995500},"last-modified-date":{"value":1476705802439},"claimed":{"value":true},"source":null,"deactivation-date":null,"verified-email":{"value":true},"verified-primary-email":{"value":true},"visibility":null},"orcid-bio":{"personal-details":{"given-names":{"value":"Thomas","visibility":null},"family-name":{"value":"Jejkal","visibility":null},"credit-name":{"value":"Thomas Jejkal","visibility":"PUBLIC"},"other-names":null},"biography":null,"researcher-urls":null,"contact-details":{"email":[{"value":"thomas.jejkal@kit.edu","primary":true,"current":true,"verified":true,"visibility":"PUBLIC","source":"0000-0003-2804-688X","source-client-id":null}],"address":{"country":{"value":"DE","visibility":"PUBLIC"}}},"keywords":null,"external-identifiers":null,"delegation":null,"scope":null},"orcid-activities":null,"orcid-internal":null,"type":"USER","group-type":null,"client-type":null},"orcid-search-results":null,"error-desc":null}
                    //Sample response with mail invisible
                    //{"message-version":"1.2","orcid-profile":{"orcid":null,"orcid-id":null,"orcid-identifier":{"value":null,"uri":"http://orcid.org/0000-0003-2804-688X","path":"0000-0003-2804-688X","host":"orcid.org"},"orcid-deprecated":null,"orcid-preferences":{"locale":"EN"},"orcid-history":{"creation-method":"DIRECT","completion-date":null,"submission-date":{"value":1432891995500},"last-modified-date":{"value":1476705875890},"claimed":{"value":true},"source":null,"deactivation-date":null,"verified-email":{"value":true},"verified-primary-email":{"value":true},"visibility":null},"orcid-bio":{"personal-details":{"given-names":{"value":"Thomas","visibility":null},"family-name":{"value":"Jejkal","visibility":null},"credit-name":{"value":"Thomas Jejkal","visibility":"PUBLIC"},"other-names":null},"biography":null,"researcher-urls":null,"contact-details":{"email":[],"address":{"country":{"value":"DE","visibility":"PUBLIC"}}},"keywords":null,"external-identifiers":null,"delegation":null,"scope":null},"orcid-activities":null,"orcid-internal":null,"type":"USER","group-type":null,"client-type":null},"orcid-search-results":null,"error-desc":null}
                    try {
                        JSONObject orcidBio = orcidResponse.getJSONObject("orcid-profile")
                                .getJSONObject("orcid-bio");
                        try {
                            JSONObject personalDetails = orcidBio.getJSONObject("personal-details");
                            String lastName = personalDetails.getJSONObject("family-name").getString("value");
                            String firstName = personalDetails.getJSONObject("given-names").getString("value");
                            result.setFirstName(firstName);
                            result.setLastName(lastName);
                        } catch (JSONException ex) {
                            //failed to collect personal information
                            LOGGER.info(
                                    "No personal-details element found in ORCiD response entity. Skipping first and last name properties.");
                        }

                        try {
                            JSONObject contactDetails = orcidBio.getJSONObject("contact-details");
                            String email = contactDetails.getJSONArray("email").getJSONObject(0)
                                    .getString("value");
                            result.setEmail(email);
                        } catch (JSONException ex) {
                            //failed to collect email
                            LOGGER.info(
                                    "No contact-details element found in ORCiD response entity. Skipping email property.");
                        }
                    } catch (JSONException ex) {
                        //failed to collect email
                        LOGGER.info(
                                "No orcid-profile and/or orcid-bio elements found in ORCiD response entity. No properties can be obtained.");
                    }
                } else {
                    LOGGER.warn("Failed to obtain user profile from ORCiD service. Status is "
                            + response.getStatus() + ", response data is: " + response.getEntity(String.class));
                }
            } else {
                //unable to obtain ORCiD id...unable to continue 
                throw new UnauthorizedAccessAttemptException(
                        "Failed to obtain access token from ORCiD service. Status is " + response.getStatus()
                                + ", response data is: " + response.getEntity(String.class));
            }
            //{"access_token":"84e8f8d0-1df6-43af-9456-6619ef514aed","token_type":"bearer","refresh_token":"2f5116b4-f046-4f69-99c5-097e6066a132","expires_in":631138518,"scope":"/authenticate","name":"Thomas Jejkal","orcid":"0000-0003-2804-688X"}
        } catch (NoSuchAlgorithmException | KeyManagementException | JSONException ex) {
            LOGGER.error("Failed to collect information from ORCiD service.", ex);
            throw new UnauthorizedAccessAttemptException("Failed to collect information from ORCiD service.",
                    ex);
        } finally {
            mdm.close();
        }

        setup(AUTH_MODE.REGISTRATION, result);
    }
}

From source file:edu.kit.dama.ui.admin.utils.UIHelper.java

License:Apache License

public static void login(UserId user, GroupId group) {
    VaadinSession.getCurrent().setAttribute("userId", user.getStringRepresentation());
    changeSessionGroup(group);/*  ww  w  . j  a  v  a 2 s  . c  o  m*/
}

From source file:edu.kit.dama.ui.admin.utils.UIHelper.java

License:Apache License

public static void logout(String destination) {
    VaadinSession.getCurrent().close();
    Page.getCurrent().setLocation(destination);
}

From source file:edu.kit.dama.ui.admin.utils.UIHelper.java

License:Apache License

public static void changeSessionGroup(GroupId group) {
    VaadinSession.getCurrent().setAttribute("groupId", group.getStringRepresentation());
}