Exemplo n.º 1
0
  @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 Body getVerifyEmailMailingBodyAfterSignup(String token, User user, Context ctx) {

    boolean isSecure = getConfiguration().getBoolean(SETTING_KEY_VERIFICATION_LINK_SECURE);
    String url = routes.Signup.verify(token).absoluteURL(ctx.request(), isSecure);

    Lang lang = Lang.preferred(ctx.request().acceptLanguages());
    String langCode = lang.code();

    String html =
        getEmailTemplate(
            "views.html.account.email.verify_email",
            langCode,
            url,
            token,
            user.getName(),
            user.getEmail());
    String text =
        getEmailTemplate(
            "views.txt.account.email.verify_email",
            langCode,
            url,
            token,
            user.getName(),
            user.getEmail());

    return new Body(text, html);
  }
Exemplo n.º 3
0
  @Override
  public Result call(Context context) throws Throwable {

    String authHeader = context.request().getHeader(AUTHORIZATION);
    if (authHeader == null) {
      return sendAuthRequest(context);
    }

    String auth = authHeader.substring(6);

    byte[] decodedAuth = Base64.decode(auth);
    String[] credString = new String(decodedAuth, "UTF-8").split(":");

    if (credString == null || credString.length != 2) {
      return sendAuthRequest(context);
    }

    String username = credString[0];
    String password = credString[1];
    User authUser = User.authenticate(username, password);
    if (authUser == null) {
      return sendAuthRequest(context);
    }
    context.request().setUsername(username);
    return delegate.call(context);
  }
  protected Body getPasswordResetMailingBody(String token, User user, Context ctx) {

    boolean isSecure = getConfiguration().getBoolean(SETTING_KEY_PASSWORD_RESET_LINK_SECURE);
    String url = routes.Signup.resetPassword(token).absoluteURL(ctx.request(), isSecure);

    Lang lang = Lang.preferred(ctx.request().acceptLanguages());
    String langCode = lang.code();

    String html =
        getEmailTemplate(
            "views.html.account.email.password_reset",
            langCode,
            url,
            token,
            user.getName(),
            user.getEmail());
    String text =
        getEmailTemplate(
            "views.txt.account.email.password_reset",
            langCode,
            url,
            token,
            user.getName(),
            user.getEmail());

    return new Body(text, html);
  }
Exemplo n.º 5
0
 /*
  * (non-Javadoc)
  *
  * @see
  * com.ssachtleben.play.plugin.auth.providers.BaseProvider#handle(play.mvc
  * .Http.Context)
  */
 @Override
 protected AuthUser handle(Context context) {
   String contentType = context.request().getHeader("content-type");
   if ("application/json".equals(contentType)) {
     JsonNode node = context.request().body().asJson();
     return new PasswordEmailAuthUser(
         node.get(RequestParameter.EMAIL).asText(),
         node.get(RequestParameter.PASSWORD).asText(),
         node);
   } else {
     Map<String, String[]> params = context.request().body().asFormUrlEncoded();
     if (params != null
         && params.containsKey(RequestParameter.EMAIL)
         && params.containsKey(RequestParameter.PASSWORD)) {
       ObjectMapper mapper = new ObjectMapper();
       JsonNode data;
       try {
         data = mapper.readTree(mapper.writeValueAsString(params));
       } catch (IOException e) {
         logger().error("Failed to serialize params to json", e);
         data = mapper.createObjectNode();
       }
       return new PasswordEmailAuthUser(
           params.get(RequestParameter.EMAIL)[0], params.get(RequestParameter.PASSWORD)[0], data);
     }
   }
   return null;
 }
Exemplo n.º 6
0
 @Test
 public void testSession() {
   Application app = new GuiceApplicationBuilder().build();
   Play.start(app);
   Context ctx =
       new Context(new RequestBuilder().session("a", "1").session("b", "1").session("b", "2"));
   assertEquals("1", ctx.session().get("a"));
   assertEquals("2", ctx.session().get("b"));
   Play.stop(app);
 }
Exemplo n.º 7
0
 public PlayWebContext(final Context context, final SessionStore sessionStore) {
   this.context = context;
   this.request = context.request();
   this.response = context.response();
   this.session = context.session();
   if (sessionStore == null) {
     this.sessionStore = new PlayCacheStore();
   } else {
     this.sessionStore = sessionStore;
   }
 }
