Search in sources :

Example 1 with UserAlreadyExistsException

use of won.owner.service.impl.UserAlreadyExistsException in project webofneeds by researchstudio-sat.

the class RestUserController method registerUser.

/**
 * registers user
 *
 * @param user registration data of a user
 * @param errors
 * @return ResponseEntity with Http Status Code
 */
@ResponseBody
@RequestMapping(value = "/", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
// TODO: move transactionality annotation into the service layer
@Transactional(propagation = Propagation.REQUIRED)
public ResponseEntity registerUser(@RequestBody UserPojo user, Errors errors, WebRequest request) {
    logger.debug("processing POST request to / (registers user)");
    try {
        userRegisterValidator.validate(user, errors);
        if (errors.hasErrors()) {
            if (errors.getFieldErrorCount() > 0) {
                // someone trying to go around js validation
                return generateStatusResponse(RestStatusResponse.SIGNUP_FAILED);
            } else {
                // username is already in database
                return generateStatusResponse(RestStatusResponse.USER_ALREADY_EXISTS);
            }
        }
        User createdUser = userService.registerUser(user.getUsername(), user.getPassword(), null, user.getPrivateId());
        if (!createdUser.isAnonymous() && !createdUser.isEmailVerified()) {
            eventPublisher.publishEvent(new OnRegistrationCompleteEvent(createdUser, request.getLocale(), request.getContextPath()));
            String recoveryKey;
            try {
                recoveryKey = userService.generateRecoveryKey(user.getUsername(), user.getPassword());
                eventPublisher.publishEvent(new OnRecoveryKeyGeneratedEvent(createdUser, recoveryKey));
            } catch (UserNotFoundException e) {
                return generateStatusResponse(RestStatusResponse.RECOVERY_KEYGEN_USER_NOT_FOUND);
            } catch (IncorrectPasswordException e) {
                return generateStatusResponse(RestStatusResponse.RECOVERY_KEYGEN_WRONG_PASSWORD);
            }
        }
    } catch (UserAlreadyExistsException e) {
        // username is already in database
        return generateStatusResponse(RestStatusResponse.USER_ALREADY_EXISTS);
    }
    return generateStatusResponse(RestStatusResponse.USER_CREATED);
}
Also used : OnRecoveryKeyGeneratedEvent(won.owner.web.events.OnRecoveryKeyGeneratedEvent) UserNotFoundException(won.owner.service.impl.UserNotFoundException) User(won.owner.model.User) IncorrectPasswordException(won.owner.service.impl.IncorrectPasswordException) OnRegistrationCompleteEvent(won.owner.web.events.OnRegistrationCompleteEvent) UserAlreadyExistsException(won.owner.service.impl.UserAlreadyExistsException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Transactional(org.springframework.transaction.annotation.Transactional)

Example 2 with UserAlreadyExistsException

use of won.owner.service.impl.UserAlreadyExistsException in project webofneeds by researchstudio-sat.

the class RestUserController method registerUser.

/**
 * registers user
 *
 * @param user   registration data of a user
 * @param errors
 * @return ResponseEntity with Http Status Code
 */
@ResponseBody
@RequestMapping(value = "/", method = RequestMethod.POST)
// TODO: move transactionality annotation into the service layer
@Transactional(propagation = Propagation.SUPPORTS)
public ResponseEntity registerUser(@RequestBody UserPojo user, Errors errors) {
    try {
        userRegisterValidator.validate(user, errors);
        if (errors.hasErrors()) {
            if (errors.getFieldErrorCount() > 0) {
                // someone trying to go around js validation
                return new ResponseEntity(errors.getAllErrors().get(0).getDefaultMessage(), HttpStatus.BAD_REQUEST);
            } else {
                // username is already in database
                return new ResponseEntity("\"Cannot create user: name is already in use.\"", HttpStatus.CONFLICT);
            }
        }
        registerUser(user.getUsername(), user.getPassword(), null);
    } catch (UserAlreadyExistsException e) {
        // username is already in database
        return new ResponseEntity("\"Cannot create user: name is already in use.\"", HttpStatus.CONFLICT);
    }
    return new ResponseEntity("\"New user was created\"", HttpStatus.CREATED);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) UserAlreadyExistsException(won.owner.service.impl.UserAlreadyExistsException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Transactional(org.springframework.transaction.annotation.Transactional)

Example 3 with UserAlreadyExistsException

use of won.owner.service.impl.UserAlreadyExistsException in project webofneeds by researchstudio-sat.

the class RestUserController method registerPrivateLinkAsUser.

/**
 * registers user
 *
 * @param user   registration data of a user
 * @param errors
 * @return ResponseEntity with Http Status Code
 */
@ResponseBody
@RequestMapping(value = "/private", method = RequestMethod.POST)
// TODO: move transactionality annotation into the service layer
@Transactional(propagation = Propagation.SUPPORTS)
public ResponseEntity registerPrivateLinkAsUser(@RequestBody UserPojo user, Errors errors) {
    String privateLink = null;
    try {
        // TODO more secure random alphanum string
        privateLink = (new CheapInsecureRandomString()).nextString(32);
        user.setUsername(privateLink);
        userRegisterValidator.validate(user, errors);
        if (errors.hasErrors()) {
            if (errors.getFieldErrorCount() > 0) {
                // someone trying to go around js validation
                return new ResponseEntity("\"" + errors.getAllErrors().get(0).getDefaultMessage() + "\"", HttpStatus.BAD_REQUEST);
            } else {
                // username is already in database
                return new ResponseEntity("\"Cannot create user: name is already in use.\"", HttpStatus.CONFLICT);
            }
        } else {
            registerUser(user.getUsername(), user.getPassword(), "ROLE_PRIVATE");
        }
    } catch (UserAlreadyExistsException e) {
        // username is already in database
        return new ResponseEntity("\"Cannot create user: name is already in use.\"", HttpStatus.CONFLICT);
    }
    return new ResponseEntity("\"" + privateLink + "\"", HttpStatus.CREATED);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) CheapInsecureRandomString(won.protocol.util.CheapInsecureRandomString) CheapInsecureRandomString(won.protocol.util.CheapInsecureRandomString) UserAlreadyExistsException(won.owner.service.impl.UserAlreadyExistsException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Transactional(org.springframework.transaction.annotation.Transactional)

Example 4 with UserAlreadyExistsException

use of won.owner.service.impl.UserAlreadyExistsException in project webofneeds by researchstudio-sat.

the class RestUserController method registerUser.

/**
 * Registers the specified user with password and an opional role.
 * Assumes values have already been checked for syntactic validity.
 * @param email
 * @param password
 * @param role
 * @throws UserAlreadyExistsException
 */
private void registerUser(String email, String password, String role) throws UserAlreadyExistsException {
    User user = userRepository.findByUsername(email);
    if (user != null) {
        throw new UserAlreadyExistsException();
    }
    try {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user = new User(email, passwordEncoder.encode(password), role);
        user.setEmail(email);
        KeystorePasswordHolder keystorePassword = new KeystorePasswordHolder();
        // generate a password for the keystore and save it in the database, encrypted with a symmetric key
        // derived from the user's password
        keystorePassword.setPassword(KeystorePasswordUtils.generatePassword(KeystorePasswordUtils.KEYSTORE_PASSWORD_BYTES), password);
        // keystorePassword = keystorePasswordRepository.save(keystorePassword);
        // generate the keystore for the user
        KeystoreHolder keystoreHolder = new KeystoreHolder();
        try {
            // create the keystore if it doesnt exist yet
            keystoreHolder.getKeystore(keystorePassword.getPassword(password));
        } catch (Exception e) {
            throw new IllegalStateException("could not create keystore for user " + email);
        }
        // keystoreHolder = keystoreHolderRepository.save(keystoreHolder);
        user.setKeystorePasswordHolder(keystorePassword);
        user.setKeystoreHolder(keystoreHolder);
        userRepository.save(user);
    } catch (DataIntegrityViolationException e) {
        // username is already in database
        throw new UserAlreadyExistsException();
    }
}
Also used : User(won.owner.model.User) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) KeystoreHolder(won.owner.model.KeystoreHolder) UserAlreadyExistsException(won.owner.service.impl.UserAlreadyExistsException) KeystorePasswordHolder(won.owner.model.KeystorePasswordHolder) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) URISyntaxException(java.net.URISyntaxException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) UserAlreadyExistsException(won.owner.service.impl.UserAlreadyExistsException) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException)

Example 5 with UserAlreadyExistsException

use of won.owner.service.impl.UserAlreadyExistsException in project webofneeds by researchstudio-sat.

the class RestUserController method transferUser.

/**
 * transfers a privateId user to a registered user
 *
 * @param errors
 * @return ResponseEntity with Http Status Code
 */
@ResponseBody
@RequestMapping(value = "/transfer", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@Transactional(propagation = Propagation.REQUIRED)
public ResponseEntity transferUser(@RequestBody TransferUserPojo transferUserPojo, Errors errors, WebRequest request) {
    logger.debug("processing request to /transfer");
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    // cannot use user object from context since hw doesn't know about created in
    // this session atom,
    // therefore, we have to retrieve the user object from the user repository
    User user = userService.getByUsername(username);
    if (user == null && !transferUserPojo.getPrivateUsername().equals(user.getUsername())) {
        return generateStatusResponse(RestStatusResponse.USERNAME_MISMATCH);
    }
    try {
        userRegisterValidator.validate(transferUserPojo, errors);
        if (errors.hasErrors()) {
            if (errors.getFieldErrorCount() > 0) {
                // someone trying to go around js validation
                return generateStatusResponse(RestStatusResponse.SIGNUP_FAILED);
            } else {
                // username is already in database
                return generateStatusResponse(RestStatusResponse.USER_ALREADY_EXISTS);
            }
        }
        User transferUser = userService.transferUser(transferUserPojo.getUsername(), transferUserPojo.getPassword(), transferUserPojo.getPrivateUsername(), transferUserPojo.getPrivatePassword());
        if (!transferUser.isEmailVerified()) {
            eventPublisher.publishEvent(new OnRegistrationCompleteEvent(transferUser, request.getLocale(), request.getContextPath()));
            String recoveryKey;
            try {
                recoveryKey = userService.generateRecoveryKey(transferUserPojo.getUsername(), transferUserPojo.getPassword());
                eventPublisher.publishEvent(new OnRecoveryKeyGeneratedEvent(transferUser, recoveryKey));
            } catch (UserNotFoundException e) {
                return generateStatusResponse(RestStatusResponse.RECOVERY_KEYGEN_USER_NOT_FOUND);
            } catch (IncorrectPasswordException e) {
                return generateStatusResponse(RestStatusResponse.RECOVERY_KEYGEN_WRONG_PASSWORD);
            }
        }
    } catch (UserAlreadyExistsException e) {
        // username is already in database
        return generateStatusResponse(RestStatusResponse.USER_ALREADY_EXISTS);
    } catch (UserNotFoundException e) {
        return generateStatusResponse(RestStatusResponse.TRANSFERUSER_NOT_FOUND);
    }
    return generateStatusResponse(RestStatusResponse.USER_TRANSFERRED);
}
Also used : OnRecoveryKeyGeneratedEvent(won.owner.web.events.OnRecoveryKeyGeneratedEvent) UserNotFoundException(won.owner.service.impl.UserNotFoundException) User(won.owner.model.User) IncorrectPasswordException(won.owner.service.impl.IncorrectPasswordException) OnRegistrationCompleteEvent(won.owner.web.events.OnRegistrationCompleteEvent) UserAlreadyExistsException(won.owner.service.impl.UserAlreadyExistsException) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

UserAlreadyExistsException (won.owner.service.impl.UserAlreadyExistsException)5 Transactional (org.springframework.transaction.annotation.Transactional)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)4 User (won.owner.model.User)3 ResponseEntity (org.springframework.http.ResponseEntity)2 IncorrectPasswordException (won.owner.service.impl.IncorrectPasswordException)2 UserNotFoundException (won.owner.service.impl.UserNotFoundException)2 OnRecoveryKeyGeneratedEvent (won.owner.web.events.OnRecoveryKeyGeneratedEvent)2 OnRegistrationCompleteEvent (won.owner.web.events.OnRegistrationCompleteEvent)2 URISyntaxException (java.net.URISyntaxException)1 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)1 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)1 BCryptPasswordEncoder (org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)1 PasswordEncoder (org.springframework.security.crypto.password.PasswordEncoder)1 KeystoreHolder (won.owner.model.KeystoreHolder)1 KeystorePasswordHolder (won.owner.model.KeystorePasswordHolder)1 CheapInsecureRandomString (won.protocol.util.CheapInsecureRandomString)1