Project

General

Profile

« Previous | Next » 

Revision 60083

[maven-release-plugin] copy for tag uoa-user-management-2.0.2

View differences:

modules/uoa-user-management/tags/uoa-user-management-2.0.2/deploy.info
1
{
2
  "type_source": "SVN", 
3
  "goal": "package -U source:jar",
4
  "url": "http://svn-public.driver.research-infrastructures.eu/driver/dnet45/modules/uoa-user-management/trunk",
5
  "deploy_repository": "dnet45-snapshots", 
6
  "version": "4", 
7
  "mail": "kiatrop@di.uoa.gr, argirok@di.uoa.gr, k.triantafyllou@di.uoa.gr",
8
  "deploy_repository_url": "https://maven.d4science.org/nexus/content/repositories/dnet45-snapshots", 
9
  "name": "uoa-user-management"
10
}
11

  
modules/uoa-user-management/tags/uoa-user-management-2.0.2/src/test/java/eu/dnetlib/openaire/user/AppTest.java
1
package eu.dnetlib.openaire.user;
2

  
3
import junit.framework.Test;
4
import junit.framework.TestCase;
5
import junit.framework.TestSuite;
6

  
7
/**
8
 * Unit test for simple App.
9
 */
10
public class AppTest 
11
    extends TestCase
12
{
13
    /**
14
     * Create the test case
15
     *
16
     * @param testName name of the test case
17
     */
18
    public AppTest( String testName )
19
    {
20
        super( testName );
21
    }
22

  
23
    /**
24
     * @return the suite of tests being tested
25
     */
26
    public static Test suite()
27
    {
28
        return new TestSuite( AppTest.class );
29
    }
30

  
31
    /**
32
     * Rigourous Test :-)
33
     */
34
    public void testApp()
35
    {
36
        assertTrue( true );
37
    }
38
}
modules/uoa-user-management/tags/uoa-user-management-2.0.2/src/test/java/eu/dnetlib/openaire/user/ldap/LDAPEnhancer.java
1
package eu.dnetlib.openaire.user.ldap;
2

  
3
import com.unboundid.ldap.sdk.*;
4
import eu.dnetlib.openaire.user.pojos.migration.LDAPUser;
5
import org.junit.Before;
6
import org.junit.Test;
7

  
8
/**
9
 * Created by kiatrop on 27/9/2017.
10
 */
11
public class LDAPEnhancer {
12

  
13
    LDAPConnection ldapConnector;
14
    String ldapUsersDN;
15

  
16
    @Before
17
    public void init() throws LDAPException {
18
        ldapConnector = new LDAPConnection("esperos.di.uoa.gr", 389, "cn=admin,dc=openaire,dc=eu", "serenata");
19
        ldapUsersDN = "ou=users,dc=openaire,dc=eu";
20
    }
21

  
22
    @Test
23
    public void enhance() throws LDAPSearchException {
24
        Filter filter = Filter.createEqualityFilter("ou", "users");
25
        SearchRequest searchRequest = new SearchRequest(ldapUsersDN, SearchScope.SUBORDINATE_SUBTREE, filter);
26
        SearchResult searchResult = ldapConnector.search(searchRequest);
27

  
28
        for (SearchResultEntry entry : searchResult.getSearchEntries()) {
29
            System.out.println(entry.getAttribute("dn"));
30
        }
31
    }
32

  
33
    @Test
34
    public void getUserTest() throws LDAPSearchException {
35
            String usersDN =  "ou=users,dc=openaire,dc=eu";
36

  
37
                Filter filter = Filter.createEqualityFilter("cn","kiatrop");
38
                SearchRequest searchRequest =
39
                        new SearchRequest(usersDN, SearchScope.SUB, filter, "mail", "displayName", "cn");
40

  
41
                SearchResult searchResult = ldapConnector.search(searchRequest);
42
                LDAPUser user = new LDAPUser();
43

  
44
                for (SearchResultEntry entry : searchResult.getSearchEntries()) {
45
                    System.out.println(entry.getAttributeValue("cn"));
46
                    System.out.println(entry.getAttributeValue("mail"));
47
                    System.out.println(entry.getAttributeValue("displayName"));
48
                }
49
        }
50

  
51

  
52

  
53
}
modules/uoa-user-management/tags/uoa-user-management-2.0.2/src/main/java/eu/dnetlib/openaire/user/actions/IUserActions.java
1
package eu.dnetlib.openaire.user.actions;
2

  
3
/**
4
 * Created by sofia on 31/10/2016.
5
 */
6
public interface IUserActions {
7

  
8
    public String addUser(String email, String password) throws Exception;
9

  
10
    public boolean activateUser(String activationId) throws Exception;
11

  
12
    public boolean isUserActivated(String email) throws Exception;
13

  
14
    public boolean userExists(String email) throws Exception;
15

  
16
    public boolean usernameExists(String username) throws Exception;
17

  
18
    public boolean correctCreds(String email, String password) throws Exception;
19

  
20
    public String prepareResetPassword(String email) throws Exception;
21

  
22
    public void resetPassword(String uuid, String password) throws Exception;
23

  
24
    public boolean isAdmin(String email) throws Exception;
25

  
26
    public void editUser(String email, String fname, String lname, String inst)
27
            throws Exception;
28

  
29
    public String addUser(String username, String email, String password,
30
                          String firstName, String lastName) throws Exception;
31

  
32
    public String getEmailFromUsername(String username) throws Exception;
33

  
34
    //public UserProfile getUser(String userIdentifier) throws Exception;
35

  
36
}
modules/uoa-user-management/tags/uoa-user-management-2.0.2/src/main/java/eu/dnetlib/openaire/user/ldap/UserActionsLDAP.java
1
package eu.dnetlib.openaire.user.ldap;
2

  
3
import com.unboundid.ldap.sdk.*;
4
import org.apache.log4j.Logger;
5

  
6
import java.util.UUID;
7

  
8

  
9
/**
10
 * Created by sofia on 31/10/2016.
11
 */
