Project

General

Profile

« Previous | Next » 

Revision da8f3c20

Added by Andreas Kohlbecker over 2 years ago

ref #9497 AccountRegistrationService tesing for existing usernames & adding exist check methods to dao

View differences:

cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/dao/hibernate/permission/UserDaoImpl.java
39 39
        return initializeUser(user);
40 40
    }
41 41

  
42
    @Override
43
    public boolean userNameExists(String username) {
44
        Query query = getSession().createQuery("select count(user) from User user where user.username = :username");
45
        query.setParameter("username", username);
46

  
47
        long count = (long)query.uniqueResult();
48
        return count > 0;
49
    }
50

  
51
    @Override
52
    public boolean emailAddressExists(String emailAddress) {
53
        Query query = getSession().createQuery("select count(user) from User user where user.emailAddress = :emailAddress");
54
        query.setParameter("emailAddress", emailAddress);
55

  
56
        long count = (long)query.uniqueResult();
57
        return count > 0;
58
    }
59

  
42 60
    @Override
43 61
    public User findByEmailAddress(String emailAddress) {
44 62
        Query query = getSession().createQuery("select user from User user where user.emailAddress = :emailAddress");
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/dao/permission/IUserDao.java
37 37
     * @return The user or null
38 38
     */
39 39
    public User findByEmailAddress(String emailAddress);
40
    
40

  
41 41
     /**
42 42
     * Return a List of users matching the given query string, optionally filtered by class, optionally with a particular MatchMode
43 43
     *
44
     * @param queryString the query string to filter by
44
     * @par@Override
45
    am queryString the query string to filter by
45 46
     * @param matchmode use a particular type of matching (can be null - defaults to exact matching)
46 47
     * @param criteria extra restrictions to apply
47 48
     * @param pageSize The maximum number of rights returned (can be null for all rights)
......
69 70
     */
70 71
    public long countByUsername(String queryString, MatchMode matchmode, List<Criterion> criteria);
71 72

  
73
    /**
74
     * Checks if the <code>username</code> exists in the database.
75
     */
76
    public boolean userNameExists(String username);
77

  
78
    /**
79
     * Checks if the <code>emailAddress</code> exists in the database.
80
     */
81
    boolean emailAddressExists(String emailAddress);
82

  
72 83

  
73 84
}
cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/service/security/AccountRegistrationService.java
40 40
@Transactional(readOnly = true)
41 41
public class AccountRegistrationService extends AccountSelfManagementService implements IAccountRegistrationService {
42 42

  
43

  
44
    protected static final String EMAIL_EXISTS = "An account for this email address already exits.";
45

  
46
    protected static final String USER_NAME_EXISTS_MSG = "This user name is already being used by someone else.";
47

  
43 48
    private static Logger logger = Logger.getLogger(PasswordResetRequest.class);
44 49

  
45 50
    @Autowired
......
49 54
    @Override
50 55
    @Async
51 56
    public ListenableFuture<Boolean> emailAccountRegistrationRequest(String emailAddress,
52
            String userName, String password, String accountCreationRequestFormUrlTemplate) throws MailException, AddressException {
57
            String userName, String password, String accountCreationRequestFormUrlTemplate) throws MailException, AddressException, AccountSelfManagementException {
53 58

  
54 59
        if(logger.isTraceEnabled()) {
55 60
            logger.trace("emailAccountRegistrationConfirmation() trying to aquire from rate limiter [rate: " + emailResetToken_rateLimiter.getRate() + ", timeout: " + getRateLimiterTimeout().toMillis() + "ms]");
......
58 63
            logger.trace("emailAccountRegistrationConfirmation() allowed by rate limiter");
59 64
            try {
60 65
                emailAddressValidAndUnused(emailAddress);
66
                if(userNameExists(userName)) {
67
                    throw new AccountSelfManagementException(USER_NAME_EXISTS_MSG);
68
                }
61 69
                User user = User.NewInstance(userName, password);
62 70
                user.setEmailAddress(emailAddress);
63 71
                AbstractRequestToken resetRequest = accountRegistrationTokenStore.create(user);
......
92 100
                try {
93 101
                    // check again if the email address is still unused
94 102
                    emailAddressValidAndUnused(creationRequest.get().getUserEmail());
103
                    if(userNameExists(creationRequest.get().getUserName())) {
104
                        throw new AccountSelfManagementException(USER_NAME_EXISTS_MSG);
105
                    }
95 106
                    User newUser = User.NewInstance(creationRequest.get().getUserName(), creationRequest.get().getEncryptedPassword());
96 107
                    userDao.saveOrUpdate(newUser);
97 108
                    accountRegistrationTokenStore.remove(token);
......
125 136
            throws AddressException, EmailAddressAlreadyInUseException {
126 137
        InternetAddress emailAddr = new InternetAddress(emailAddress);
127 138
        emailAddr.validate();
128
        if (userDao.findByEmailAddress(emailAddr.toString()) != null) {
129
            throw new EmailAddressAlreadyInUseException("Email address is already in use");
139
        if (emailAddressExists(emailAddr.toString())) {
140
            throw new EmailAddressAlreadyInUseException(EMAIL_EXISTS);
130 141
        }
131 142
    }
132 143

  
144
    @Override
145
    public boolean emailAddressExists(String emailAddress) {
146
        return userDao.emailAddressExists(emailAddress);
147
    }
148

  
149
    @Override
150
    public boolean userNameExists(String userName) {
151
        return userDao.userNameExists(userName);
152
    }
153

  
133 154
}
cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/service/security/IAccountRegistrationService.java
52 52
     *             in case sending the email has failed
53 53
     * @throws AddressException
54 54
     *             in case the <code>emailAddress</code> in not valid
55
     * @throws AccountSelfManagementException
56
     *             in case the user name is already being used.
55 57
     */
56 58
    ListenableFuture<Boolean> emailAccountRegistrationRequest(String emailAddress, String userName, String password,
57
            String passwordRequestFormUrlTemplate) throws MailException, AddressException;
59
            String passwordRequestFormUrlTemplate)
60
            throws MailException, AddressException, AccountSelfManagementException;
58 61

  
59 62
    /**
60 63
     *
......
82 85
    ListenableFuture<Boolean> createUserAccount(String token, String givenName, String familyName, String prefix)
83 86
            throws MailException, AccountSelfManagementException, AddressException;
84 87

  
88
    boolean userNameExists(String userName);
89

  
90
    boolean emailAddressExists(String emailAddress);
91

  
85 92
}
cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/service/security/AccountRegistrationServiceTest.java
229 229
        assertEquals(0, wiser.getMessages().size());
230 230
    }
231 231

  
232
    // @Test
233
    @DataSet(loadStrategy = CleanSweepInsertLoadStrategy.class, value="/eu/etaxonomy/cdm/database/ClearDBDataSet.xml")
234
    public void testUserNameExists() throws Throwable {
235

  
236
        logger.debug("testUserNameExists() ...");
237

  
238
        createRequestTokenSendSignal = new CountDownLatch(1);
239

  
240
        ListenableFuture<Boolean> emailResetFuture = accountRegistrationService.emailAccountRegistrationRequest(userEmail, "admin", userPWD, requestFormUrlTemplate);
241
        emailResetFuture.addCallback(
242
                requestSuccessVal -> {
243
                    createRequestTokenSendSignal.countDown();
244
                }, futureException -> {
245
                    assyncError = futureException;
246
                    createRequestTokenSendSignal.countDown();
247
                });
248

  
249
        // -- wait for passwordResetService.emailResetToken() to complete
250
        createRequestTokenSendSignal.await();
251

  
252
        assertNotNull(assyncError);
253
        assertEquals(AccountSelfManagementException.class, assyncError.getClass());
254
        assertEquals(AccountRegistrationService.USER_NAME_EXISTS_MSG, assyncError.getMessage());
255
        assertEquals(0, wiser.getMessages().size());
256
    }
257

  
232 258
    @Override
233 259
    public void createTestDataSet() throws FileNotFoundException {
234 260
        // not needed

Also available in: Unified diff