Search in sources :

Example 1 with OAuthService

use of org.scribe.oauth.OAuthService in project openhab1-addons by openhab.

the class OpenPathsBinding method getUserLocation.

@SuppressWarnings("unchecked")
private Location getUserLocation(String accessKey, String secretKey) {
    // build the OAuth service using the access/secret keys
    OAuthService service = new ServiceBuilder().provider(new OpenPathsApi()).apiKey(accessKey).apiSecret(secretKey).build();
    // build the request
    OAuthRequest request = new OAuthRequest(Verb.GET, "https://openpaths.cc/api/1");
    service.signRequest(Token.empty(), request);
    request.addQuerystringParameter("num_points", "1");
    // send the request and check we got a successful response
    Response response = request.send();
    if (!response.isSuccessful()) {
        logger.error("Failed to request the OpenPaths location, response code: " + response.getCode());
        return null;
    }
    // parse the response to build our location object
    Map<String, Object> locationData;
    String toParse = "{}";
    try {
        ObjectMapper jsonReader = new ObjectMapper();
        toParse = response.getBody();
        toParse = toParse.substring(1, toParse.length() - 2);
        locationData = jsonReader.readValue(toParse, Map.class);
    } catch (JsonParseException e) {
        logger.error("Error parsing JSON:\n" + toParse, e);
        return null;
    } catch (JsonMappingException e) {
        logger.error("Error mapping JSON:\n" + toParse, e);
        return null;
    } catch (IOException e) {
        logger.error("An I/O error occured while decoding JSON:\n" + response.getBody());
        return null;
    }
    float latitude = Float.parseFloat(locationData.get("lat").toString());
    float longitude = Float.parseFloat(locationData.get("lon").toString());
    String device = locationData.get("device").toString();
    return new Location(latitude, longitude, device);
}
Also used : OAuthRequest(org.scribe.model.OAuthRequest) IOException(java.io.IOException) JsonParseException(org.codehaus.jackson.JsonParseException) ServiceBuilder(org.scribe.builder.ServiceBuilder) Response(org.scribe.model.Response) OAuthService(org.scribe.oauth.OAuthService) JsonMappingException(org.codehaus.jackson.map.JsonMappingException) HashMap(java.util.HashMap) Map(java.util.Map) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 2 with OAuthService

use of org.scribe.oauth.OAuthService in project OpenOLAT by OpenOLAT.

the class OAuthResource method redirect.

public static void redirect(OAuthSPI oauthProvider, HttpServletResponse httpResponse, HttpSession httpSession) {
    // Configure
    try {
        ServiceBuilder builder = new ServiceBuilder();
        builder.provider(oauthProvider.getScribeProvider()).apiKey(oauthProvider.getAppKey()).apiSecret(oauthProvider.getAppSecret());
        String[] scopes = oauthProvider.getScopes();
        for (String scope : scopes) {
            builder.scope(scope);
        }
        String callbackUrl = Settings.getServerContextPathURI() + OAuthConstants.CALLBACK_PATH;
        OAuthService service = builder.callback(callbackUrl).build();
        httpSession.setAttribute(OAuthConstants.OAUTH_SERVICE, service);
        httpSession.setAttribute(OAuthConstants.OAUTH_SPI, oauthProvider);
        if ("2.0".equals(service.getVersion())) {
            String redirectUrl = service.getAuthorizationUrl(null);
            saveStateAndNonce(httpSession, redirectUrl);
            httpResponse.sendRedirect(redirectUrl);
        } else {
            Token token = service.getRequestToken();
            httpSession.setAttribute(OAuthConstants.REQUEST_TOKEN, token);
            String redirectUrl = service.getAuthorizationUrl(token);
            httpResponse.sendRedirect(redirectUrl);
        }
    } catch (Exception e) {
        log.error("", e);
    }
}
Also used : OAuthService(org.scribe.oauth.OAuthService) Token(org.scribe.model.Token) ServiceBuilder(org.scribe.builder.ServiceBuilder)

Example 3 with OAuthService

use of org.scribe.oauth.OAuthService in project OpenOLAT by OpenOLAT.