12
public class UserActionsLDAP {
13

  
14
    transient Logger logger = Logger.getLogger(UserActionsLDAP.class);
15

  
16
    private int ldapPort = 0;
17
    private String ldapAddress;
18
    private String ldapUsername;
19
    private String ldapPassword;
20
    private String ldapUsersDN;
21

  
22
    public boolean activateUser(String activationId) throws Exception {
23
        LDAPConnection connection = null;
24
        try {
25
            logger.debug("activating user with activationId " + activationId);
26
            connection = new LDAPConnection(ldapAddress, ldapPort, ldapUsername, ldapPassword);
27
            Filter filter = Filter.createEqualityFilter("employeeNumber", activationId);
28
            SearchRequest searchRequest = new SearchRequest(ldapUsersDN, SearchScope.SUB, filter, "uid");
29
            SearchResult searchResult = connection.search(searchRequest);
30
            String dn = null;
31

  
32
            if ( searchResult.getSearchEntries().size() > 0	) {
33

  
34
                for (SearchResultEntry entry : searchResult.getSearchEntries()) {
35
                    dn = "uid=" + entry.getAttributeValue("uid") + "," + ldapUsersDN;
36
                }
37

  
38
                Modification mod1 = new Modification(ModificationType.REPLACE, "JoomlaBlockUser", "0");
39
                Modification mod2 = new Modification(ModificationType.REPLACE, "employeeNumber");
40
                connection.modify(dn, mod1, mod2);
41
                return true;
42
            } else {
43
                return false;
44
            }
45
        } catch (Exception e) {
46
            logger.error("", e);
47
            throw e;
48
        } finally {
49
            if (connection != null)
50
                connection.close();
51
        }
52
    }
53

  
54
    public String addUser(String email, String password) throws Exception {
55
        throw new UnsupportedOperationException();
56
    }
57

  
58
    public String addUser(String username, String email, String password, String firstName, String lastName) throws Exception {
59
        logger.debug("adding user " + username + " " + email + " to ldap");
60
        Attribute cn = new Attribute("cn", username);
61
        Attribute displayName = new Attribute("displayName", firstName + " " + lastName);
62
        Attribute mail = new Attribute("mail", email);
63
        Attribute givenName = new Attribute("givenName", firstName);
64
        Attribute joomlaBlockUser = new Attribute("JoomlaBlockUser", "1");
65
        Attribute joomlaGroup = new Attribute("JoomlaGroup", "Registered");
66
        Attribute objectClass = new Attribute("objectClass", "top", "inetOrgPerson", "JoomlaUser");
67
        Attribute userPassword = new Attribute("userPassword", Joomla15PasswordHash.create(password));
68
        Attribute sn = new Attribute("sn", lastName);
69
        Attribute uid = new Attribute("uid", username);
70
        // Attribute joomlaUserParams = new Attribute("JoomlaUserParams", "");
71
        String activationId = UUID.randomUUID().toString();
72
        Attribute x500UniqueIdentifier = new Attribute("employeeNumber", activationId);
73
        LDAPConnection connection = null;
74
        try {
75
            DN dn = new DN("uid=" + username + "," + ldapUsersDN);
76
            System.out.println("cn: " + cn + " displayName: " + displayName + " mail: " + mail + " givenName: " + givenName + " joomlaBlockUser: " + joomlaBlockUser + " joomlaGroup: " + joomlaGroup + " objectClass: " + objectClass + " userPassword: " + userPassword + " sn: " + sn + " uid: " + uid + " x500UniqueIdentifier: " + x500UniqueIdentifier);
77
            Entry entry = new Entry(dn.toNormalizedString(), cn, displayName, mail, givenName, joomlaBlockUser, joomlaGroup, objectClass, userPassword, sn, uid/*
78
																																								 * ,
79
																																								 * joomlaUserParams
80
																																								 */, x500UniqueIdentifier);
81
            connection = new LDAPConnection(ldapAddress, ldapPort, ldapUsername, ldapPassword);
82
            connection.add(entry);
83

  
84
            return activationId;
85
        } catch (Exception e) {
86
            logger.error("", e);
87
            throw e;
88
        } finally {
89
            if (connection != null)
90
                connection.close();
91
        }
92
    }
93

  
94
    public boolean correctCreds(String email, String password) throws Exception {
95
        LDAPConnection connection = null;
96
        try {
97
            logger.debug("checking if user " + email + " entered a correct password when logging in");
98
            connection = new LDAPConnection(ldapAddress, ldapPort, ldapUsername, ldapPassword);
99
            Filter filter = Filter.createEqualityFilter("mail", email);
100
            SearchRequest searchRequest = new SearchRequest(ldapUsersDN, SearchScope.SUB, filter, "userPassword");
101
            SearchResult searchResult = connection.search(searchRequest);
102
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
103
                if (Joomla15PasswordHash.check(password, entry.getAttributeValue("userPassword")))
104
                    return true;
105
            }
106
            return false;
107
        } catch (Exception e) {
108
            logger.error("", e);
109
            throw e;
110
        } finally {
111
            if (connection != null)
112
                connection.close();
113
        }
114
    }
115

  
116
    public void editUser(String email, String fname, String lname, String inst) throws Exception {
117
        LDAPConnection connection = null;
118
        try {
119
            logger.debug("editing user " + email);
120
            connection = new LDAPConnection(ldapAddress, ldapPort, ldapUsername, ldapPassword);
121
            Filter filter = Filter.createEqualityFilter("mail", email);
122
            SearchRequest searchRequest = new SearchRequest(ldapUsersDN, SearchScope.SUB, filter, "uid");
123
            SearchResult searchResult = connection.search(searchRequest);
124
            String dn = null;
125
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
126
                dn = "uid=" + entry.getAttributeValue("uid") + "," + ldapUsersDN;
127
            }
128
            Modification mod1 = new Modification(ModificationType.REPLACE, "displayName", fname + " " + lname);
129
            Modification mod2 = new Modification(ModificationType.REPLACE, "givenName", fname);
130
            Modification mod3 = new Modification(ModificationType.REPLACE, "sn", lname);
131
            Modification mod4 = new Modification(ModificationType.REPLACE, "o", inst);
132
            connection.modify(dn, mod1, mod2, mod3, mod4);
133
        } catch (Exception e) {
134
            logger.error("", e);
135
            throw e;
136
        } finally {
137
            if (connection != null)
138
                connection.close();
139
        }
140
    }
141

  
142
    /*
143
    @Override
144
    public eu.dnetlib.openaire.user.user.UserProfile getUser(String userIdentifier) throws Exception {
145
        LDAPConnection connection = null;
146
        try {
147
            logger.debug("getting user " + userIdentifier + " from ldap");
148
            connection = new LDAPConnection(ldapAddress, ldapPort, ldapUsername, ldapPassword);
149
            Filter filter = Filter.createEqualityFilter("mail", userIdentifier);
150
            SearchRequest searchRequest = new SearchRequest(ldapUsersDN, SearchScope.SUB, filter, "mail", "givenName", "sn", "o", "uid");
151
            SearchResult searchResult = connection.search(searchRequest);
152
            UserProfileIS profile = new UserProfileIS();
153
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
154
                profile.setEmail(entry.getAttributeValue("mail"));
155
                profile.setFname(entry.getAttributeValue("givenName"));
156
                profile.setLname(entry.getAttributeValue("sn"));
157
                profile.setInstitution(entry.getAttributeValue("o"));
158
                profile.setUsername(entry.getAttributeValue("uid"));
159
            }
160
            return profile;
161
        } catch (Exception e) {
162
            logger.error("", e);
163
            throw e;
164
        } finally {
165
            if (connection != null)
166
                connection.close();
167
        }
168
    }*/
169

  
170
    public boolean isAdmin(String email) throws Exception {
171
        LDAPConnection connection = null;
172
        try {
173
            logger.debug("checking if user " + email + " is an administrator");
174
            connection = new LDAPConnection(ldapAddress, ldapPort, ldapUsername, ldapPassword);
175
            Filter filter = Filter.createEqualityFilter("mail", email);
176
            SearchRequest searchRequest = new SearchRequest(ldapUsersDN, SearchScope.SUB, filter, "JoomlaGroup");
177
            SearchResult searchResult = connection.search(searchRequest);
178

  
179
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
180
                for (String role : entry.getAttributeValues("JoomlaGroup"))
181
                    if (role.equals("validatorAdmin"))
182
                        return true;
183
            }
184
            logger.debug(email + " is not administrator");
185
            return false;
186
        } catch (Exception e) {
187
            logger.error("", e);
188
            throw e;
189
        } finally {
190
            if (connection != null)
191
                connection.close();
192
        }
193
    }
194

  
195
    public boolean isUserActivated(String email) throws Exception {
196
        LDAPConnection connection = null;
197
        try {
198
            logger.debug("checking if user " + email + " is activated");
199
            connection = new LDAPConnection(ldapAddress, ldapPort, ldapUsername, ldapPassword);
200
            Filter filter = Filter.createEqualityFilter("mail", email);
201
            SearchRequest searchRequest = new SearchRequest(ldapUsersDN, SearchScope.SUB, filter, "JoomlaBlockUser");
202
            SearchResult searchResult = connection.search(searchRequest);
203
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
204
                int val = entry.getAttributeValueAsInteger("JoomlaBlockUser");
205
                if (val == 0)
206
                    return true;
207
                else
208
                    return false;
209
            }
210
        } catch (Exception e) {
211
            logger.error("", e);
212
            throw e;
213
        } finally {
214
            if (connection != null)
215
                connection.close();
216
        }
217
        return false;
218
    }
