Search in sources :

Example 16 with OAuthRequest

use of org.scribe.model.OAuthRequest in project fitscales by paulburton.

the class RunKeeperSyncService method postOAuth.

@Override
protected void postOAuth() {
    try {
        OAuthRequest request = new OAuthRequest(Verb.GET, API_BASE + "/profile");
        request.addHeader("Accept", "application/vnd.com.runkeeper.Profile+json");
        oaService.signRequest(oaToken, request);
        Response response = request.send();
        String body = response.getBody();
        if (DEBUG)
            Log.d(TAG, "Got profile body " + body);
        JSONObject json = new JSONObject(body);
        user = json.getString("name");
    } catch (Exception ex) {
        user = "unknown";
    }
}
Also used : OAuthRequest(org.scribe.model.OAuthRequest) Response(org.scribe.model.Response) JSONObject(org.json.JSONObject)

Example 17 with OAuthRequest

use of org.scribe.model.OAuthRequest in project sling by apache.

the class XingOauthAuthenticationHandler method fetchUser.

protected XingUser fetchUser(final Token accessToken) throws Exception {
    final OAuthRequest request = new OAuthRequest(Verb.GET, usersMeUrl);
    oAuthService.signRequest(accessToken, request);
    final Response response = request.send();
    final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    final Users users = gson.fromJson(response.getBody(), Users.class);
    return users.getUsers().get(0);
}
Also used : OAuthRequest(org.scribe.model.OAuthRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.scribe.model.Response) GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) Users(org.apache.sling.auth.xing.api.users.Users)

Example 18 with OAuthRequest

use of org.scribe.model.OAuthRequest in project webapp by elimu-ai.

the class SignOnControllerGoogle method handleCallback.