the class OAuthDispatcher method execute.

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String uri = request.getRequestURI();
    try {
        uri = URLDecoder.decode(uri, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new AssertException("UTF-8 encoding not supported!!!!");
    }
    String uriPrefix = DispatcherModule.getLegacyUriPrefix(request);
    uri = uri.substring(uriPrefix.length());
    UserRequest ureq = null;
    try {
        // upon creation URL is checked for
        ureq = new UserRequestImpl(uriPrefix, request, response);
    } catch (NumberFormatException nfe) {
        if (log.isDebug()) {
            log.debug("Bad Request " + request.getPathInfo());
        }
        DispatcherModule.sendBadRequest(request.getPathInfo(), response);
        return;
    }
    String error = request.getParameter("error");
    if (null != error) {
        error(ureq, translateOauthError(ureq, error));
        return;
    }
    String problem = request.getParameter("oauth_problem");
    if (problem != null && "token_rejected".equals(problem.trim())) {
        error(ureq, translateOauthError(ureq, error));
        return;
    }
    try {
        HttpSession sess = request.getSession();
        // OAuth 2.0 hasn't any request token
        Token requestToken = (Token) sess.getAttribute(OAuthConstants.REQUEST_TOKEN);
        OAuthService service = (OAuthService) sess.getAttribute(OAuthConstants.OAUTH_SERVICE);
        OAuthSPI provider = (OAuthSPI) sess.getAttribute(OAuthConstants.OAUTH_SPI);
        Token accessToken;
        if (provider == null) {
            log.audit("OAuth Login failed, no provider in request");
            DispatcherModule.redirectToDefaultDispatcher(response);
            return;
        } else if (provider.isImplicitWorkflow()) {
            String idToken = ureq.getParameter("id_token");
            if (idToken == null) {
                redirectImplicitWorkflow(ureq);
                return;
            } else {
                Verifier verifier = OpenIDVerifier.create(ureq, sess);
                accessToken = service.getAccessToken(requestToken, verifier);
            }
        } else {
            String requestVerifier = request.getParameter("oauth_verifier");
            if (requestVerifier == null) {
                // OAuth 2.0 as a code
                requestVerifier = request.getParameter("code");
            }
            accessToken = service.getAccessToken(requestToken, new Verifier(requestVerifier));
        }
        OAuthUser infos = provider.getUser(service, accessToken);
        if (infos == null || !StringHelper.containsNonWhitespace(infos.getId())) {
            error(ureq, translate(ureq, "error.no.id"));
            log.error("OAuth Login failed, no infos extracted from access token: " + accessToken);
            return;
        }
        OAuthRegistration registration = new OAuthRegistration(provider.getProviderName(), infos);
        login(infos, registration);
        if (provider instanceof OAuthUserCreator) {
            Identity newIdentity;
            OAuthUserCreator userCreator = (OAuthUserCreator) provider;
            if (registration.getIdentity() == null) {
                newIdentity = userCreator.createUser(infos);
            } else {
                newIdentity = userCreator.updateUser(infos, registration.getIdentity());
            }
            if (newIdentity != null) {
                registration.setIdentity(newIdentity);
            }
        }
        if (registration.getIdentity() == null) {
            if (CoreSpringFactory.getImpl(OAuthLoginModule.class).isAllowUserCreation()) {
                register(request, response, registration);
            } else {
                error(ureq, translate(ureq, "error.account.creation"));
                log.error("OAuth Login ok but the user has not an account on OpenOLAT: " + infos);
            }
        } else {
            if (ureq.getUserSession() != null) {
                // re-init the activity logger
                ThreadLocalUserActivityLoggerInstaller.initUserActivityLogger(request);
            }
            Identity identity = registration.getIdentity();
            int loginStatus = AuthHelper.doLogin(identity, provider.getProviderName(), ureq);
            if (loginStatus != AuthHelper.LOGIN_OK) {
                if (loginStatus == AuthHelper.LOGIN_NOTAVAILABLE) {
                    DispatcherModule.redirectToServiceNotAvailable(response);
                } else {
                    // error, redirect to login screen
                    DispatcherModule.redirectToDefaultDispatcher(response);
                }
            } else {
                // update last login date and register active user
                UserDeletionManager.getInstance().setIdentityAsActiv(identity);
                MediaResource mr = ureq.getDispatchResult().getResultingMediaResource();
                if (mr instanceof RedirectMediaResource) {
                    RedirectMediaResource rmr = (RedirectMediaResource) mr;
                    rmr.prepare(response);
                } else {
                    // error, redirect to login screen
                    DispatcherModule.redirectToDefaultDispatcher(response);
                }
            }
        }
    } catch (Exception e) {
        log.error("Unexpected error", e);
        error(ureq, translate(ureq, "error.generic"));
    }
}
Also used : AssertException(org.olat.core.logging.AssertException) HttpSession(javax.servlet.http.HttpSession) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Token(org.scribe.model.Token) OpenIDVerifier(org.olat.login.oauth.spi.OpenIDVerifier) Verifier(org.scribe.model.Verifier) AssertException(org.olat.core.logging.AssertException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) OAuthService(org.scribe.oauth.OAuthService) OAuthUser(org.olat.login.oauth.model.OAuthUser) OAuthRegistration(org.olat.login.oauth.model.OAuthRegistration) RedirectMediaResource(org.olat.core.gui.media.RedirectMediaResource) MediaResource(org.olat.core.gui.media.MediaResource) RedirectMediaResource(org.olat.core.gui.media.RedirectMediaResource) Identity(org.olat.core.id.Identity) UserRequest(org.olat.core.gui.UserRequest) UserRequestImpl(org.olat.core.gui.UserRequestImpl)