219

  
220
    public String prepareResetPassword(String email) throws Exception {
221
        LDAPConnection connection = null;
222
        try {
223
            logger.debug("preparing reset password for user " + email);
224
            connection = new LDAPConnection(ldapAddress, ldapPort, ldapUsername, ldapPassword);
225
            Filter filter = Filter.createEqualityFilter("mail", email);
226
            SearchRequest searchRequest = new SearchRequest(ldapUsersDN, SearchScope.SUB, filter, "uid");
227
            SearchResult searchResult = connection.search(searchRequest);
228
            String dn = null;
229
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
230
                dn = "uid=" + entry.getAttributeValue("uid") + "," + ldapUsersDN;
231
            }
232
            String uuid = UUID.randomUUID().toString();
233
            Modification mod = new Modification(ModificationType.REPLACE, "employeeNumber", uuid);
234
            connection.modify(dn, mod);
235
            return uuid;
236
        } catch (Exception e) {
237
            logger.error("", e);
238
            throw e;
239
        } finally {
240
            if (connection != null)
241
                connection.close();
242
        }
243
    }
244

  
245
    public void resetPassword(String uuid, String password) throws Exception {
246
        LDAPConnection connection = null;
247
        try {
248
            connection = new LDAPConnection(ldapAddress, ldapPort, ldapUsername, ldapPassword);
249
            Filter filter = Filter.createEqualityFilter("employeeNumber", uuid);
250
            SearchRequest searchRequest = new SearchRequest(ldapUsersDN, SearchScope.SUB, filter, "uid");
251
            SearchResult searchResult = connection.search(searchRequest);
252
            String dn = null;
253
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
254
                dn = "uid=" + entry.getAttributeValue("uid") + "," + ldapUsersDN;
255
            }
256
            Modification mod1 = new Modification(ModificationType.REPLACE, "userPassword", Joomla15PasswordHash.create(password));
257
            Modification mod2 = new Modification(ModificationType.REPLACE, "employeeNumber");
258
            connection.modify(dn, mod1, mod2);
259
        } catch (Exception e) {
260
            logger.error("", e);
261
            throw e;
262
        } finally {
263
            if (connection != null)
264
                connection.close();
265
        }
266
    }
267

  
268
    public boolean userExists(String email) throws Exception {
269
        LDAPConnection connection = null;
270
        try {
271
            logger.debug("checking if user " + email + " exists in ldap");
272
            connection = new LDAPConnection(ldapAddress, ldapPort, ldapUsername, ldapPassword);
273
            Filter filter = Filter.createEqualityFilter("mail", email);
274
            SearchRequest searchRequest = new SearchRequest(ldapUsersDN, SearchScope.SUB, filter, "mail");
275

  
276
            SearchResult searchResult = connection.search(searchRequest);
277
            if (!searchResult.getSearchEntries().isEmpty())
278
                return true;
279

  
280
            return false;
281
        } catch (Exception e) {
282
            logger.error("", e);
283
            throw e;
284
        } finally {
285
            if (connection != null)
286
                connection.close();
287
        }
288
    }
289

  
290
    public boolean usernameExists(String username) throws Exception {
291
        LDAPConnection connection = null;
292
        try {
293
            logger.debug("checking if user " + username + " exists in ldap");
294
            connection = new LDAPConnection(ldapAddress, ldapPort, ldapUsername, ldapPassword);
295
            Filter filter = Filter.createEqualityFilter("uid", username);
296
            SearchRequest searchRequest = new SearchRequest(ldapUsersDN, SearchScope.SUB, filter, "uid");
297
            SearchResult searchResult = connection.search(searchRequest);
298

  
299
            if (!searchResult.getSearchEntries().isEmpty()) {
300
                return true;
301
            }
302

  
303
            return false;
304
        } catch (Exception e) {
305
            logger.error("", e);
306
            throw e;
307
        } finally {
308
            if (connection != null)
309
                connection.close();
310
        }
311
    }
312

  
313
    public String getEmailFromUsername(String username) throws Exception {
314
        LDAPConnection connection = null;
315
        try {
316
            logger.debug("getting email for user " + username);
317
            connection = new LDAPConnection(ldapAddress, ldapPort, ldapUsername, ldapPassword);
318
            Filter filter = Filter.createEqualityFilter("uid", username);
319
            SearchRequest searchRequest = new SearchRequest(ldapUsersDN, SearchScope.SUB, filter, "mail");
320
            SearchResult searchResult = connection.search(searchRequest);
321
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
322
                return entry.getAttributeValue("mail");
323
            }
324
            return null;
325
        } catch (Exception e) {
326
            logger.error("", e);
327
            throw e;
328
        } finally {
329
            if (connection != null)
330
                connection.close();
331
        }
332
    }
333

  
334
    public String getUsername(String email) throws LDAPException {
335

  
336
        LDAPConnection ldapConnection = new LDAPConnection(ldapAddress, ldapPort, ldapUsername, ldapPassword);
337

  
338
        Filter filter = Filter.createEqualityFilter("mail", email);
339
        SearchRequest searchRequest = new SearchRequest("dc=openaire,dc=eu", SearchScope.SUB, filter, "uid");
340

  
341
        SearchResult searchResult = ldapConnection.search(searchRequest);
342

  
343
        if (searchResult.getSearchEntries() != null) {
344
            if (searchResult.getSearchEntries().size() > 1) {
345
                logger.warn("An email is used for two different usernames! We only keep the first one");
346
            }
347

  
348
            if (searchResult.getSearchEntries().get(0) != null) {
349
                return searchResult.getSearchEntries().get(0).getAttributeValue("uid");
350
            }
351
        }
352

  
353
        return null;
354
    }
355

  
356
    public void setLdapPort(int ldapPort) {
357
        this.ldapPort = ldapPort;
358
    }
359

  
360
    public void setLdapAddress(String ldapAddress) {
361
        this.ldapAddress = ldapAddress;
362
    }
363

  
364
    public void setLdapUsername(String ldapUsername) {
365
        this.ldapUsername = ldapUsername;
366
    }
367

  
368
    public void setLdapPassword(String ldapPassword) {
369
        this.ldapPassword = ldapPassword;
370
    }
371

  
372
    public void setLdapUsersDN(String ldapUsersDN) {
373
        this.ldapUsersDN = ldapUsersDN;
374
    }
