@Override public Object authenticate(final Context context, final Object payload) throws AuthException { final Request request = context.request(); final String uri = request.uri(); if (Logger.isDebugEnabled()) { Logger.debug("Returned with URL: '" + uri + "'"); } final Configuration c = getConfiguration(); final ConsumerKey key = new ConsumerKey( c.getString(SettingKeys.CONSUMER_KEY), c.getString(SettingKeys.CONSUMER_SECRET)); final String requestTokenURL = c.getString(SettingKeys.REQUEST_TOKEN_URL); final String accessTokenURL = c.getString(SettingKeys.ACCESS_TOKEN_URL); final String authorizationURL = c.getString(SettingKeys.AUTHORIZATION_URL); final ServiceInfo info = new ServiceInfo(requestTokenURL, accessTokenURL, authorizationURL, key); final OAuth service = new OAuth(info, true); checkError(request); if (uri.contains(Constants.OAUTH_VERIFIER)) { final RequestToken rtoken = (RequestToken) PlayAuthenticate.removeFromCache(context.session(), CACHE_TOKEN); final String verifier = Authenticate.getQueryString(request, Constants.OAUTH_VERIFIER); final Either<OAuthException, RequestToken> retrieveAccessToken = service.retrieveAccessToken(rtoken, verifier); if (retrieveAccessToken.isLeft()) { throw new AuthException(retrieveAccessToken.left().get().getLocalizedMessage()); } else { final I i = buildInfo(retrieveAccessToken.right().get()); return transform(i); } } else { final String callbackURL = getRedirectUrl(request); final Either<OAuthException, RequestToken> reponse = service.retrieveRequestToken(callbackURL); if (reponse.isLeft()) { // Exception happened throw new AuthException(reponse.left().get().getLocalizedMessage()); } else { // All good, we have the request token final RequestToken rtoken = reponse.right().get(); final String token = rtoken.token(); final String redirectUrl = service.redirectUrl(token); PlayAuthenticate.storeInCache(context.session(), CACHE_TOKEN, rtoken); return redirectUrl; } } }
protected OAuthCalculator getOAuthCalculator(final OAuth1AuthInfo info) { final RequestToken token = new RequestToken(info.getAccessToken(), info.getAccessTokenSecret()); final Configuration c = getConfiguration(); final ConsumerKey cK = new ConsumerKey( c.getString(SettingKeys.CONSUMER_KEY), c.getString(SettingKeys.CONSUMER_SECRET)); final OAuthCalculator op = new OAuthCalculator(cK, token); return op; }
public static String getValueStr(String name) { Configuration root = Configuration.root(); if (root == null || root.getString(name) == null) { return null; } String value = root.getString(name); Logger.info(name + ":" + value); return value; }
public static Result writeMail(String errorMessage, boolean sended) { Configuration config = play.Play.application().configuration(); List<String> notConfiguredItems = new ArrayList<String>(); String[] requiredItems = {"smtp.host", "smtp.user", "smtp.password"}; for (String key : requiredItems) { if (config.getString(key) == null) { notConfiguredItems.add(key); } } String sender = config.getString("smtp.user"); return ok(mail.render("title.sendMail", notConfiguredItems, sender, errorMessage, sended)); }
private static void startStream(List<String> terms) throws TwitterException { if (twitter != null) { twitter.cleanUp(); } if (esClient != null) { esClient.close(); esClient = null; } play.Configuration pconf = Play.application().configuration(); String elasticSearchCluster = pconf.getString("tweet.elasticsearch.cluster.name"); if (elasticSearchCluster != null) { Logger.info("Configuring ElasticSearch..."); Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", elasticSearchCluster).build(); esClient = new TransportClient(settings) .addTransportAddress( new InetSocketTransportAddress( pconf.getString("tweet.elasticsearch.transport.host"), pconf.getInt("tweet.elasticsearch.transport.port"))); } else { esClient = null; } twitter4j.conf.Configuration tconf = Application.getTwitterConfiguration(); TwitterStreamFactory tf = new TwitterStreamFactory(tconf); twitter = tf.getInstance(); StatusListener l = new TweetListener( terms, esClient, pconf.getString("tweet.elasticsearch.index"), pconf.getString("tweet.elasticsearch.type")); twitter.addListener(l); String[] tracks = new String[terms.size()]; StringBuffer termsString = new StringBuffer(); for (int i = 0; i < terms.size(); i++) { tracks[i] = terms.get(i); if (i != 0) termsString.append(","); termsString.append(terms.get(i)); } FilterQuery q = new FilterQuery().track(tracks); twitter.filter(q); Logger.info("Starting listening for tweets using terms " + termsString.toString() + "..."); }
/** * This handles the login form submission for the Web IDE. * * @return The result of rendering the page. */ @AddCSRFToken @RequireCSRFCheck @Transactional public CompletionStage<Result> login() { Form<LoginForm> userForm = myFormFactory.form(LoginForm.class).bindFromRequest(); // Perform the basic validation checks. if (userForm.hasErrors()) { // Render the page with the login form with the errors fields String token = CSRF.getToken(request()).map(t -> t.value()).orElse("no token"); return CompletableFuture.supplyAsync( () -> badRequest(index.render(userForm, token)), myHttpExecutionContext.current()); } else { LoginForm form = userForm.get(); // Check for a registered user with the same email. // Note that "connect" expects a JPA entity manager, // which is not present if we don't wrap the call using // "withTransaction()". User user = myJpaApi.withTransaction(() -> User.connect(form.getEmail(), form.getPassword())); if (user != null) { // Check to see if this account has been authenticated or not. boolean hasAuthenticated = myJpaApi.withTransaction(() -> User.hasAuthenticated(form.getEmail())); if (hasAuthenticated) { // Update the login date final User updatedUser = myJpaApi.withTransaction(() -> User.lastLogin(form.getEmail())); // Add a new user event myJpaApi.withTransaction(() -> UserEvent.addRegularEvent("login", "", updatedUser)); // Stores the email as session value session("connected", form.getEmail()); // Obtain the http context from the configuration file String context = myConfiguration.getString("play.http.context"); if (context == null) { context = ""; } // Redirect back to the home page final String finalContext = context; return CompletableFuture.supplyAsync( () -> redirect(finalContext + "/"), myHttpExecutionContext.current()); } else { // Render the not authenticated page return CompletableFuture.supplyAsync( () -> ok(notAuthenticated.render(form.getEmail())), myHttpExecutionContext.current()); } } else { // The email and/or password does not match, so we add a new validation error. userForm.reject(new ValidationError("loginError", "Could not login.")); // Render the page with the login form with the errors fields String token = CSRF.getToken(request()).map(t -> t.value()).orElse("no token"); return CompletableFuture.supplyAsync( () -> badRequest(index.render(userForm, token)), myHttpExecutionContext.current()); } } }
@Inject public MorphiumConnection(ApplicationLifecycle lifecycle, Configuration configuration) { final String dbName = configuration.getString("mongodb.name"); final String dbHostName = configuration.getString("mongodb.host.name"); final Integer dbHostPort = configuration.getInt("mongodb.host.port"); final String username = configuration.getString("mongodb.username"); final String password = configuration.getString("mongodb.password"); Logger.info( "Mong db name: " + dbName + ", host : " + dbHostName + ", port : " + dbHostPort + ", username:"******", passsword:" + password); cfg = new MorphiumConfig(); cfg.setDatabase(dbName); try { cfg.addHost(dbHostName, dbHostPort); if (StringUtils.isNotEmpty(username)) { cfg.setMongoLogin(username); } if (StringUtils.isNotEmpty(password)) { cfg.setMongoPassword(password); } m = new Morphium(cfg); } catch (UnknownHostException e) { e.printStackTrace(); m = null; cfg = null; } lifecycle.addStopHook( () -> { if (m != null) { m.close(); } return F.Promise.pure(null); }); }
private List<NameValuePair> getRequestTokenParams(final Request request, final Configuration c) { final List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add( new BasicNameValuePair( PocketConstants.CONSUMER_KEY, c.getString(SettingKeys.CONSUMER_KEY))); params.add(new BasicNameValuePair(getRedirectUriKey(), getRedirectUrl(request))); return params; }
/* * 시스템 설정에서 가입 승인 여부 조회 */ private static boolean isUseSignUpConfirm() { Configuration config = play.Play.application().configuration(); String useSignUpConfirm = config.getString("signup.require.confirm"); if (useSignUpConfirm != null && useSignUpConfirm.equals("true")) { return true; } else { return false; } }
@Inject public AmazonS3Storage(Configuration configuration) { bucketName = configuration.getString("storage.s3.bucket"); String accessKey = configuration.getString("storage.s3.accesskey"); String secretKey = configuration.getString("storage.s3.secretkey"); credentials = new BasicAWSCredentials(accessKey, secretKey); AmazonS3 amazonS3 = new AmazonS3Client(credentials); try { if (!(amazonS3.doesBucketExist(bucketName))) { amazonS3.createBucket(new CreateBucketRequest(bucketName)); } String bucketLocation = amazonS3.getBucketLocation(new GetBucketLocationRequest(bucketName)); Logger.info("Amazon S3 bucket created at " + bucketLocation); } catch (AmazonServiceException ase) { Logger.error( "Caught an AmazonServiceException, which " + "means your request made it " + "to Amazon S3, but was rejected with an error response " + "for some reason." + " Error Message: " + ase.getMessage() + " HTTP Status Code: " + ase.getStatusCode() + " AWS Error Code: " + ase.getErrorCode() + " Error Type: " + ase.getErrorType() + " Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { Logger.error( "Caught an AmazonClientException, which " + "means the client encountered " + "an internal error while trying to " + "communicate with S3, " + "such as not being able to access the network." + " Error Message: " + ace.getMessage()); } }
@Override protected String getAccessTokenParams( final Configuration c, final String code, final Request request) { final List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add( new BasicNameValuePair( PocketConstants.CONSUMER_KEY, c.getString(SettingKeys.CONSUMER_KEY))); params.add(new BasicNameValuePair(Constants.CODE, code)); return URLEncodedUtils.format(params, "UTF-8"); }
/** This handles the logout action for the Web IDE. */ public Result logout() { // Clear the session session().clear(); // Obtain the http context from the configuration file String context = myConfiguration.getString("play.http.context"); if (context == null) { context = ""; } return redirect(context + "/"); }
private String getRequestToken(final Request request) throws AuthException { final Configuration c = getConfiguration(); final List<NameValuePair> params = getRequestTokenParams(request, c); final Response r = WS.url(c.getString(SettingKeys.REQUEST_TOKEN_URL)) .setHeader("Content-Type", "application/json") .setHeader("X-Accept", "application/json") .post(encodeParamsAsJson(params)) .get(getTimeout()); if (r.getStatus() >= 400) { throw new AuthException(r.asJson().asText()); } else { return r.asJson().get(PocketConstants.CODE).asText(); } }
/** * This renders the login page for the Web IDE. * * @return The result of rendering the page. */ @AddCSRFToken public Result index() { // Check the session to see if the request comes from an user // that has logged in already. String user = session().remove("connected"); if (user != null) { // Obtain the http context from the configuration file String context = myConfiguration.getString("play.http.context"); if (context == null) { context = ""; } // Redirect back to the home page return redirect(context + "/"); } else { // Render the page with the login form String token = CSRF.getToken(request()).map(t -> t.value()).orElse("no token"); return ok(index.render(myFormFactory.form(LoginForm.class), token)); } }
@Override protected List<NameValuePair> getAuthParams( final Configuration c, final Request request, final String state) throws AuthException { final List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add( new BasicNameValuePair( PocketConstants.CONSUMER_KEY, c.getString(SettingKeys.CONSUMER_KEY))); final String requestToken = this.getRequestToken(request); params.add(new BasicNameValuePair(PocketConstants.REQUEST_TOKEN, requestToken)); if (state != null) { params.add(new BasicNameValuePair(PocketConstants.STATE, state)); } // with this we fake the response to contain the response to Play! // Authenticate to contain the request token in the "code" parameter final String redirectUrl = getRedirectUrl( request, Arrays.asList(new BasicNameValuePair(PocketConstants.CODE, requestToken))); params.add(new BasicNameValuePair(getRedirectUriKey(), redirectUrl)); return params; }
@Override public void onStart() { if (!isEnabled) { return; } // Register SLF4JLogrImplFactory as Logger // @see http://nesbot.com/2011/11/28/play-2-morphia-logging-error MorphiaLoggerFactory.reset(); MorphiaLoggerFactory.registerLogger(SLF4JLogrImplFactory.class); try { Configuration morphiaConf = Configuration.root().getConfig(ConfigKey.PREFIX); if (morphiaConf == null) { throw Configuration.root() .reportError(ConfigKey.PREFIX, "Missing Morphia configuration", null); } MorphiaLogger.debug(morphiaConf); String dbName = morphiaConf.getString(ConfigKey.DB_NAME.getKey()); if (StringUtils.isBlank(dbName)) { throw morphiaConf.reportError( ConfigKey.DB_NAME.getKey(), "Missing Morphia configuration", null); } // Connect to MongoDB String seeds = morphiaConf.getString(ConfigKey.DB_SEEDS.getKey()); if (StringUtils.isNotBlank(seeds)) { mongo = connect(seeds); } else { mongo = connect( morphiaConf.getString(ConfigKey.DB_HOST.getKey()), morphiaConf.getString(ConfigKey.DB_PORT.getKey())); } morphia = new Morphia(); // To prevent problem during hot-reload if (application.isDev()) { morphia.getMapper().getOptions().objectFactory = new PlayCreator(); } // Configure validator new ValidationExtension(morphia); // Check if credentials parameters are present String username = morphiaConf.getString(ConfigKey.DB_USERNAME.getKey()); String password = morphiaConf.getString(ConfigKey.DB_PASSWORD.getKey()); if (StringUtils.isNotBlank(username) ^ StringUtils.isNotBlank(password)) { throw morphiaConf.reportError( ConfigKey.DB_NAME.getKey(), "Missing username or password", null); } // Create datastore if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) { ds = morphia.createDatastore(mongo, dbName, username, password.toCharArray()); } else { ds = morphia.createDatastore(mongo, dbName); } MorphiaLogger.debug("Datastore [%s] created", dbName); // Create GridFS String uploadCollection = morphiaConf.getString(ConfigKey.COLLECTION_UPLOADS.getKey()); if (StringUtils.isBlank(dbName)) { uploadCollection = "uploads"; MorphiaLogger.warn( "Missing Morphia configuration key [%s]. Use default value instead [%s]", ConfigKey.COLLECTION_UPLOADS, "uploads"); } gridfs = new GridFS(ds.getDB(), uploadCollection); MorphiaLogger.debug("GridFS created", ""); MorphiaLogger.debug("Add Interceptor...", ""); morphia .getMapper() .addInterceptor( new AbstractEntityInterceptor() { @Override public void postLoad(final Object ent, final DBObject dbObj, final Mapper mapr) { if (ent instanceof Model) { Model m = (Model) ent; m._post_Load(); } } }); MorphiaLogger.debug("Classes mapping...", ""); mapClasses(); MorphiaLogger.debug("End of initializing Morphia", ""); } catch (MongoException e) { MorphiaLogger.error(e, "Problem connecting MongoDB"); throw new RuntimeException(e); } catch (ClassNotFoundException e) { MorphiaLogger.error(e, "Problem mapping class"); throw new RuntimeException(e); } }
@Override public void onReceive(Object message) throws Exception { if (message instanceof ConfiguredChildActorProtocol.GetConfig) { sender().tell(configuration.getString(key), self()); } }