@RequestMapping(value = "/sign-on/google/callback", method = RequestMethod.GET)
public String handleCallback(HttpServletRequest request, Model model) {
    logger.info("handleCallback");
    if (request.getParameter("error") != null) {
        return "redirect:/sign-on?error=" + request.getParameter("error");
    } else {
        String verifierParam = request.getParameter("code");
        logger.debug("verifierParam: " + verifierParam);
        Verifier verifier = new Verifier(verifierParam);
        String responseBody = null;
        try {
            Token accessToken = oAuthService.getAccessToken(requestToken, verifier);
            logger.debug("accessToken: " + accessToken);
            OAuthRequest oAuthRequest = new OAuthRequest(Verb.GET, "https://www.googleapis.com/oauth2/v1/userinfo");
            oAuthService.signRequest(accessToken, oAuthRequest);
            Response response = oAuthRequest.send();
            responseBody = response.getBody();
            logger.info("response.getCode(): " + response.getCode());
            logger.info("response.getBody(): " + responseBody);
        } catch (OAuthException e) {
            logger.error(null, e);
            return "redirect:/sign-on?login_error=" + e.getMessage();
        }
        Contributor contributor = new Contributor();
        contributor.setReferrer(CookieHelper.getReferrer(request));
        contributor.setUtmSource(CookieHelper.getUtmSource(request));
        contributor.setUtmMedium(CookieHelper.getUtmMedium(request));
        contributor.setUtmCampaign(CookieHelper.getUtmCampaign(request));
        contributor.setUtmTerm(CookieHelper.getUtmTerm(request));
        contributor.setReferralId(CookieHelper.getReferralId(request));
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            logger.info("jsonObject: " + jsonObject);
            if (jsonObject.has("email")) {
                // TODO: validate e-mail
                contributor.setEmail(jsonObject.getString("email"));
            }
            if (jsonObject.has("id")) {
                contributor.setProviderIdGoogle(jsonObject.getString("id"));
            }
            if (jsonObject.has("picture")) {
                contributor.setImageUrl(jsonObject.getString("picture"));
            }
            if (jsonObject.has("given_name")) {
                contributor.setFirstName(jsonObject.getString("given_name"));
            }
            if (jsonObject.has("family_name")) {
                contributor.setLastName(jsonObject.getString("family_name"));
            }
        } catch (JSONException e) {
            logger.error(null, e);
        }
        Contributor existingContributor = contributorDao.read(contributor.getEmail());
        if (existingContributor == null) {
            // Store new Contributor in database
            contributor.setRegistrationTime(Calendar.getInstance());
            if (contributor.getEmail().endsWith("@elimu.ai")) {
                contributor.setRoles(new HashSet<>(Arrays.asList(Role.ADMIN, Role.ANALYST, Role.CONTRIBUTOR)));
            } else {
                contributor.setRoles(new HashSet<>(Arrays.asList(Role.CONTRIBUTOR)));
            }
            contributorDao.create(contributor);
            // Send welcome e-mail
            String to = contributor.getEmail();
            String from = "elimu.ai <info@elimu.ai>";
            String subject = "Welcome to the community";
            String title = "Welcome!";
            String firstName = StringUtils.isBlank(contributor.getFirstName()) ? "" : contributor.getFirstName();
            String htmlText = "<p>Hi, " + firstName + "</p>";
            htmlText += "<p>Thank you very much for registering as a contributor to the elimu.ai community. We are glad to see you join us!</p>";
            htmlText += "<h2>Purpose</h2>";
            htmlText += "<p>The purpose of elimu.ai is to provide <i>every child</i> with access to quality basic education.</p>";
            htmlText += "<h2>Why?</h2>";
            htmlText += "<p>The word \"elimu\" is Swahili for \"education\". We believe that a free quality education is the right of every child no matter her social or geographical background.</p>";
            htmlText += "<h2>How?</h2>";
            htmlText += "<p>With your help, this is what we aim to achieve:</p>";
            htmlText += "<p><blockquote>\"We build tablet-based software that teaches a child to read, write and calculate fully autonomously, without guidance from qualified teachers.\"</blockquote></p>";
            htmlText += "<p><img src=\"http://elimu.ai/static/img/banner-en.jpg\" alt=\"\" style=\"width: 564px; max-width: 100%;\" /></p>";
            htmlText += "<h2>Chat</h2>";
            htmlText += "<p>At http://slack.elimu.ai you can chat with the other community members.</p>";
            Mailer.sendHtmlWithButton(to, null, from, subject, title, htmlText, "Open chat", "http://slack.elimu.ai");
            if (EnvironmentContextLoaderListener.env == Environment.PROD) {
                // Post notification in Slack
                String name = "";
                if (StringUtils.isNotBlank(contributor.getFirstName())) {
                    name += "(";
                    name += contributor.getFirstName();
                    if (StringUtils.isNotBlank(contributor.getLastName())) {
                        name += " " + contributor.getLastName();
                    }
                    name += ")";
                }
                String text = URLEncoder.encode("A new contributor " + name + " just joined the community: ") + "http://elimu.ai/content/community/contributors";
                String iconUrl = contributor.getImageUrl();
                SlackApiHelper.postMessage(null, text, iconUrl, null);
            }
        } else {
            // Update existing contributor with latest values fetched from provider
            if (StringUtils.isNotBlank(contributor.getProviderIdGoogle())) {
                existingContributor.setProviderIdGoogle(contributor.getProviderIdGoogle());
            }
            if (StringUtils.isNotBlank(contributor.getImageUrl())) {
                existingContributor.setImageUrl(contributor.getImageUrl());
            }
            // TODO: firstName/lastName
            if (StringUtils.isBlank(existingContributor.getReferrer())) {
                existingContributor.setReferrer(contributor.getReferrer());
            }
            if (StringUtils.isBlank(existingContributor.getUtmSource())) {
                existingContributor.setUtmSource(contributor.getUtmSource());
            }
            if (StringUtils.isBlank(existingContributor.getUtmMedium())) {
                existingContributor.setUtmMedium(contributor.getUtmMedium());
            }
            if (StringUtils.isBlank(existingContributor.getUtmCampaign())) {
                existingContributor.setUtmCampaign(contributor.getUtmCampaign());
            }
            if (StringUtils.isBlank(existingContributor.getUtmTerm())) {
                existingContributor.setUtmTerm(contributor.getUtmTerm());
            }
            if (existingContributor.getReferralId() == null) {
                existingContributor.setReferralId(contributor.getReferralId());
            }
            contributorDao.update(existingContributor);
            // Contributor registered previously
            contributor = existingContributor;
        }
        // Authenticate
        new CustomAuthenticationManager().authenticateUser(contributor);
        // Add Contributor object to session
        request.getSession().setAttribute("contributor", contributor);
        SignOnEvent signOnEvent = new SignOnEvent();
        signOnEvent.setContributor(contributor);
        signOnEvent.setCalendar(Calendar.getInstance());
        signOnEvent.setServerName(request.getServerName());
        signOnEvent.setProvider(Provider.GOOGLE);
        signOnEvent.setRemoteAddress(request.getRemoteAddr());
        signOnEvent.setUserAgent(StringUtils.abbreviate(request.getHeader("User-Agent"), 1000));
        signOnEvent.setReferrer(CookieHelper.getReferrer(request));
        signOnEvent.setUtmSource(CookieHelper.getUtmSource(request));
        signOnEvent.setUtmMedium(CookieHelper.getUtmMedium(request));
        signOnEvent.setUtmCampaign(CookieHelper.getUtmCampaign(request));
        signOnEvent.setUtmTerm(CookieHelper.getUtmTerm(request));
        signOnEvent.setReferralId(CookieHelper.getReferralId(request));
        signOnEventDao.create(signOnEvent);
        return "redirect:/content";
    }
}
Also used : OAuthRequest(org.scribe.model.OAuthRequest) Response(org.scribe.model.Response) JSONObject(org.json.JSONObject) OAuthException(org.scribe.exceptions.OAuthException) Contributor(ai.elimu.model.Contributor) JSONException(org.json.JSONException) Token(org.scribe.model.Token) SignOnEvent(ai.elimu.model.contributor.SignOnEvent) Verifier(org.scribe.model.Verifier) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 19 with OAuthRequest