375

  
376

  
377
    public static void main(String[] args) {
378

  
379
        UserActionsLDAP ldap =  new UserActionsLDAP();
380

  
381
        String ldapAddress = "esperos.di.uoa.gr";
382
        String ldapUsername = "cn=admin,dc=openaire,dc=eu";
383
        String ldapPassword = "serenata";
384
        String ldapUsersDN = "ou=users,dc=openaire,dc=eu";
385
        int ldapPort = 389;
386

  
387
        ldap.setLdapAddress(ldapAddress);
388
        ldap.setLdapUsername(ldapUsername);
389
        ldap.setLdapPassword(ldapPassword);
390
        ldap.setLdapUsersDN(ldapUsersDN);
391
        ldap.setLdapPort(ldapPort);
392

  
393

  
394

  
395
        // CHECK: usernameExists(uid)
396
        // TERMINAL: ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu dn
397

  
398
//        try {
399
//            if (ldap.usernameExists("ngasparis"))
400
//                System.out.println("username exists");
401
//            else
402
//                System.out.println("username doesn't exist");
403
//
404
//        } catch (Exception e) {
405
//            e.printStackTrace();
406
//        }
407

  
408

  
409
        // CHECK: userExists(mail)
410
        // TERMINAL: ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu mail
411

  
412
//        try {
413
//            if (ldap.userExists("n.gasparis@di.uoa.gr"))
414
//                System.out.println("user exists");
415
//            else
416
//                System.out.println("user doesn't exist");
417
//        } catch (Exception e) {
418
//            e.printStackTrace();
419
//        }
420

  
421

  
422
        // CHECK: isUserActivated(mail)
423
        // TODO not sure!
424
        // TERMINAL: ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu mail
425

  
426
//        try {
427
//            if (ldap.isUserActivated("n.gasparis@di.uoa.gr"))
428
//                System.out.println("user is activated");
429
//            else
430
//                System.out.println("user isn't activated");
431
//        } catch (Exception e) {
432
//            e.printStackTrace();
433
//        }
434

  
435

  
436
        // CHECK: getUser(mail)
437
        // TERMINAL(mail): ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu mail
438
        // TERMINAL(firstname): ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu givenName
439
        // TERMINAL(lastname): ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu sn
440
        // TERMINAL(institution): ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu o
441
        // TERMINAL(username): ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu uid
442

  
443
//        try {
444
//            gr.uoa.di.validator.api.user.UserProfileIS userProfile = (gr.uoa.di.validator.api.user.UserProfileIS) ldap.getUser("n.gasparis@di.uoa.gr");
445
//            System.out.println("User with Firstname: "        + userProfile.getFname() +
446
//                                  "\n          Lastname: "    + userProfile.getLname() +
447
//                                  "\n          Username: "    + userProfile.getUsername() +
448
//                                  "\n          Email: "       + userProfile.getEmail() +
449
//                                  "\n          Institution: " + userProfile.getInstitution());
450
//
451
//        } catch (Exception e) {
452
//            e.printStackTrace();
453
//        }
454

  
455
        // CHECK: getEmailFromUsername(username)
456
        // ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu mail
457

  
458
//        try {
459
//            if (ldap.usernameExists("user is adminngasparis")) {
460
//                String email = ldap.getEmailFromUsername("ngasparis");
461
//                System.out.println("username exists with email: " + email);
462
//            }
463
//            else
464
//                System.out.println("username doesn't exist");
465
//
466
//        } catch (Exception e) {
467
//            e.printStackTrace();
468
//        }
469

  
470
        // CHECK: isAdmin(mail)
471
        // TODO not sure
472

  
473
//        try {
474
//            if (ldap.isAdmin("n.gasparis@di.uoa.gr"))
475
//                System.out.println("user is admin");
476
//            else
477
//                System.out.println("user isn't admin");
478
//        } catch (Exception e) {
479
//            e.printStackTrace();
480
//        }
481

  
482
        // CHECK: addUser(username, email, password, firstname, lastname)
483
        // TERMINAL (check only): ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu dn
484
//
485
//        try {
486
//            String activationId = ldap.addUser("sbaltzi", "sbaltzi@di.uoa.gr", "12345678", "sofia", "baltzi");
487
//            System.out.println("Added user with activation id:" + activationId);
488
//            gr.uoa.di.validator.api.user.UserProfileIS userProfile = (gr.uoa.di.validator.api.user.UserProfileIS) ldap.getUser("sbaltzi@di.uoa.gr");
489
//            System.out.println("User with Firstname: "        + userProfile.getFname() +
490
//                                  "\n          Lastname: "    + userProfile.getLname() +
491
//                                  "\n          Username: "    + userProfile.getUsername() +
492
//                                  "\n          Email: "       + userProfile.getEmail() +
493
//                                  "\n          Institution: " + userProfile.getInstitution());
494
//
495
//        } catch (Exception e) {
496
//            e.printStackTrace();
497
//        }
498

  
499
        // CHECK: correctCreds(mail, password)
500

  
501
//        try {
502
//            if (ldap.correctCreds("sbaltzi@di.uoa.gr", "12345678"))
503
//                System.out.println("correct credentials");
504
//            else
505
//                System.out.println("wrong credentials");
506
//        } catch (Exception e) {
507
//            e.printStackTrace();
508
//        }
509

  
510

  
511
        // CHECK: editUser()
512
        // TERMINAL(mail): ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu mail
513
        // TERMINAL(firstname): ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu givenName
514
        // TERMINAL(lastname): ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu sn
515
        // TERMINAL(institution): ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu o
516
        // TERMINAL(username): ldapsearch -x -LLL -h esperos.di.uoa.gr -b dc=openaire,dc=eu uid
517

  
518
//        try {
519
//            ldap.editUser("sbaltzi@di.uoa.gr", "sofie", "baltzi", "di");
520
//            gr.uoa.di.validator.api.user.UserProfileIS userProfile = (gr.uoa.di.validator.api.user.UserProfileIS) ldap.getUser("sbaltzi@di.uoa.gr");
521
//            System.out.println("User with Firstname: "        + userProfile.getFname() +
522
//                                  "\n          Lastname: "    + userProfile.getLname() +
523
//                                  "\n          Username: "    + userProfile.getUsername() +
524
//                                  "\n          Email: "       + userProfile.getEmail() +
525
//                                  "\n          Institution: " + userProfile.getInstitution());
526
//
527
//        } catch (Exception e) {
528
//            e.printStackTrace();
529
//        }
530

  
531
        // CHECK: prepareResetPassword(mail)
532
        // CHECK: resetPassword(mail, newpassword)
533

  
534
//        try {
535
//            String uuid = ldap.prepareResetPassword("sbaltzi@di.uoa.gr");
536
//            System.out.println("uuid is " + uuid);
537
//            ldap.resetPassword(uuid, "12345678");
538
//            if (ldap.correctCreds("sbaltzi@di.uoa.gr", "12345678"))
539
//                System.out.println("correct credentials");
540
//            else
541
//                System.out.println("wrong credentials");
542
//        } catch (Exception e) {
543
//            e.printStackTrace();
544
//        }
545

  
546
    }
547
}
modules/uoa-user-management/tags/uoa-user-management-2.0.2/src/main/java/eu/dnetlib/openaire/user/ldap/MUserActionsLDAP.java
1
package eu.dnetlib.openaire.user.ldap;
2

  
3
import com.unboundid.ldap.sdk.*;
4
import eu.dnetlib.openaire.user.dao.RoleDAO;
5
import eu.dnetlib.openaire.user.dao.SQLMigrationUserDAO;
6
import eu.dnetlib.openaire.user.pojos.migration.LDAPUser;
7
import eu.dnetlib.openaire.user.pojos.migration.MigrationUser;
8
import eu.dnetlib.openaire.user.pojos.migration.Role;
9
import eu.dnetlib.openaire.user.store.LDAPConnector;
10
import org.apache.log4j.Logger;
11
import org.springframework.beans.factory.annotation.Autowired;
12

  
13
import java.sql.SQLException;
14

  
15
/**
16
 * Created by sofia on 7/11/2016.
17
 */
18
public class MUserActionsLDAP {
19

  
20
    @Autowired
21
    private LDAPConnector ldapConnector;
22

  
23
    private static final Logger logger = Logger.getLogger(MUserActionsLDAP.class);
24

  
25
    public  boolean authenticate(String cn, String password) throws LDAPException {
26
        LDAPConnection connection = ldapConnector.getConnection();
27
        String usersDN = ldapConnector.getUsersDN();
28

  
29
        try {
30
            logger.debug("checking if user " + cn + " entered a correct password when logging in");
31

  
32
            Filter filter = Filter.createEqualityFilter("cn", cn);
33

  
34
            SearchRequest searchRequest = new SearchRequest(usersDN, SearchScope.SUB, filter, "userPassword");
35
            SearchResult searchResult = connection.search(searchRequest);
36

  
37
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
38
                if (Joomla15PasswordHash.check(password, entry.getAttributeValue("userPassword")))
39
                    return true;
40
            }
41

  
42
            return false;
43
        }
44
        finally {
45
            if (connection != null)
46
                connection.close();
47
        }
48
    }
49

  
50
    public boolean usernameExists(String username) throws LDAPException
