Search in sources :

Example 11 with User

use of io.github.jhipster.sample.domain.User in project jhipster-sample-app-dto by jhipster.

the class UserResource method createUser.

/**
 * POST  /users  : Creates a new user.
 * <p>
 * Creates a new user if the login and email are not already used, and sends an
 * mail with an activation link.
 * The user needs to be activated on creation.
 *
 * @param userDTO the user to create
 * @return the ResponseEntity with status 201 (Created) and with body the new user, or with status 400 (Bad Request) if the login or email is already in use
 * @throws URISyntaxException if the Location URI syntax is incorrect
 * @throws BadRequestAlertException 400 (Bad Request) if the login or email is already in use
 */
@PostMapping("/users")
@Timed
@Secured(AuthoritiesConstants.ADMIN)
public ResponseEntity<User> createUser(@Valid @RequestBody UserDTO userDTO) throws URISyntaxException {
    log.debug("REST request to save User : {}", userDTO);
    if (userDTO.getId() != null) {
        throw new BadRequestAlertException("A new user cannot already have an ID", "userManagement", "idexists");
    // Lowercase the user login before comparing with database
    } else if (userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).isPresent()) {
        throw new LoginAlreadyUsedException();
    } else if (userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).isPresent()) {
        throw new EmailAlreadyUsedException();
    } else {
        User newUser = userService.createUser(userDTO);
        mailService.sendCreationEmail(newUser);
        return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin())).headers(HeaderUtil.createAlert("userManagement.created", newUser.getLogin())).body(newUser);
    }
}
Also used : BadRequestAlertException(io.github.jhipster.sample.web.rest.errors.BadRequestAlertException) User(io.github.jhipster.sample.domain.User) LoginAlreadyUsedException(io.github.jhipster.sample.web.rest.errors.LoginAlreadyUsedException) URI(java.net.URI) EmailAlreadyUsedException(io.github.jhipster.sample.web.rest.errors.EmailAlreadyUsedException) Secured(org.springframework.security.access.annotation.Secured) Timed(com.codahale.metrics.annotation.Timed)

Example 12 with User

use of io.github.jhipster.sample.domain.User in project jhipster-sample-app-dto by jhipster.

the class DomainUserDetailsService method loadUserByUsername.

@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
    log.debug("Authenticating {}", login);
    if (new EmailValidator().isValid(login, null)) {
        Optional<User> userByEmailFromDatabase = userRepository.findOneWithAuthoritiesByEmail(login);
        return userByEmailFromDatabase.map(user -> createSpringSecurityUser(login, user)).orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database"));
    }
    String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
    Optional<User> userByLoginFromDatabase = userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin);
    return userByLoginFromDatabase.map(user -> createSpringSecurityUser(lowercaseLogin, user)).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database"));
}
Also used : EmailValidator(org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator) java.util(java.util) UserRepository(io.github.jhipster.sample.repository.UserRepository) Logger(org.slf4j.Logger) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) LoggerFactory(org.slf4j.LoggerFactory) UserDetailsService(org.springframework.security.core.userdetails.UserDetailsService) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) Collectors(java.util.stream.Collectors) GrantedAuthority(org.springframework.security.core.GrantedAuthority) User(io.github.jhipster.sample.domain.User) Component(org.springframework.stereotype.Component) UserDetails(org.springframework.security.core.userdetails.UserDetails) Transactional(org.springframework.transaction.annotation.Transactional) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) EmailValidator(org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator) User(io.github.jhipster.sample.domain.User) Transactional(org.springframework.transaction.annotation.Transactional)

Example 13 with User

use of io.github.jhipster.sample.domain.User in project jhipster-sample-app-dto by jhipster.

the class UserService method removeNotActivatedUsers.

/**
 * Not activated users should be automatically deleted after 3 days.
 * <p>
 * This is scheduled to get fired everyday, at 01:00 (am).
 */
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
    List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS));
    for (User user : users) {
        log.debug("Deleting not activated user {}", user.getLogin());
        userRepository.delete(user);
        this.clearUserCaches(user);
    }
}
Also used : User(io.github.jhipster.sample.domain.User) Scheduled(org.springframework.scheduling.annotation.Scheduled)

Example 14 with User

use of io.github.jhipster.sample.domain.User in project jhipster-sample-app-dto by jhipster.

the class AccountResourceIntTest method testRegisterInvalidEmail.

@Test
@Transactional
public void testRegisterInvalidEmail() throws Exception {
    ManagedUserVM invalidUser = new ManagedUserVM();
    invalidUser.setLogin("bob");
    invalidUser.setPassword("password");
    invalidUser.setFirstName("Bob");
    invalidUser.setLastName("Green");
    // <-- invalid
    invalidUser.setEmail("invalid");
    invalidUser.setActivated(true);
    invalidUser.setImageUrl("http://placehold.it/50x50");
    invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
    invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
    restUserMockMvc.perform(post("/api/register").contentType(TestUtil.APPLICATION_JSON_UTF8).content(TestUtil.convertObjectToJsonBytes(invalidUser))).andExpect(status().isBadRequest());
    Optional<User> user = userRepository.findOneByLogin("bob");
    assertThat(user.isPresent()).isFalse();
}
Also used : User(io.github.jhipster.sample.domain.User) WithMockUser(org.springframework.security.test.context.support.WithMockUser) ManagedUserVM(io.github.jhipster.sample.web.rest.vm.ManagedUserVM) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Transactional(org.springframework.transaction.annotation.Transactional)

Example 15 with User

use of io.github.jhipster.sample.domain.User in project jhipster-sample-app-dto by jhipster.

the class AccountResourceIntTest method testChangePasswordEmpty.

@Test
@Transactional
@WithMockUser("change-password-empty")
public void testChangePasswordEmpty() throws Exception {
    User user = new User();
    user.setPassword(RandomStringUtils.random(60));
    user.setLogin("change-password-empty");
    user.setEmail("change-password-empty@example.com");
    userRepository.saveAndFlush(user);
    restMvc.perform(post("/api/account/change-password").content(RandomStringUtils.random(0))).andExpect(status().isBadRequest());
    User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null);
    assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
Also used : User(io.github.jhipster.sample.domain.User) WithMockUser(org.springframework.security.test.context.support.WithMockUser) WithMockUser(org.springframework.security.test.context.support.WithMockUser) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

User (io.github.jhipster.sample.domain.User)329 Test (org.junit.Test)251 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)251 Transactional (org.springframework.transaction.annotation.Transactional)150 WithMockUser (org.springframework.security.test.context.support.WithMockUser)138 ManagedUserVM (io.github.jhipster.sample.web.rest.vm.ManagedUserVM)90 AbstractCassandraTest (io.github.jhipster.sample.AbstractCassandraTest)38 UserDTO (io.github.jhipster.sample.service.dto.UserDTO)32 Authority (io.github.jhipster.sample.domain.Authority)24 PasswordChangeDTO (io.github.jhipster.sample.service.dto.PasswordChangeDTO)24 MimeMessage (javax.mail.internet.MimeMessage)24 Instant (java.time.Instant)21 Before (org.junit.Before)13 Timed (com.codahale.metrics.annotation.Timed)12 KeyAndPasswordVM (io.github.jhipster.sample.web.rest.vm.KeyAndPasswordVM)12 Scheduled (org.springframework.scheduling.annotation.Scheduled)8 GrantedAuthority (org.springframework.security.core.GrantedAuthority)7 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)7 UserDetails (org.springframework.security.core.userdetails.UserDetails)7 PersistentToken (io.github.jhipster.sample.domain.PersistentToken)6