Example 4 with OAuthService

use of org.scribe.oauth.OAuthService in project openolat by klemens.

the class OAuthResource method redirect.

public static void redirect(OAuthSPI oauthProvider, HttpServletResponse httpResponse, HttpSession httpSession) {
    // Configure
    try {
        ServiceBuilder builder = new ServiceBuilder();
        builder.provider(oauthProvider.getScribeProvider()).apiKey(oauthProvider.getAppKey()).apiSecret(oauthProvider.getAppSecret());
        String[] scopes = oauthProvider.getScopes();
        for (String scope : scopes) {
            builder.scope(scope);
        }
        String callbackUrl = Settings.getServerContextPathURI() + OAuthConstants.CALLBACK_PATH;
        OAuthService service = builder.callback(callbackUrl).build();
        httpSession.setAttribute(OAuthConstants.OAUTH_SERVICE, service);
        httpSession.setAttribute(OAuthConstants.OAUTH_SPI, oauthProvider);
        if ("2.0".equals(service.getVersion())) {
            String redirectUrl = service.getAuthorizationUrl(null);
            saveStateAndNonce(httpSession, redirectUrl);
            httpResponse.sendRedirect(redirectUrl);
        } else {
            Token token = service.getRequestToken();
            httpSession.setAttribute(OAuthConstants.REQUEST_TOKEN, token);
            String redirectUrl = service.getAuthorizationUrl(token);
            httpResponse.sendRedirect(redirectUrl);
        }
    } catch (Exception e) {
        log.error("", e);
    }
}
Also used : OAuthService(org.scribe.oauth.OAuthService) Token(org.scribe.model.Token) ServiceBuilder(org.scribe.builder.ServiceBuilder)

Example 5 with OAuthService

use of org.scribe.oauth.OAuthService in project camel by apache.

the class YammerAccessCodeGenerator method main.

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Paste the consumerKey here");
    System.out.print(">>");
    String apiKey = in.nextLine();
    System.out.println("Paste the consumerSecret here");
    System.out.print(">>");
    String apiSecret = in.nextLine();
    OAuthService service = new ServiceBuilder().provider(YammerApi.class).apiKey(apiKey).apiSecret(apiSecret).build();
    String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
    System.out.println("Go and authorize your app here (eg. in a web browser):");
    System.out.println(authorizationUrl);
    System.out.println("... and paste the authorization code here");
    System.out.print(">>");
    Verifier verifier = new Verifier(in.nextLine());
    System.out.println();
    Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
    System.out.println("Your Access Token is: " + accessToken);
    System.out.println();
    in.close();
}
Also used : Scanner(java.util.Scanner) OAuthService(org.scribe.oauth.OAuthService) Token(org.scribe.model.Token) Verifier(org.scribe.model.Verifier) YammerApi(org.apache.camel.component.yammer.scribe.YammerApi) ServiceBuilder(org.scribe.builder.ServiceBuilder)

Aggregations

OAuthService (org.scribe.oauth.OAuthService)10 ServiceBuilder (org.scribe.builder.ServiceBuilder)6 Token (org.scribe.model.Token)6 IOException (java.io.IOException)3 Verifier (org.scribe.model.Verifier)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ServletException (javax.servlet.ServletException)2 HttpSession (javax.servlet.http.HttpSession)2 Test (org.junit.Test)2 UserRequest (org.olat.core.gui.UserRequest)2 UserRequestImpl (org.olat.core.gui.UserRequestImpl)2 MediaResource (org.olat.core.gui.media.MediaResource)2 RedirectMediaResource (org.olat.core.gui.media.RedirectMediaResource)2 Identity (org.olat.core.id.Identity)2 AssertException (org.olat.core.logging.AssertException)2 OAuthRegistration (org.olat.login.oauth.model.OAuthRegistration)2 OAuthUser (org.olat.login.oauth.model.OAuthUser)2 OpenIDVerifier (org.olat.login.oauth.spi.OpenIDVerifier)2 HashMap (java.util.HashMap)1 Map (java.util.Map)1