51
    {
52

  
53
        logger.debug("checking if username " + username + " exists");
54
        LDAPConnection connection = ldapConnector.getConnection();
55
        String usersDN = ldapConnector.getUsersDN();
56

  
57
        try {
58
            logger.debug("checking if username " + username + " exists");
59

  
60
            Filter filter = Filter.createEqualityFilter("cn", username);
61

  
62
            SearchRequest searchRequest = new SearchRequest(usersDN, SearchScope.SUB, filter, "cn");
63
            SearchResult searchResult = connection.search(searchRequest);
64

  
65
            if (!searchResult.getSearchEntries().isEmpty()) {
66
                logger.debug("User exists.");
67
                return true;
68
            }
69
            logger.debug("User does not exist.");
70
            return false;
71
        }
72
        finally {
73
            if (connection != null)
74
                connection.close();
75
        }
76
    }
77

  
78
    public boolean authenticateUser(String email, String password) throws LDAPException {
79
        LDAPConnection connection = ldapConnector.getConnection();
80
        String usersDN = ldapConnector.getUsersDN();
81

  
82
        try {
83
            logger.debug("checking if user " + email + " entered a correct password when logging in");
84
            Filter filter = Filter.createEqualityFilter("mail", email);
85

  
86
            SearchRequest searchRequest = new SearchRequest(usersDN, SearchScope.SUB, filter, "userPassword");
87
            SearchResult searchResult = connection.search(searchRequest);
88

  
89
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
90
                if (Joomla15PasswordHash.check(password, entry.getAttributeValue("userPassword")))
91
                    logger.debug("User exists.");
92
                    return true;
93
            }
94

  
95
            logger.debug("User does not exist.");
96
            return false;
97
        }
98
        finally {
99
            if (connection != null)
100
                connection.close();
101
        }
102
    }
103

  
104
    public String getRole(String email, String password) throws LDAPException, SQLException {
105

  
106
        boolean authenticated = authenticateUser(email, password);
107

  
108
        if (authenticated)
109
        {
110
            SQLMigrationUserDAO muDAO = new SQLMigrationUserDAO();
111
            MigrationUser mUser = new MigrationUser();
112
            mUser = muDAO.fetchByEmail(email);
113
            RoleDAO roleDAO = new RoleDAO();
114
            Role role = roleDAO.fetchById(mUser.getRoleId());
115
            return role.getRole();
116
        }
117
        return null;
118
    }
119

  
120
    public LDAPUser getUser(String username) throws LDAPException {
121

  
122
        LDAPConnection connection = ldapConnector.getConnection();
123
        String usersDN = ldapConnector.getUsersDN();
124

  
125
        try {
126

  
127
            logger.debug("getting user " + username + " from ldap");
128
            Filter filter = Filter.createEqualityFilter("cn",username);
129
            SearchRequest searchRequest =
130
                    new SearchRequest(usersDN, SearchScope.SUB, filter, "mail", "displayName", "cn");
131

  
132
            SearchResult searchResult = connection.search(searchRequest);
133
            LDAPUser user = new LDAPUser();
134

  
135
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
136
                user.setCn(entry.getAttributeValue("cn"));
137
                user.setEmail(entry.getAttributeValue("mail"));
138
                user.setDisplayName(entry.getAttributeValue("displayName"));
139
            }
140
            logger.debug("Cn = " + user.getCn() + " mail = " + user.getEmail() + " displayName = " + user.getDisplayName());
141
            return user;
142

  
143
        } finally {
144
            if (connection != null)
145
                connection.close();
146
        }
147
    }
148

  
149
}
modules/uoa-user-management/tags/uoa-user-management-2.0.2/src/main/java/eu/dnetlib/openaire/user/ldap/Joomla15PasswordHash.java
1
package eu.dnetlib.openaire.user.ldap;
2

  
3
import com.unboundid.util.Base64;
4

  
5
import java.security.GeneralSecurityException;
6
import java.security.MessageDigest;
7
import java.util.Random;
8

  
9
/**
10
 * Created by sofia on 31/10/2016.
11
 */
12
public class Joomla15PasswordHash {
13

  
14
    public static boolean check(String passwd,String dbEntry) {
15
        String hashed = "{MD5}"+ Base64.encode(pack(Joomla15PasswordHash.md5(passwd)));
16
        if(dbEntry.equals(hashed))
17
            return true;
18
        else
19
            return false;
20
    }
21

  
22
    static Random _rnd;
23

  
24
    public static String create(String passwd) {
25
        return "{MD5}"+Base64.encode(pack(Joomla15PasswordHash.md5(passwd)));
26
    }
27

  
28
    /** Takes the MD5 hash of a sequence of ASCII or LATIN1 characters,
29
     *  and returns it as a 32-character lowercase hex string.
30
     *
31
     *  Equivalent to MySQL's MD5() function
32
     *  and to perl's Digest::MD5::md5_hex(),
33
     *  and to PHP's md5().
34
     *
35
     *  Does no error-checking of the input,  but only uses the low 8 bits
36
     *  from each input character.
37
     */
38
    public static String md5(String data) {
39
        byte[] bdata = new byte[data.length()]; int i; byte[] hash;
40

  
41
        for (i=0;i<data.length();i++) bdata[i]=(byte)(data.charAt(i)&0xff );
42

  
43
        try {
44
            MessageDigest md5er = MessageDigest.getInstance("MD5");
45
            hash = md5er.digest(bdata);
46
        } catch (GeneralSecurityException e) { throw new RuntimeException(e); }
47

  
48
        StringBuffer r = new StringBuffer(32);
49
        for (i=0;i<hash.length;i++) {
50
            String x = Integer.toHexString(hash[i]&0xff);
51
            if (x.length()<2) r.append("0");
52
            r.append(x);
53
        }
54
        return r.toString();
55
    }
56

  
57
    public static byte[] pack(String md5) {
58
        byte[] bytes = new byte[16];
59
        int j = 0;
60
        for(int i=0; i < 31; i+=2) {
61
            bytes[j] = (byte) Integer.parseInt(md5.charAt(i)+""+md5.charAt(i+1),16);
62
            j++;
63
        }
64
        return bytes;
65
    }
66
}
modules/uoa-user-management/tags/uoa-user-management-2.0.2/src/main/java/eu/dnetlib/openaire/user/utils/VerifyRecaptcha.java
1
package eu.dnetlib.openaire.user.utils;
2

  
3
import org.apache.log4j.Logger;
4

  
5
import javax.json.Json;
6
import javax.json.JsonObject;
7
import javax.json.JsonReader;
8
import javax.net.ssl.HttpsURLConnection;
9
import java.io.BufferedReader;
10
import java.io.DataOutputStream;
11
import java.io.InputStreamReader;
12
import java.io.StringReader;
13
import java.net.URL;
14

  
15
public class VerifyRecaptcha {
16

  
17
    public static final String url = "https://www.google.com/recaptcha/api/siteverify";
18

  
19
    //private final static String USER_AGENT = "Mozilla/5.0";
20

  
21
    private static Logger logger = Logger.getLogger(VerifyRecaptcha.class);
22
    public static boolean verify(String gRecaptchaResponse, String secret) {
23

  
24
        logger.debug("Recaptch secret " + secret);
25
        logger.debug("response " + gRecaptchaResponse);
26
        
27
        if (gRecaptchaResponse == null || "".equals(gRecaptchaResponse)) {
28
            return false;
29
        }
30

  
31
        try{
32
            URL obj = new URL(url);
33
            HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
34

  
35
            // add reuqest header
36
            con.setRequestMethod("POST");
37
            //con.setRequestProperty("User-Agent", USER_AGENT);
38
            con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
39

  
40
            String postParams = "secret=" + secret + "&response="
41
                    + gRecaptchaResponse;
42

  
43
            // Send post request
44
            con.setDoOutput(true);
45
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
46
            wr.writeBytes(postParams);
47
            wr.flush();
48
            wr.close();
49

  
50
            int responseCode = con.getResponseCode();
51
            logger.debug("\nSending 'POST' request to URL : " + url);
52
            logger.debug("Post parameters : " + postParams);
53
            logger.info("recaptcha response Code : " + responseCode);
54

  
55
            BufferedReader in = new BufferedReader(new InputStreamReader(
56
                    con.getInputStream()));
57
            String inputLine;
58
            StringBuffer response = new StringBuffer();
59

  
60
            while ((inputLine = in.readLine()) != null) {
61
                response.append(inputLine);
62
            }
63
            in.close();
64

  
65
            // print result
66
            logger.debug(response.toString());
67

  
68
            //parse JSON response and return 'success' value
69
            JsonReader jsonReader = Json.createReader(new StringReader(response.toString()));
70
            JsonObject jsonObject = jsonReader.readObject();
71
            jsonReader.close();
72

  
73
            return jsonObject.getBoolean("success");
74

  
75
        } catch(Exception e){
76
            logger.error("Error validating recaptcha");
77
            return false;
78
        }
79
    }
80

  
81
}
modules/uoa-user-management/tags/uoa-user-management-2.0.2/src/main/java/eu/dnetlib/openaire/user/utils/LDAPActions.java
1
package eu.dnetlib.openaire.user.utils;
2

  
3
import com.unboundid.ldap.sdk.*;
4
import com.unboundid.ldap.sdk.extensions.PasswordModifyExtendedRequest;
5
import com.unboundid.ldap.sdk.extensions.PasswordModifyExtendedResult;
6
import eu.dnetlib.openaire.user.store.LDAPConnector;
7
import org.apache.commons.validator.routines.EmailValidator;
8
import org.apache.log4j.Logger;
9

  
10
import java.util.ArrayList;
11
import java.util.List;
12

  
13
/**
14
 * Created by kiatrop on 29/9/2017.
15
 */
