/** * Creates a new user. * * @param user * The user to create * @return The created user (enhanced with information form the DB); an error message on failure. * @responseType de.learnlib.alex.auth.entities.User * @successResponse 201 created * @errorResponse 400 bad request `de.learnlib.alex.common.utils.ResourceErrorHandler.RESTError */ @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response create(User user) { LOGGER.traceEntry("create({}).", user); try { // validate email address if (!new EmailValidator().isValid(user.getEmail(), null)) { throw new ValidationException("The email is not valid"); } user.setEncryptedPassword(user.getPassword()); // create user userDAO.create(user); LOGGER.traceExit(user); return Response.status(Status.CREATED).entity(user).build(); } catch (ValidationException e) { LOGGER.traceExit(e); return ResourceErrorHandler.createRESTErrorMessage("UserResource.create", Status.BAD_REQUEST, e); } }
/** * Changes the email of the user. * This can only be invoked for your own account or if you are an administrator. * Please also note: Your new email must not be your current one and no other user should already have this email. * * @param userId * The id of the user * @param json * the json with a property 'email' * @return The updated user. * @throws NotFoundException If the requested User could not be found. * * @responseType de.learnlib.alex.auth.entities.User * @successResponse 200 Ok * @errorResponse 400 bad request `de.learnlib.alex.common.utils.ResourceErrorHandler.RESTError * @errorResponse 403 forbidden `de.learnlib.alex.common.utils.ResourceErrorHandler.RESTError * @errorResponse 404 not found `de.learnlib.alex.common.utils.ResourceErrorHandler.RESTError */ @PUT @Path("/{id}/email") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({"REGISTERED"}) public Response changeEmail(@PathParam("id") Long userId, JSONObject json) throws NotFoundException { User user = ((UserPrincipal) securityContext.getUserPrincipal()).getUser(); LOGGER.traceEntry("changeEmail({}, {}) for user {}.", userId, json, user); if (!user.getId().equals(userId) && !user.getRole().equals(UserRole.ADMIN)) { LOGGER.traceExit("Only the user or an admin is allowed to change the email."); return ResourceErrorHandler.createRESTErrorMessage("UserResource.changePassword", Status.FORBIDDEN, null); } String email = (String) json.get("email"); try { User realUser = userDAO.getById(userId); if (!new EmailValidator().isValid(email, null)) { throw new ValidationException("The email is not valid!"); } if (email.equals(user.getEmail())) { throw new ValidationException("The email is the same as the current one!"); } if (emailIsAlreadyTaken(email)) { throw new ValidationException("The email is already taken!"); } realUser.setEmail(email); userDAO.update(realUser); LOGGER.traceExit(realUser); return Response.ok(realUser).build(); } catch (ValidationException e) { LOGGER.traceExit(e); return ResourceErrorHandler.createRESTErrorMessage("UserResource.changeEmail", Status.BAD_REQUEST, e); } }
private void validateEmail(String email) { if (isNullOrEmpty(email)) { throw new EntityInvalidException("Email must not be null or empty"); } EmailValidator emailValidator = new EmailValidator(); if (!emailValidator.isValid(email, null)) { throw new EntityInvalidException("e-mail address is not valid"); } }
@Override public void validate(FormRenderedElement element) { String value = (String)element.getValue(); if (value == null) { return; } // Use the hibernate validator... boolean valid = new EmailValidator().isValid(value, null); if (!valid) { element.addError(translate("Please provide a valid email address")); } }
@POST @Path("/_join") public Response create(@FormParam("username") String username, @FormParam("firstname") String firstName, @FormParam("lastname") String lastName, @FormParam("email") String email, @FormParam("locale") String preferredLanguage, @FormParam("application") List<String> applications, @FormParam("group") List<String> groups, @FormParam("password") String password, @FormParam("reCaptchaResponse") String reCaptchaResponse, @Context HttpServletRequest request) { if(Strings.isNullOrEmpty(email)) throw new BadRequestException("Email cannot be empty"); if(!new EmailValidator().isValid(email, null)) throw new BadRequestException("Not a valid email address"); String name = username; if(Strings.isNullOrEmpty(username)) { if(configurationService.getConfiguration().isJoinWithUsername()) throw new BadRequestException("User name cannot be empty"); try { name = email.split("@")[0]; } catch(Exception e) { name = new ObjectId().toString(); } } if(new EmailValidator().isValid(name, null)) throw new BadRequestException("User name cannot be an email address"); if(!reCaptchaService.verify(reCaptchaResponse)) throw new BadRequestException("Invalid reCaptcha response"); if(CURRENT_USER_NAME.equals(name)) throw new BadRequestException("Reserved user name: " + CURRENT_USER_NAME); User user = userService.findUserByEmail(email); if(user != null) throw new BadRequestException("Email already in use: " + user.getEmail()); user = userService.findUser(name); int i = 1; String originalName = name; while(user != null) { name = originalName + i; user = userService.findUser(name); i++; } user = User.newBuilder().name(name).realm(AgateUserRealm.AGATE_REALM).role(Roles.AGATE_USER).pending() .firstName(firstName).lastName(lastName).email(email).preferredLanguage(preferredLanguage).build(); user.setGroups(Sets.newHashSet(groups)); user.setApplications(Sets.newHashSet(applications)); user.setAttributes(extractAttributes(request)); if(isRequestedByApplication(request)) { user.setStatus(UserStatus.APPROVED); } userService.createUser(user, password); return Response .created(UriBuilder.fromPath(JerseyConfiguration.WS_ROOT).path(UserResource.class).build(user.getId())).build(); }
@POST public Response create(Agate.UserCreateFormDto userCreateFormDto) { Agate.UserDto userDto = userCreateFormDto.getUser(); String username = userDto.getName(); if (new EmailValidator().isValid(username, null)) throw new BadRequestException("username can not be an email address."); User user = userService.findUser(username); if(user != null) throw new BadRequestException("User already exists: " + username); user = userService.findUserByEmail(userDto.getEmail()); if(user != null) throw new BadRequestException("Email already in use: " + user.getEmail()); if(CURRENT_USER_NAME.equals(username)) throw new BadRequestException("Reserved user name: " + CURRENT_USER_NAME); user = userService.createUser(dtos.fromDto(userDto), userCreateFormDto.getPassword()); return Response .created(UriBuilder.fromPath(JerseyConfiguration.WS_ROOT).path(UserResource.class).build(user.getId())).build(); }
/** * Return the property name used to match the user name. * * @param name * The current principal. * @return the property name used to match the user name. */ public String getAuthenticateProperty(final String name) { return new EmailValidator().isValid(name, null) ? "mail" : uidAttribute; }