コード例 #1
0
ファイル: User.java プロジェクト: kevinrstewart/baasbox
 @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
 public static Result logoutWithDevice(String deviceId) throws SqlInjectionException {
   String token = (String) Http.Context.current().args.get("token");
   UserService.logout(deviceId);
   SessionTokenProvider.getSessionTokenProvider().removeSession(token);
   return noContent();
 }
コード例 #2
0
ファイル: User.java プロジェクト: endrelovas/baasbox
 @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
 public static Result logoutWithoutDevice() throws SqlInjectionException {
   String token = (String) Http.Context.current().args.get("token");
   if (!StringUtils.isEmpty(token))
     SessionTokenProvider.getSessionTokenProvider().removeSession(token);
   return ok("user logged out");
 }
コード例 #3
0
ファイル: User.java プロジェクト: kevinrstewart/baasbox
  /**
   * * Login the user. parameters: username password appcode: the App Code (API KEY) login_data:
   * json serialized string containing info related to the device used by the user. In particular,
   * for push notification, must by supplied: deviceId os: (android|ios)
   *
   * @return
   * @throws SqlInjectionException
   */
  @With({NoUserCredentialWrapFilter.class})
  @BodyParser.Of(BodyParser.FormUrlEncoded.class)
  public static Result login() throws SqlInjectionException {
    Map<String, String[]> body = request().body().asFormUrlEncoded();
    if (body == null) return badRequest("missing data: is the body x-www-form-urlencoded?");
    String username = "";
    String password = "";
    String appcode = "";
    String loginData = null;
    if (body.get("username") == null) return badRequest("The 'username' field is missing");
    else username = body.get("username")[0];
    if (body.get("password") == null) return badRequest("The 'password' field is missing");
    else password = body.get("password")[0];
    if (body.get("appcode") == null) return badRequest("The 'appcode' field is missing");
    else appcode = body.get("appcode")[0];
    Logger.debug("Username " + username);
    Logger.debug("Password " + password);
    Logger.debug("Appcode" + appcode);
    if (username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername())
        || username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername()))
      return forbidden(username + " cannot login");

    if (body.get("login_data") != null) loginData = body.get("login_data")[0];
    Logger.debug("LoginData" + loginData);

    /* other useful parameter to receive and to store...*/
    // validate user credentials
    OGraphDatabase db = null;
    try {
      db = DbHelper.open(appcode, username, password);
      if (loginData != null) {
        JsonNode loginInfo = null;
        try {
          loginInfo = Json.parse(loginData);
        } catch (Exception e) {
          Logger.debug("Error parsong login_data field");
          Logger.debug(ExceptionUtils.getFullStackTrace(e));
          return badRequest("login_data field is not a valid json string");
        }
        Iterator<Entry<String, JsonNode>> it = loginInfo.getFields();
        HashMap<String, Object> data = new HashMap<String, Object>();
        while (it.hasNext()) {
          Entry<String, JsonNode> element = it.next();
          String key = element.getKey();
          Object value = element.getValue().asText();
          data.put(key, value);
        }
        UserService.registerDevice(data);
      }
    } catch (OSecurityAccessException e) {
      Logger.debug("UserLogin: "******"user " + username + " unauthorized");
    } catch (InvalidAppCodeException e) {
      Logger.debug("UserLogin: "******"user " + username + " unauthorized");
    } finally {
      if (db != null && !db.isClosed()) db.close();
    }
    ImmutableMap<SessionKeys, ? extends Object> sessionObject =
        SessionTokenProvider.getSessionTokenProvider().setSession(appcode, username, password);
    response()
        .setHeader(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN));
    ObjectNode result = Json.newObject();
    result.put(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN));
    return ok(result);
  }