16

  
17
public class LDAPActions {
18

  
19
    private LDAPConnector ldapConnector;
20

  
21
    private Logger logger = Logger.getLogger(LDAPConnector.class);
22

  
23
    public String getUsername(String email) throws LDAPException {
24
        Filter filter = Filter.createEqualityFilter("mail", email);
25
        SearchRequest searchRequest = new SearchRequest("dc=openaire,dc=eu", SearchScope.SUB, filter, "uid");
26
        SearchResult searchResult = ldapConnector.getConnection().search(searchRequest);
27

  
28
        if (searchResult.getSearchEntries() != null) {
29
            if (searchResult.getSearchEntries().size() > 1) {
30
                logger.warn("An email is used for two different usernames! We only keep the first one.");
31
            }
32

  
33
            if (searchResult.getSearchEntries().size() == 0) {
34
                return null;
35
            }
36

  
37
            if (searchResult.getSearchEntries().get(0) != null) {
38
                return searchResult.getSearchEntries().get(0).getAttributeValue("uid");
39
            }
40
        }
41

  
42
        return null;
43
    }
44

  
45
    public Entry createUser(String username, String email, String firstName, String lastName, String institution, String password) throws Exception {
46

  
47
        if(!InputValidator.isValidUsername(username)) {
48
            throw new CustomLDAPException("Invalid username!");
49
        }
50

  
51
        if(!EmailValidator.getInstance().isValid(email)){
52
            throw new CustomLDAPException("Invalid email!");
53
        }
54

  
55
        if(!InputValidator.isValidPassword(password)) {
56
            throw new CustomLDAPException("Invalid password!");
57
        }
58

  
59
        Filter uidFilter = Filter.createEqualityFilter("uid", username);
60
        SearchRequest uidRequest = new SearchRequest("dc=openaire,dc=eu", SearchScope.SUB, uidFilter, "cn", "mail", "uid", "objectClass");
61

  
62
        Filter mailFilter = Filter.createEqualityFilter("mail", email);
63
        SearchRequest mailRequest = new SearchRequest("dc=openaire,dc=eu", SearchScope.SUB, mailFilter, "cn", "mail", "uid", "objectClass");
64

  
65
        SearchResult searchResult = ldapConnector.getConnection().search(uidRequest);
66
        if(!searchResult.getSearchEntries().isEmpty()){
67
            throw new CustomLDAPException("Username " + username + " already exists!");
68
        }
69
        searchResult = ldapConnector.getConnection().search(mailRequest);
70
        if(!searchResult.getSearchEntries().isEmpty()){
71
            throw new CustomLDAPException("Email " + email + " already exists!");
72
        }
73

  
74
        Entry entry = new Entry("dn: uid=" + username + ",ou=users,dc=openaire,dc=eu",
75
                "objectClass: inetOrgPerson",
76
                "objectClass: eduPerson",
77
                "cn: "  + username,
78
                "uid: " + username,
79
                "displayName: " + firstName + " " + lastName,
80
                "mail: " + email,
81
                "givenName: " + firstName,
82
                "sn: " + lastName,
83
                "eduPersonPrincipalName: " + username + "@openaire.eu");
84

  
85
        if(institution != null && !institution.isEmpty()) {
86
            entry.addAttribute("o", institution);
87
        }
88

  
89
        ldapConnector.getConnection().add(entry);
90
        PasswordModifyExtendedRequest passwordModifyExtendedRequest = new PasswordModifyExtendedRequest(entry.getDN(), (String) null, password);
91
        PasswordModifyExtendedResult passwordModifyResult = (PasswordModifyExtendedResult) ldapConnector.getConnection().processExtendedOperation(passwordModifyExtendedRequest);
92
        logger.info("User: " + username + " was created successfully!");
93

  
94
        return entry;
95
    }
96

  
97
    public void updateUser(String username, String email, String firstName, String lastName, String password) throws Exception {
98
        SearchRequest searchRequest = new SearchRequest("dc=openaire,dc=eu", SearchScope.SUB, Filter.createEqualityFilter("uid", username), "mail", "givenName", "sn", "displayName");
99
        SearchResult searchResult = ldapConnector.getConnection().search(searchRequest);
100
        List<Modification> mods = new ArrayList<>();
101

  
102
        if (!searchResult.getSearchEntries().isEmpty()) {
103
            Entry entry = searchResult.getSearchEntries().get(0);
104
            if(!entry.getAttributeValue("mail").equals(email)){
105
                if(!EmailValidator.getInstance().isValid(email)){
106
                    throw new CustomLDAPException("Invalid email!");
107
                }
108
                Filter uidFilter = Filter.createEqualityFilter("uid", username);
109
                Filter mailFilter = Filter.createEqualityFilter("mail", email);
110
                SearchRequest mailRequest = new SearchRequest("dc=openaire,dc=eu", SearchScope.SUB, Filter.createANDFilter(mailFilter, Filter.createNOTFilter(uidFilter)), "mail", "givenName", "sn", "displayName");
111
                SearchResult mailResult = ldapConnector.getConnection().search(mailRequest);
112
                if(!mailResult.getSearchEntries().isEmpty()){
113
                    throw new CustomLDAPException("Email " + email + " already in use!");
114
                }
115
                mods.add(new Modification(ModificationType.REPLACE, "mail", email));
116
            }
117
            if(entry.getAttributeValue("givenName") == null){
118
                mods.add(new Modification(ModificationType.ADD, "givenName", firstName));
119
            } else if(!entry.getAttributeValue("givenName").equals(firstName)){
120
                mods.add(new Modification(ModificationType.REPLACE, "givenName", firstName));
121
            }
122
            if(entry.getAttributeValue("sn") == null){
123
                mods.add(new Modification(ModificationType.ADD, "sn", lastName));
124
            } else if(!entry.getAttributeValue("sn").equals(lastName)){
125
                mods.add(new Modification(ModificationType.REPLACE, "sn", lastName));
126
            }
127
            if(entry.getAttributeValue("displayName") == null) {
128
                mods.add(new Modification(ModificationType.ADD, "displayName", firstName + " " + lastName));
129
            } else if (!entry.getAttributeValue("displayName").equals(firstName + " " + lastName)) {
130
                mods.add(new Modification(ModificationType.REPLACE, "displayName", firstName + " " + lastName));
131
            }
132

  
133
            if(!InputValidator.isValidPassword(password)) {
134
                throw new CustomLDAPException("Invalid password!");
135
            }
136

  
137
            //mods.add(new Modification(ModificationType.REPLACE, "userPassword",password));
138
            if(!mods.isEmpty()) {
139
                ldapConnector.getConnection().modify(entry.getDN(), mods);
140
            }
141
            PasswordModifyExtendedRequest passwordModifyExtendedRequest = new PasswordModifyExtendedRequest(entry.getDN(), (String) null, password);
142
            PasswordModifyExtendedResult passwordModifyResult = (PasswordModifyExtendedResult) ldapConnector.getConnection().processExtendedOperation(passwordModifyExtendedRequest);
143
        } else {
144
            throw new CustomLDAPException("Username " + username + " not found!");
145
        }
146
    }
147

  
148
//    public void resetPassword(String username, String email, String password) throws Exception {
149
//        SearchRequest searchRequest = new SearchRequest("dc=openaire,dc=eu", SearchScope.SUB, Filter.createEqualityFilter("uid", username), "mail");
150
//        SearchResult searchResult = ldapConnector.getConnection().search(searchRequest);
151
//        List<Modification> mods = new ArrayList<>();
152
//
153
//        if (!searchResult.getSearchEntries().isEmpty()) {
154
//            Entry entry = searchResult.getSearchEntries().get(0);
155
//            if(!entry.getAttributeValue("mail").equals(email)){
156
//                if(!EmailValidator.getInstance().isValid(email)){
157
//                    throw new CustomLDAPException("Invalid email!");
158
//                }
159
//                Filter uidFilter = Filter.createEqualityFilter("uid", username);
160
//                Filter mailFilter = Filter.createEqualityFilter("mail", email);
161
//                SearchRequest mailRequest = new SearchRequest("dc=openaire,dc=eu", SearchScope.SUB, Filter.createANDFilter(mailFilter, Filter.createNOTFilter(uidFilter)), "mail", "givenName", "sn", "displayName");
162
//                SearchResult mailResult = ldapConnector.getConnection().search(mailRequest);
163
//                if(!mailResult.getSearchEntries().isEmpty()){
164
//                    throw new CustomLDAPException("Email " + email + " already in use!");
165
//                }
166
//                mods.add(new Modification(ModificationType.REPLACE, "mail", email));
167
//            }
168
//            //mods.add(new Modification(ModificationType.REPLACE, "userPassword",password));
169
//            if(!mods.isEmpty()) {
170
//                ldapConnector.getConnection().modify(entry.getDN(), mods);
171
//            }
172
//              if(!password.matches("(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,}")){
173
//                   throw new CustomLDAPException("Invalid password!");
174
//              }
175
//            PasswordModifyExtendedRequest passwordModifyExtendedRequest = new PasswordModifyExtendedRequest(entry.getDN(), (String) null, password);
176
//            PasswordModifyExtendedResult passwordModifyResult = (PasswordModifyExtendedResult) ldapConnector.getConnection().processExtendedOperation(passwordModifyExtendedRequest);
177
//        } else {
178
//            throw new CustomLDAPException("Username " + username + " not found!");
179
//        }
180
//    }
181

  
182
    public void deleteUser(String username) throws Exception {
183
        LDAPConnection connection = ldapConnector.getConnection();
184

  
185
        try {
186
            logger.info("User: " + username + "was deleted!");
187
            ldapConnector.getConnection().delete("uid=" + username + "," + ldapConnector.getUsersDN());
188
        } catch (Exception e) {
189
            logger.error("Fail to delete user.", e);
190
            throw e;
191
        } finally {
192
            if (connection != null)
193
                connection.close();
194
        }
195
    }
196

  
197
    public void deleteZombieUser(String username) throws Exception {
198
        LDAPConnection connection = ldapConnector.getConnection();
199

  
200
        try {
201
            logger.info("User: " + username + "was deleted!");
202
            ldapConnector.getConnection().delete("uid=" + username + "," + ldapConnector.getZombiesDN());
203
        } catch (Exception e) {
204
            logger.error("Fail to delete user.", e);
205
            throw e;
206
        } finally {
207
            if (connection != null)
208
                connection.close();
209
        }
210
    }
211

  
212
    public String getUsersEmail(String username) throws Exception {
213
        LDAPConnection connection = ldapConnector.getConnection();
214
        try {
215
            logger.debug("getting email for user " + username);
216
            Filter filter = Filter.createEqualityFilter("uid", username);
217
            SearchRequest searchRequest = new SearchRequest(ldapConnector.getUsersDN(), SearchScope.SUB, filter, "mail");
218
            SearchResult searchResult = connection.search(searchRequest);
219
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
220
                return entry.getAttributeValue("mail");
221
            }
222
            return null;
223
        } catch (Exception e) {
224
            logger.error("Fail to get user's email exists.", e);
225
            throw e;
226
        } finally {
227
            if (connection != null)
228
                connection.close();
229
        }
230
    }