use of org.scribe.model.OAuthRequest in project OpenOLAT by OpenOLAT.

the class FacebookProvider method getUser.

@Override
public OAuthUser getUser(OAuthService service, Token accessToken) {
    OAuthRequest request = new OAuthRequest(Verb.GET, "https://graph.facebook.com/me");
    service.signRequest(accessToken, request);
    Response oauthResponse = request.send();
    String body = oauthResponse.getBody();
    return parseInfos(body);
}
Also used : OAuthRequest(org.scribe.model.OAuthRequest) Response(org.scribe.model.Response)

Example 20 with OAuthRequest

use of org.scribe.model.OAuthRequest in project muikku by otavanopisto.

the class PyramusApi20ServiceImpl method getAccessToken.

@Override
public Token getAccessToken(Token requestToken, Verifier verifier) {
    OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
    request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
    request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
    request.addBodyParameter(OAuthConstants.CODE, verifier.getValue());
    request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
    request.addBodyParameter("grant_type", "authorization_code");
    if (config.hasScope())
        request.addBodyParameter(OAuthConstants.SCOPE, config.getScope());
    Response response = request.send();
    ObjectMapper objectMapper = new ObjectMapper();
    String tokenJson;
    try {
        tokenJson = objectMapper.writeValueAsString(objectMapper.readTree(response.getBody()));
    } catch (IOException e) {
        throw new OAuthException("Invalid Token JSON", e);
    }
    return api.getAccessTokenExtractor().extract(tokenJson);
}
Also used : OAuthRequest(org.scribe.model.OAuthRequest) Response(org.scribe.model.Response) OAuthException(org.scribe.exceptions.OAuthException) IOException(java.io.IOException) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Aggregations

OAuthRequest (org.scribe.model.OAuthRequest)25 Response (org.scribe.model.Response)24 IOException (java.io.IOException)6 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)6 Date (java.util.Date)5 Token (org.scribe.model.Token)4 Verifier (org.scribe.model.Verifier)4 AuthenticationResult (fi.otavanopisto.muikku.auth.AuthenticationResult)3 Calendar (java.util.Calendar)3 GregorianCalendar (java.util.GregorianCalendar)3 JSONObject (org.json.JSONObject)3 OAuthException (org.scribe.exceptions.OAuthException)3 SimpleDateFormat (java.text.SimpleDateFormat)2 Contributor (ai.elimu.model.Contributor)1 SignOnEvent (ai.elimu.model.contributor.SignOnEvent)1 Gson (com.google.gson.Gson)1 GsonBuilder (com.google.gson.GsonBuilder)1 WhoAmI (fi.otavanopisto.pyramus.rest.model.WhoAmI)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1