コード例 #4
0
ファイル: User.java プロジェクト: endrelovas/baasbox
  /**
   * * Login the user. parameters: username password appcode: the App Code (API KEY) login_data:
   * json serialized string containing info related to the device used by the user. In particular,
   * for push notification, must by supplied: deviceId os: (android|ios)
   *
   * @return
   * @throws SqlInjectionException
   * @throws IOException
   * @throws JsonProcessingException
   */
  @With({NoUserCredentialWrapFilter.class})
  public static Result login() throws SqlInjectionException, JsonProcessingException, IOException {
    String username = "";
    String password = "";
    String appcode = "";
    String loginData = null;

    RequestBody body = request().body();
    // BaasBoxLogger.debug ("Login called. The body is: {}", body);
    if (body == null)
      return badRequest(
          "missing data: is the body x-www-form-urlencoded or application/json? Detected: "
              + request().getHeader(CONTENT_TYPE));
    Map<String, String[]> bodyUrlEncoded = body.asFormUrlEncoded();
    if (bodyUrlEncoded != null) {
      if (bodyUrlEncoded.get("username") == null)
        return badRequest("The 'username' field is missing");
      else username = bodyUrlEncoded.get("username")[0];
      if (bodyUrlEncoded.get("password") == null)
        return badRequest("The 'password' field is missing");
      else password = bodyUrlEncoded.get("password")[0];
      if (bodyUrlEncoded.get("appcode") == null)
        return badRequest("The 'appcode' field is missing");
      else appcode = bodyUrlEncoded.get("appcode")[0];
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Username " + username);
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Password " + password);
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Appcode " + appcode);
      if (username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername())
          || username.equalsIgnoreCase(BBConfiguration.getBaasBoxUsername()))
        return forbidden(username + " cannot login");

      if (bodyUrlEncoded.get("login_data") != null) loginData = bodyUrlEncoded.get("login_data")[0];
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("LoginData" + loginData);
    } else {
      JsonNode bodyJson = body.asJson();
      if (bodyJson == null)
        return badRequest(
            "missing data : is the body x-www-form-urlencoded or application/json? Detected: "
                + request().getHeader(CONTENT_TYPE));
      if (bodyJson.get("username") == null) return badRequest("The 'username' field is missing");
      else username = bodyJson.get("username").asText();
      if (bodyJson.get("password") == null) return badRequest("The 'password' field is missing");
      else password = bodyJson.get("password").asText();
      if (bodyJson.get("appcode") == null) return badRequest("The 'appcode' field is missing");
      else appcode = bodyJson.get("appcode").asText();
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Username " + username);
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Password " + password);
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Appcode " + appcode);
      if (username.equalsIgnoreCase(BBConfiguration.getBaasBoxAdminUsername())
          || username.equalsIgnoreCase(BBConfiguration.getBaasBoxUsername()))
        return forbidden(username + " cannot login");

      if (bodyJson.get("login_data") != null) loginData = bodyJson.get("login_data").asText();
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("LoginData" + loginData);
    }
    /* other useful parameter to receive and to store...*/
    // validate user credentials
    ODatabaseRecordTx db = null;
    String user = null;
    try {
      db = DbHelper.open(appcode, username, password);
      user = prepareResponseToJson(UserService.getCurrentUser());

      if (loginData != null) {
        JsonNode loginInfo = null;
        try {
          loginInfo = Json.parse(loginData);
        } catch (Exception e) {
          if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Error parsong login_data field");
          if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug(ExceptionUtils.getFullStackTrace(e));
          return badRequest("login_data field is not a valid json string");
        }
        Iterator<Entry<String, JsonNode>> it = loginInfo.fields();
        HashMap<String, Object> data = new HashMap<String, Object>();
        while (it.hasNext()) {
          Entry<String, JsonNode> element = it.next();
          String key = element.getKey();
          Object value = element.getValue().asText();
          data.put(key, value);
        }
        UserService.registerDevice(data);
      }
    } catch (OSecurityAccessException e) {
      if (BaasBoxLogger.isDebugEnabled())
        BaasBoxLogger.debug("UserLogin: "******"user " + username + " unauthorized");
    } catch (InvalidAppCodeException e) {
      if (BaasBoxLogger.isDebugEnabled())
        BaasBoxLogger.debug("UserLogin: "******"user " + username + " unauthorized");
    } finally {
      if (db != null && !db.isClosed()) db.close();
    }
    ImmutableMap<SessionKeys, ? extends Object> sessionObject =
        SessionTokenProvider.getSessionTokenProvider().setSession(appcode, username, password);
    response()
        .setHeader(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN));

    ObjectMapper mapper = new ObjectMapper();
    user =
        user.substring(0, user.lastIndexOf("}"))
            + ",\""
            + SessionKeys.TOKEN.toString()
            + "\":\""
            + (String) sessionObject.get(SessionKeys.TOKEN)
            + "\"}";
    JsonNode jn = mapper.readTree(user);

    return ok(jn);
  }
コード例 #5
0
ファイル: User.java プロジェクト: endrelovas/baasbox
  @With({AdminCredentialWrapFilter.class, ConnectToDBFilter.class})
  @BodyParser.Of(BodyParser.Json.class)
  public static Result signUp() throws JsonProcessingException, IOException {
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method Start");
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("signUp bodyJson: " + bodyJson);
    if (bodyJson == null)
      return badRequest(
          "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json");
    // check and validate input
    if (!bodyJson.has("username")) return badRequest("The 'username' field is missing");
    if (!bodyJson.has("password")) return badRequest("The 'password' field is missing");

    // extract mandatory fields
    JsonNode nonAppUserAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_ANONYMOUS_USER);
    JsonNode privateAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER);
    JsonNode friendsAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_FRIENDS_USER);
    JsonNode appUsersAttributes = bodyJson.get(UserDao.ATTRIBUTES_VISIBLE_BY_REGISTERED_USER);
    String username = (String) bodyJson.findValuesAsText("username").get(0);
    String password = (String) bodyJson.findValuesAsText("password").get(0);
    String appcode = (String) ctx().args.get("appcode");
    if (privateAttributes != null && privateAttributes.has("email")) {
      // check if email address is valid
      if (!Util.validateEmail((String) privateAttributes.findValuesAsText("email").get(0)))
        return badRequest("The email address must be valid.");
    }
    if (StringUtils.isEmpty(password)) return status(422, "The password field cannot be empty");

    // try to signup new user
    ODocument profile = null;
    try {
      UserService.signUp(
          username,
          password,
          null,
          nonAppUserAttributes,
          privateAttributes,
          friendsAttributes,
          appUsersAttributes,
          false);
      // due to issue 412, we have to reload the profile
      profile = UserService.getUserProfilebyUsername(username);
    } catch (InvalidJsonException e) {
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("signUp", e);
      return badRequest("One or more profile sections is not a valid JSON object");
    } catch (UserAlreadyExistsException e) {
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("signUp", e);
      // Return a generic error message if the username is already in use.
      return badRequest("Error signing up");
    } catch (EmailAlreadyUsedException e) {
      // Return a generic error message if the email is already in use.
      if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("signUp", e);
      return badRequest("Error signing up");
    } catch (Throwable e) {
      BaasBoxLogger.warn("signUp", e);
      if (Play.isDev()) return internalServerError(ExceptionUtils.getFullStackTrace(e));
      else return internalServerError(ExceptionUtils.getMessage(e));
    }
    if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method End");
    ImmutableMap<SessionKeys, ? extends Object> sessionObject =
        SessionTokenProvider.getSessionTokenProvider().setSession(appcode, username, password);
    response()
        .setHeader(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN));

    String result = prepareResponseToJson(profile);
    ObjectMapper mapper = new ObjectMapper();
    result =
        result.substring(0, result.lastIndexOf("}"))
            + ",\""
            + SessionKeys.TOKEN.toString()
            + "\":\""
            + (String) sessionObject.get(SessionKeys.TOKEN)
            + "\"}";
    JsonNode jn = mapper.readTree(result);

    return created(jn);
  }