231

  
232
    public Entry createZombieUser(String username, String email, String firstName, String lastName, String institution, String password) throws Exception {
233

  
234
        if(!InputValidator.isValidUsername(username)) {
235
            throw new CustomLDAPException("Invalid username!");
236
        }
237

  
238
        if(!EmailValidator.getInstance().isValid(email)){
239
            throw new CustomLDAPException("Invalid email!");
240
        }
241

  
242
        if(!InputValidator.isValidPassword(password)) {
243
            throw new CustomLDAPException("Invalid password!");
244
        }
245

  
246
        Filter uidFilter = Filter.createEqualityFilter("uid", username);
247
        SearchRequest uidRequest = new SearchRequest("dc=openaire,dc=eu", SearchScope.SUB, uidFilter, "cn", "mail", "uid", "objectClass");
248

  
249
        Filter mailFilter = Filter.createEqualityFilter("mail", email);
250
        SearchRequest mailRequest = new SearchRequest("dc=openaire,dc=eu", SearchScope.SUB, mailFilter, "cn", "mail", "uid", "objectClass");
251

  
252
        SearchResult searchResult = ldapConnector.getConnection().search(uidRequest);
253
        if(!searchResult.getSearchEntries().isEmpty()){
254
            logger.info("S" + searchResult.getSearchEntries());
255
            throw new CustomLDAPException("Username " + username + " already exists!");
256
        }
257
        searchResult = ldapConnector.getConnection().search(mailRequest);
258
        if(!searchResult.getSearchEntries().isEmpty()){
259
            throw new CustomLDAPException("Email " + email + " already exists!");
260
        }
261

  
262
        Entry entry = new Entry("dn: uid=" + username + ",ou=zombies,dc=openaire,dc=eu",
263
                "objectClass: inetOrgPerson",
264
                "objectClass: eduPerson",
265
                "cn: "  + username,
266
                "uid: " + username,
267
                "displayName: " + firstName + " " + lastName,
268
                "mail: " + email,
269
                "givenName: " + firstName,
270
                "sn: " + lastName,
271
                "eduPersonPrincipalName: " + username + "@openaire.eu");
272

  
273
        if(institution != null && !institution.isEmpty()) {
274
            entry.addAttribute("o", institution);
275
        }
276

  
277
        ldapConnector.getConnection().add(entry);
278
        PasswordModifyExtendedRequest passwordModifyExtendedRequest = new PasswordModifyExtendedRequest(entry.getDN(), (String) null, password);
279
        PasswordModifyExtendedResult passwordModifyResult = (PasswordModifyExtendedResult) ldapConnector.getConnection().processExtendedOperation(passwordModifyExtendedRequest);
280
        logger.info("User: " + username + " was created successfully!");
281

  
282
        return entry;
283
    }
