@BeforeClass public static void initTestser() { running( fakeApplication(), () -> { try { DbHelper.open("1234567890", "admin", "admin"); ODocument user = UserService.signUp(TEST_USER, TEST_USER, new Date(), null, null, null, null, false); assertNotNull(user); ODocument alt = UserService.signUp( TEST_ALT_USER, TEST_ALT_USER, new Date(), null, null, null, null, false); assertNotNull(alt); CollectionService.create(TEST_COLLECTION); DbHelper.close(DbHelper.getConnection()); DbHelper.open("1234567890", TEST_USER, TEST_USER); sGenIds = createRandomDocuments(10); DbHelper.close(DbHelper.getConnection()); } catch (Throwable e) { fail(ExceptionUtils.getFullStackTrace(e)); } finally { DbHelper.close(DbHelper.getConnection()); } }); }
public static void createDefaultUsers() { try { // the baasbox default user used to connect to the DB like anonymous user String username = BBConfiguration.getBaasBoxUsername(); String password = BBConfiguration.getBaasBoxPassword(); UserService.signUp( username, password, new Date(), DefaultRoles.ANONYMOUS_USER.toString(), null, null, null, null, false); // the baasbox default user used to act internally as the administrator username = BBConfiguration.getBaasBoxAdminUsername(); password = BBConfiguration.getBaasBoxAdminPassword(); UserService.signUp( username, password, new Date(), DefaultRoles.ADMIN.toString(), null, null, null, null, false); moveUserToRole("admin", DefaultRoles.BASE_ADMIN.toString(), DefaultRoles.ADMIN.toString()); } catch (Exception e) { throw new RuntimeException(e); } }
@With({UserCredentialWrapFilter.class, ConnectToDBFilter.class}) public static Result follow(String toFollowUsername) { String currentUsername = DbHelper.currentUsername(); try { UserService.getOUserByUsername(currentUsername); } catch (Exception e) { return internalServerError(ExceptionUtils.getMessage(e)); } try { ODocument followed = FriendShipService.follow(currentUsername, toFollowUsername); return created(prepareResponseToJson(followed)); } catch (UserToFollowNotExistsException e) { return notFound(ExceptionUtils.getMessage(e)); } catch (UserNotFoundException e) { return internalServerError(ExceptionUtils.getMessage(e)); } catch (AlreadyFriendsException e) { return badRequest(ExceptionUtils.getMessage(e)); } catch (SqlInjectionException e) { return badRequest( "The username " + toFollowUsername + " is not a valid username. HINT: check if it contains invalid character, the server has encountered a possible SQL Injection attack"); } catch (IllegalArgumentException e) { return badRequest(ExceptionUtils.getMessage(e)); } catch (Exception e) { return internalServerError(ExceptionUtils.getMessage(e)); } }
@With({UserCredentialWrapFilter.class, ConnectToDBFilter.class}) @BodyParser.Of(BodyParser.Json.class) public static Result changePassword() { Logger.trace("Method Start"); Http.RequestBody body = request().body(); JsonNode bodyJson = body.asJson(); Logger.trace("changePassword 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("old")) return badRequest("The 'old' field is missing"); if (!bodyJson.has("new")) return badRequest("The 'new' field is missing"); String currentPassword = DbHelper.getCurrentHTTPPassword(); String oldPassword = (String) bodyJson.findValuesAsText("old").get(0); String newPassword = (String) bodyJson.findValuesAsText("new").get(0); if (!oldPassword.equals(currentPassword)) { return badRequest("The old password does not match with the current one"); } UserService.changePasswordCurrentUser(newPassword); Logger.trace("Method End"); return ok(); }
@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(); }
/* @Path("/{id}") @ApiOperation(value = "Get info about current user", notes = "", httpMethod = "GET") */ @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class}) public static Result getCurrentUser() throws SqlInjectionException { Logger.trace("Method Start"); ODocument profile = UserService.getCurrentUser(); String result = prepareResponseToJson(profile); Logger.trace("Method End"); return ok(result); }
@With({UserCredentialWrapFilter.class, ConnectToDBFilter.class}) public static Result logoutWithDevice(String pushToken) throws SqlInjectionException { String token = (String) Http.Context.current().args.get("token"); if (!StringUtils.isEmpty(token)) { UserService.logout(pushToken); SessionTokenProvider.getSessionTokenProvider().removeSession(token); } return ok("pushToken: " + pushToken + " logged out"); }
@With({UserCredentialWrapFilter.class, ConnectToDBFilter.class}) public static Result disable() { try { UserService.disableCurrentUser(); } catch (UserNotFoundException e) { return badRequest(ExceptionUtils.getMessage(e)); } catch (OpenTransactionException e) { BaasBoxLogger.error(ExceptionUtils.getFullStackTrace(e)); throw new RuntimeException(e); } return ok(); }
@With({ AdminCredentialWrapFilter.class, ConnectToDBFilter.class, }) @BodyParser.Of(BodyParser.Json.class) public static Result signUp() { Logger.trace("Method Start"); Http.RequestBody body = request().body(); JsonNode bodyJson = body.asJson(); Logger.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); 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."); } // try to signup new user try { UserService.signUp( username, password, nonAppUserAttributes, privateAttributes, friendsAttributes, appUsersAttributes); } catch (UserAlreadyExistsException e) { Logger.debug("signUp", e); return badRequest(username + " already exists"); } catch (Throwable e) { Logger.warn("signUp", e); if (Play.isDev()) return internalServerError(ExceptionUtils.getFullStackTrace(e)); else return internalServerError(e.getMessage()); } Logger.trace("Method End"); return created(); }
public static void createDefaultUsers() throws Exception { Logger.trace("Method Start"); // the baasbox default user used to connect to the DB like anonymous user String username = BBConfiguration.getBaasBoxUsername(); String password = BBConfiguration.getBaasBoxPassword(); UserService.signUp( username, password, DefaultRoles.ANONYMOUS_USER.toString(), null, null, null, null); OGraphDatabase db = DbHelper.getConnection(); OUser admin = db.getMetadata().getSecurity().getUser("admin"); admin.setPassword(BBConfiguration.configuration.getString(BBConfiguration.ADMIN_PASSWORD)); admin.save(); Logger.trace("Method End"); }
@With({AdminCredentialWrapFilter.class, ConnectToDBFilter.class}) public static Result resetPasswordStep1(String username) { if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method Start"); // check and validate input if (username == null) return badRequest( "The 'username' field is missing in the URL, please check the documentation"); if (!UserService.exists(username)) return badRequest("Username " + username + " not found!"); QueryParams criteria = QueryParams.getInstance().where("user.name=?").params(new String[] {username}); ODocument user; try { List<ODocument> users = UserService.getUsers(criteria); user = UserService.getUsers(criteria).get(0); ODocument attrObj = user.field(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER); if (attrObj == null || attrObj.field("email") == null) return badRequest( "Cannot reset password, the \"email\" attribute is not defined into the user's private profile"); // if (UserService.checkResetPwdAlreadyRequested(username)) return badRequest("You have // already requested a reset of your password."); String appCode = (String) Http.Context.current.get().args.get("appcode"); UserService.sendResetPwdMail(appCode, user); } catch (PasswordRecoveryException e) { BaasBoxLogger.warn("resetPasswordStep1", e); return badRequest(ExceptionUtils.getMessage(e)); } catch (Exception e) { BaasBoxLogger.warn("resetPasswordStep1", e); return internalServerError(ExceptionUtils.getFullStackTrace(e)); } if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method End"); return ok(); }
@With({UserCredentialWrapFilter.class, ConnectToDBFilter.class}) public static Result getUser(String username) throws SqlInjectionException { if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method Start"); if (ArrayUtils.contains( new String[] { BBConfiguration.getBaasBoxAdminUsername(), BBConfiguration.getBaasBoxUsername() }, username)) return badRequest(username + " cannot be queried"); ODocument profile = UserService.getUserProfilebyUsername(username); if (profile == null) return notFound(username + " not found"); String result = prepareResponseToJson(profile); if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method End"); return ok(result); }
@With({UserCredentialWrapFilter.class, ConnectToDBFilter.class, ExtractQueryParameters.class}) public static Result getUsers() { if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method Start"); Context ctx = Http.Context.current.get(); QueryParams criteria = (QueryParams) ctx.args.get(IQueryParametersKeys.QUERY_PARAMETERS); List<ODocument> profiles = null; ; try { profiles = UserService.getUsers(criteria, true); } catch (SqlInjectionException e) { return badRequest( ExceptionUtils.getMessage(e) + " -- " + ExceptionUtils.getRootCauseMessage(e)); } String result = prepareResponseToJson(profiles); if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method End"); return ok(result); }
public static ODocument updateCurrentProfile( JsonNode nonAppUserAttributes, JsonNode privateAttributes, JsonNode friendsAttributes, JsonNode appUsersAttributes) throws Exception { try { ODocument profile = UserService.getCurrentUser(); profile = updateProfile( profile, nonAppUserAttributes, privateAttributes, friendsAttributes, appUsersAttributes); return profile; } catch (Exception e) { throw e; } } // update profile
@With({UserCredentialWrapFilter.class, ConnectToDBFilter.class}) @BodyParser.Of(BodyParser.Json.class) public static Result changeUserName() throws UserNotFoundException { Http.RequestBody body = request().body(); JsonNode bodyJson = body.asJson(); if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("updateuserName bodyJson: " + bodyJson); if (bodyJson == null) return badRequest( "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json"); if (bodyJson.get("username") == null || !bodyJson.get("username").isTextual()) return badRequest("'username' field must be a String"); String newUsername = bodyJson.get("username").asText(); try { UserService.changeUsername(DbHelper.getCurrentHTTPUsername(), newUsername); } catch (OpenTransactionException e) { return internalServerError(ExceptionUtils.getMessage(e)); } catch (SqlInjectionException e) { return badRequest("Username not valid"); } return ok(); }
@With({UserCredentialWrapFilter.class, ConnectToDBFilter.class}) @BodyParser.Of(BodyParser.Json.class) public static Result updateProfile() { Logger.trace("Method Start"); Http.RequestBody body = request().body(); JsonNode bodyJson = body.asJson(); Logger.trace("updateProfile bodyJson: " + bodyJson); if (bodyJson == null) return badRequest( "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json"); // extract the profile 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); if (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."); } ODocument profile; try { profile = UserService.updateCurrentProfile( nonAppUserAttributes, privateAttributes, friendsAttributes, appUsersAttributes); } catch (Throwable e) { Logger.warn("updateProfile", e); if (Play.isDev()) return internalServerError(ExceptionUtils.getFullStackTrace(e)); else return internalServerError(e.getMessage()); } Logger.trace("Method End"); return ok(prepareResponseToJson(profile)); } // updateProfile
@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); }
/** * * 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); }
/** * * Generate LAYER API token for the user. parameters: nonce: nonce received from Layer * authentication request on client * * @return * @throws SqlInjectionException * @throws IOException * @throws JsonProcessingException */ @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class}) public static Result generateLayerToken() throws SqlInjectionException, JsonProcessingException, IOException { String nonce = ""; 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("nonce") == null) return badRequest("The 'nonce' field is missing"); else nonce = bodyUrlEncoded.get("nonce")[0]; if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Nonce " + nonce); } 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("nonce") == null) return badRequest("The 'nonce' field is missing"); else nonce = bodyJson.get("nonce").asText(); if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("Nonce " + nonce); } String result = ""; try { ODocument doc = UserService.getCurrentUser(); result = prepareResponseToJson(UserService.getCurrentUser()); String userid = doc.field("user.name"); Boolean layerEnabled = com.baasbox.configuration.Application.LAYER_API_ENABLED.getValueAsBoolean(); if (!layerEnabled) { return badRequest("Layer tokens are disabled. Visit console to enable it."); } try { if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("NonceToken requested for user: "******"}")) + ",\"LayerToken\":\"" + token + "\"}"; } catch (Exception ex) { if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("NonceToken generation error: " + ex.getMessage()); return badRequest("Could not generate LAYER API token: " + ex.getMessage()); } } catch (Exception ex) { if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("NonceToken generation error: " + ex.getMessage()); return badRequest("Could not generate LAYER API token: " + ex.getMessage()); } ObjectMapper mapper = new ObjectMapper(); JsonNode jn = mapper.readTree(result); return ok(jn); }
// NOTE: this controller is called via a web form by a browser to reset the user's password // Filters to extract username/appcode/atc.. from the headers have no sense in this case public static Result resetPasswordStep3(String base64) { String tokenReceived = ""; String appCode = ""; String username = ""; String tokenId = ""; Map<String, String[]> bodyForm = null; try { // loads the received token and extracts data by the hashcode in the url tokenReceived = new String(Base64.decodeBase64(base64.getBytes())); Logger.debug("resetPasswordStep3 - sRandom: " + tokenReceived); // token format should be APP_Code%%%%Username%%%%ResetTokenId String[] tokens = tokenReceived.split("%%%%"); if (tokens.length != 3) return badRequest("The reset password code is invalid."); appCode = tokens[0]; username = tokens[1]; tokenId = tokens[2]; String adminUser = BBConfiguration.configuration.getString(IBBConfigurationKeys.ADMIN_USERNAME); String adminPassword = BBConfiguration.configuration.getString(IBBConfigurationKeys.ADMIN_PASSWORD); try { DbHelper.open(appCode, adminUser, adminPassword); } catch (InvalidAppCodeException e1) { throw new Exception("The code to reset the password seems to be invalid"); } if (!UserService.exists(username)) throw new Exception("User not found!"); boolean isTokenValid = ResetPwdDao.getInstance().verifyTokenStep2(base64, username); if (!isTokenValid) throw new Exception( "Reset Code not found or expired! Please repeat the reset password procedure"); Http.RequestBody body = request().body(); bodyForm = body.asFormUrlEncoded(); if (bodyForm == null) throw new Exception( "Error getting submitted data. Please repeat the reset password procedure"); } catch (Exception e) { ST pageTemplate = new ST(PasswordRecovery.PAGE_HTML_FEEDBACK_TEMPLATE.getValueAsString(), '$', '$'); pageTemplate.add("user_name", username); pageTemplate.add("error", e.getMessage()); pageTemplate.add( "application_name", com.baasbox.configuration.Application.APPLICATION_NAME.getValueAsString()); DbHelper.getConnection().close(); return badRequest(Html.apply(pageTemplate.render())); } // check and validate input String errorString = ""; if (bodyForm.get("password").length != 1) errorString = "The 'new password' field is missing"; if (bodyForm.get("repeat-password").length != 1) errorString = "The 'repeat password' field is missing"; String password = (String) bodyForm.get("password")[0]; String repeatPassword = (String) bodyForm.get("repeat-password")[0]; if (!password.equals(repeatPassword)) { errorString = "The new \"password\" field and the \"repeat password\" field must be the same."; } if (!errorString.isEmpty()) { ST pageTemplate = new ST(PasswordRecovery.PAGE_HTML_TEMPLATE.getValueAsString(), '$', '$'); pageTemplate.add( "form_template", "<form action='/user/password/reset/" + base64 + "' method='POST' id='reset_pwd_form'>" + "<label for='password'>New password</label>" + "<input type='password' id='password' name='password' />" + "<label for='repeat-password'>Repeat the new password</label>" + "<input type='password' id='repeat-password' name='repeat-password' />" + "<button type='submit' id='reset_pwd_submit'>Reset the password</button>" + "</form>"); pageTemplate.add("user_name", username); pageTemplate.add("link", "/user/password/reset/" + base64); pageTemplate.add("password", "password"); pageTemplate.add("repeat_password", "repeat-password"); pageTemplate.add( "application_name", com.baasbox.configuration.Application.APPLICATION_NAME.getValueAsString()); pageTemplate.add("error", errorString); DbHelper.getConnection().close(); return badRequest(Html.apply(pageTemplate.render())); } try { UserService.resetUserPasswordFinalStep(username, password); } catch (Throwable e) { Logger.warn("changeUserPassword", e); DbHelper.getConnection().close(); if (Play.isDev()) return internalServerError(ExceptionUtils.getFullStackTrace(e)); else return internalServerError(e.getMessage()); } Logger.trace("Method End"); String ok_message = "Password changed"; ST pageTemplate = new ST(PasswordRecovery.PAGE_HTML_FEEDBACK_TEMPLATE.getValueAsString(), '$', '$'); pageTemplate.add("user_name", username); pageTemplate.add("message", ok_message); pageTemplate.add( "application_name", com.baasbox.configuration.Application.APPLICATION_NAME.getValueAsString()); DbHelper.getConnection().close(); return ok(Html.apply(pageTemplate.render())); }
/** * * 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); }