Exemplo n.º 8
0
  /**
   * Build the action context from the Play {@link Context} and the {@link RequiresAuthentication}
   * annotation.
   *
   * @param ctx the Play context.
   * @param configuration the configuration.
   * @return
   */
  public static ActionContext build(Context ctx, Object configuration) {
    JavaWebContext context = new JavaWebContext(ctx.request(), ctx.response(), ctx.session());
    String clientName = null;
    String targetUrl = "";
    Boolean isAjax = false;
    Boolean stateless = false;
    String requireAnyRole = "";
    String requireAllRoles = "";

    if (configuration != null) {
      try {
        final InvocationHandler invocationHandler = Proxy.getInvocationHandler(configuration);
        clientName = (String) invocationHandler.invoke(configuration, clientNameMethod, null);
        targetUrl = (String) invocationHandler.invoke(configuration, targetUrlMethod, null);
        logger.debug("targetUrl : {}", targetUrl);
        isAjax = (Boolean) invocationHandler.invoke(configuration, isAjaxMethod, null);
        logger.debug("isAjax : {}", isAjax);
        stateless = (Boolean) invocationHandler.invoke(configuration, statelessMethod, null);
        logger.debug("stateless : {}", stateless);
        requireAnyRole =
            (String) invocationHandler.invoke(configuration, requireAnyRoleMethod, null);
        logger.debug("requireAnyRole : {}", requireAnyRole);
        requireAllRoles =
            (String) invocationHandler.invoke(configuration, requireAllRolesMethod, null);
        logger.debug("requireAllRoles : {}", requireAllRoles);
      } catch (Throwable e) {
        logger.error("Error during configuration retrieval", e);
        throw new TechnicalException(e);
      }
    }
    clientName =
        (clientName != null)
            ? clientName
            : context.getRequestParameter(Config.getClients().getClientNameParameter());
    logger.debug("clientName : {}", clientName);
    String sessionId = (stateless) ? null : StorageHelper.getOrCreationSessionId(ctx.session());

    return new ActionContext(
        ctx,
        ctx.request(),
        sessionId,
        context,
        clientName,
        targetUrl,
        isAjax,
        stateless,
        requireAnyRole,
        requireAllRoles);
  }
  @Override
  public F.Promise<SimpleResult> call(Context ctx) throws Throwable {
    if (Logger.isTraceEnabled()) Logger.trace("Method Start");
    Context.current.set(ctx);

    if (Logger.isDebugEnabled())
      Logger.debug("AnonymousLogin  for resource " + Context.current().request());

    String user = BBConfiguration.getBaasBoxUsername();
    String password = BBConfiguration.getBaasBoxPassword();

    // retrieve AppCode
    String appCode = RequestHeaderHelper.getAppCode(ctx);

    ctx.args.put("username", user);
    ctx.args.put("password", password);
    ctx.args.put("appcode", appCode);

    if (Logger.isDebugEnabled()) Logger.debug("username (defined in conf file): " + user);
    if (Logger.isDebugEnabled()) Logger.debug("password (defined in conf file): " + password);
    if (Logger.isDebugEnabled()) Logger.debug("appcode (from header or querystring): " + appCode);
    if (Logger.isDebugEnabled()) Logger.debug("token: N/A");

    // executes the request
    F.Promise<SimpleResult> tempResult = delegate.call(ctx);

    WrapResponse wr = new WrapResponse();
    // SimpleResult result=wr.wrap(ctx, tempResult);
    F.Promise<SimpleResult> result = wr.wrapAsync(ctx, tempResult);
    if (Logger.isTraceEnabled()) Logger.trace("Method End");
    return result;
  }
Exemplo n.º 10
0
  @Override
  public Promise<SimpleResult> call(Context ctx) throws Throwable {

    Promise<SimpleResult> ret = null;

    // redirect if it's not secure
    if (!isHttpsRequest(ctx.request())) {
      String url = redirectHostHttps(ctx) + ctx.request().uri();
      ret = Promise.pure(redirect(url));
    } else {
      // Let request proceed.
      ret = delegate.call(ctx);
    }

    return ret;
  }
Exemplo n.º 11
0
 public CompletionStage<Result> call(final Context ctx) {
   Authenticator authenticator = injector.instanceOf(configuration.value());
   String username = authenticator.getUsername(ctx);
   if (username == null) {
     Result unauthorized = authenticator.onUnauthorized(ctx);
     return CompletableFuture.completedFuture(unauthorized);
   } else {
     try {
       ctx.request().setUsername(username);
       return delegate
           .call(ctx)
           .whenComplete((result, error) -> ctx.request().setUsername(null));
     } catch (Exception e) {
       ctx.request().setUsername(null);
       throw e;
     }
   }
 }
 @Override
 protected String onLoginUserNotFound(Context context) {
   context
       .flash()
       .put(
           controllers.Application.FLASH_ERROR_KEY,
           Messages.get("playauthenticate.password.login.unknown_user_or_pw"));
   return super.onLoginUserNotFound(context);
 }
Exemplo n.º 13
0
 public Result call(Context ctx) {
   try {
     Authenticator authenticator = configuration.value().newInstance();
     String username = authenticator.getUsername(ctx);
     if (username == null) {
       return authenticator.onUnauthorized(ctx);
     } else {
       try {
         ctx.request().setUsername(username);
         return deleguate.call(ctx);
       } finally {
         ctx.request().setUsername(null);
       }
     }
   } catch (RuntimeException e) {
     throw e;
   } catch (Throwable t) {
     throw new RuntimeException(t);
   }
 }
Exemplo n.º 14
0
  @Override
  public final Result call(Context context) throws Throwable {
    PathParser parser = new PathParser(context);
    String ownerLoginId = parser.getOwnerLoginId();
    String projectName = parser.getProjectName();

    Project project = Project.findByOwnerAndProjectName(ownerLoginId, projectName);

    if (project == null) {
      return AccessLogger.log(
          context.request(), notFound(ErrorViews.NotFound.render("error.notfound.project")), null);
    }

    if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) {
      return AccessLogger.log(
          context.request(), notFound(ErrorViews.NotFound.render("error.notfound.project")), null);
    }

    return call(project, context, parser);
  }
Exemplo n.º 15
0
  public static String redirectHostHttps(Context ctx) {

    String[] pieces = ctx.request().host().split(":");
    String ret = "https://" + pieces[0];

    // In Dev mode we want to append the port.
    // In Prod mode, no need to append the port as we use the standard https port, 443.
    if (isDev()) {
      ret += ":" + getHttpsPort();
    }

    return ret;
  }
  @Override
  public Promise<Result> call(Context ctx) throws Throwable {
    String accessToken = ctx.request().getHeader("x-access-token");
    if (accessToken != null) {
      // Check RateLimit
      Logger.debug("Checking for token RateLimit. token:" + accessToken);
      if (!RateLimitAgent.isRateOverLimit(accessToken)) {
        return Promise.<Result>pure(badRequest("Over RateLimit. Account temporaly suspended"));
      }
    } else {
      return Promise.<Result>pure(badRequest("Authentication need"));
    }

    return delegate.call(ctx);
  }
Exemplo n.º 17
0
  private boolean checkPermission(
      Subject roleHolder, Class<? extends RequestPermission> permissionClass, Context ctx) {
    if (log.isDebugEnabled()) log.debug("checkPermission() <-");

    RequestPermission permission = null;
    try {
      permission = permissionClass.newInstance();
    } catch (Exception e) {
      log.error("cannot create permission", e);
      return false;
    }

    List<? extends Permission> permissions = roleHolder.getPermissions();

    Request request = ctx.request();
    if (log.isDebugEnabled()) log.debug("request : " + request);
    String path = request.path();
    if (log.isDebugEnabled()) log.debug("path : " + path);
    return permission.isAllowed(request, permissions);
  }
Exemplo n.º 18
0
 @Override
 public String getUsername(Context ctx) {
   return ctx.session().get("email");
 }
Exemplo n.º 19
0
 /**
  * Retrieves the username from the HTTP context; the default is to read from the session cookie.
  *
  * @return null if the user is not authenticated.
  */
 public String getUsername(Context ctx) {
   return ctx.session().get("username");
 }
Exemplo n.º 20
0
 /**
  * Update the SSO language so that it is aligned with the specified language.<br>
  * The SSO language is the one used for the login & logout page.
  *
  * @param ctx a Context (play meaning)
  * @param languageCode a language code (en, fr, de)
  */
 public static void setSsoLanguage(Context ctx, String languageCode) {
   // For CAS, the language is stored in a cookie
   // To "update" this cookie we have to override it with a different value
   ctx.response().setCookie(CAS_SSO_LANGUAGE_COOKIE, languageCode);
 }
Exemplo n.º 21
0
 private Result sendAuthRequest(Context context) {
   context.response().setHeader(WWW_AUTHENTICATE, REALM);
   return unauthorized();
 }
Exemplo n.º 22
0
 @Override
 public String getUsername(Context context) {
   AppLogUtil.debug("@@@@@StudentSecured#getUsername");
   return context.session().get("entry_user_id");
 }
Exemplo n.º 23
0
 @Test
 public void testFlash() {
   Context ctx = new Context(new RequestBuilder().flash("a", "1").flash("b", "1").flash("b", "2"));
   assertEquals("1", ctx.flash().get("a"));
   assertEquals("2", ctx.flash().get("b"));
 }
Exemplo n.º 24
0
 @Override
 public Result onUnauthorized(Context ctx) {
   return redirect(controllers.routes.Authentication.login(UIUtil.urlEncode(ctx.request())));
 }
Exemplo n.º 25
0
 @Override
 public String getUsername(Context ctx) {
   String cookieValue = ctx.session().get(Application.PASSWORD);
   return validate(cookieValue) ? "okay" : null;
 }
Exemplo n.º 26
0
 public static String getIP(Context ctx) {
   return ctx.request().remoteAddress();
 }