284

  
285
    public void moveUser(String username) throws Exception {
286
        LDAPConnection connection = ldapConnector.getConnection();
287

  
288
        try {
289
            logger.info("Moving user:" +username);
290
            ModifyDNRequest modifyDNRequest =
291
                    new ModifyDNRequest("uid=" + username + ",ou=zombies,dc=openaire,dc=eu", "uid=" + username, true, "ou=users,dc=openaire,dc=eu");
292

  
293
            LDAPResult result = connection.modifyDN(modifyDNRequest);
294
        }
295
        catch (Exception e){
296
            logger.error("Fail to move user.", e);
297
            throw e;
298
        } finally {
299
            if (connection != null)
300
                connection.close();
301
        }
302

  
303
    }
304

  
305
    public boolean isZombieUsersEmail(String email) throws Exception{
306
        LDAPConnection connection = ldapConnector.getConnection();
307

  
308
        try {
309
            logger.debug("checking if zombie user " + email + " exists in ldap");
310
            Filter filter = Filter.createEqualityFilter("mail", email);
311
            SearchRequest searchRequest = new SearchRequest(ldapConnector.getZombiesDN(), SearchScope.SUB, filter, "mail");
312
            SearchResult searchResult = connection.search(searchRequest);
313

  
314
            if (!searchResult.getSearchEntries().isEmpty()) {
315
                logger.info("Zombie user with email: " + email + " exists!");
316
                return true;
317
            } else {
318
                return false;
319
            }
320
        } catch (Exception e) {
321
            logger.error("Fail to check if zombie user email exists.", e);
322
            throw e;
323
        } finally {
324
            if (connection != null)
325
                connection.close();
326
        }
327
    }
328

  
329
    public boolean isZombieUsersUsername(String username) throws Exception {
330
        LDAPConnection connection = ldapConnector.getConnection();
331

  
332
        try {
333
            logger.debug("checking if zombie user " + username + " exists in ldap");
334
            Filter filter = Filter.createEqualityFilter("uid", username);
335
            SearchRequest searchRequest = new SearchRequest(ldapConnector.getZombiesDN(), SearchScope.SUB, filter, "uid");
336
            SearchResult searchResult = connection.search(searchRequest);
337

  
338
            if (!searchResult.getSearchEntries().isEmpty()) {
339
                logger.info("Zombie user with username: " + username + " exists!");
340
                return true;
341
            } else {
342
                return false;
343
            }
344

  
345
        } catch (Exception e) {
346
            logger.error("Fail to check if zombie username exists.", e);
347
            throw e;
348
        } finally {
349
            if (connection != null)
350
                connection.close();
351
        }
352
    }
353

  
354
    public String getZombieUsersEmail(String username) throws Exception {
355
        LDAPConnection connection = ldapConnector.getConnection();
356
        try {
357
            logger.debug("getting email for zombie user " + username);
358
            Filter filter = Filter.createEqualityFilter("uid", username);
359
            SearchRequest searchRequest = new SearchRequest(ldapConnector.getZombiesDN(), SearchScope.SUB, filter, "mail");
360
            SearchResult searchResult = connection.search(searchRequest);
361
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
362
                return entry.getAttributeValue("mail");
363
            }
364
            return null;
365
        } catch (Exception e) {
366
            logger.error("Fail to get zombie user's email exists.", e);
367
            throw e;
368
        } finally {
369
            if (connection != null)
370
                connection.close();
371
        }
372
    }
373

  
374
    public String getZombieUsersUserName(String email) throws LDAPException {
375
        Filter filter = Filter.createEqualityFilter("mail", email);
376
        SearchRequest searchRequest = new SearchRequest(ldapConnector.getZombiesDN(), SearchScope.SUB, filter, "uid");
377
        SearchResult searchResult = ldapConnector.getConnection().search(searchRequest);
378

  
379
        if (searchResult.getSearchEntries() != null) {
380
            if (searchResult.getSearchEntries().size() > 1) {
381
                logger.warn("An email is used for two different usernames! We only keep the first one.");
382
            }
383

  
384
            if (searchResult.getSearchEntries().size() == 0) {
385
                return null;
386
            }
387

  
388
            if (searchResult.getSearchEntries().get(0) != null) {
389
                return searchResult.getSearchEntries().get(0).getAttributeValue("uid");
390
            }
391
        }
392

  
393
        return null;
394
    }
395

  
396
    public boolean emailExists(String email) throws Exception {
397
        LDAPConnection connection = ldapConnector.getConnection();
398

  
399
        try {
400
            logger.debug("checking if user " + email + " exists in ldap");
401
            Filter filter = Filter.createEqualityFilter("mail", email);
402
            SearchRequest searchRequest = new SearchRequest(ldapConnector.getUsersDN(), SearchScope.SUB, filter, "mail");
403
            SearchResult searchResult = connection.search(searchRequest);
404

  
405
            if (!searchResult.getSearchEntries().isEmpty()) {
406
                logger.info("User with email: " + email + " exists!");
407
                return true;
408
            } else {
409
                return false;
410
            }
411
        } catch (Exception e) {
412
            logger.error("Fail to check if user email exists.", e);
413
            throw e;
414
        } finally {
415
            if (connection != null)
416
                connection.close();
417
        }
418
    }
419

  
420
    public boolean usernameExists(String username) throws Exception {
421
        LDAPConnection connection = ldapConnector.getConnection();
422

  
423
        try {
424
            logger.debug("checking if user " + username + " exists in ldap");
425
            Filter filter = Filter.createEqualityFilter("uid", username);
426
            SearchRequest searchRequest = new SearchRequest(ldapConnector.getUsersDN(), SearchScope.SUB, filter, "uid");
427
            SearchResult searchResult = connection.search(searchRequest);
428

  
429
            if (!searchResult.getSearchEntries().isEmpty()) {
430
                logger.info("User with username: " + username + " exists!");
431
                return true;
432
            } else {
433
                return false;
434
            }
435

  
436
        } catch (Exception e) {
437
            logger.error("Fail to check if username exists.", e);
438
            throw e;
439
        } finally {
440
            if (connection != null)
441
                connection.close();
442
        }
443
    }
444

  
445
    public void resetPassword(String username, String password) throws Exception {
446
        LDAPConnection connection = ldapConnector.getConnection();
447

  
448
        try {
449

  
450
            Filter filter = Filter.createEqualityFilter("uid", username);
451
            SearchRequest searchRequest = new SearchRequest(ldapConnector.getUsersDN(), SearchScope.SUB, filter, "uid");
452
            SearchResult searchResult = connection.search(searchRequest);
453
            String dn = null;
454
            for (SearchResultEntry entry : searchResult.getSearchEntries()) {
455
                dn = "uid=" + entry.getAttributeValue("uid") + "," + ldapConnector.getUsersDN();
456
                //logger.info("dn " + dn);
457
            }
458

  
459
            if(!InputValidator.isValidPassword(password)) {
460
                throw new CustomLDAPException("Invalid password!");
461
            }
462

  
463
            //Modification mod1 = new Modification(ModificationType.REPLACE, "userPassword", password);
464
            PasswordModifyExtendedRequest passwordModifyExtendedRequest = new PasswordModifyExtendedRequest(dn, (String) null, password);
465
            PasswordModifyExtendedResult passwordModifyResult = (PasswordModifyExtendedResult) ldapConnector.getConnection().processExtendedOperation(passwordModifyExtendedRequest);
466
            //connection.modify(dn, mod1);
467

  
468
        } catch (Exception e) {
469
            logger.error("Fail to reset password.", e);
470
            throw e;
471

  
472
        } finally {
473
            if (connection != null)
474
                connection.close();
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff