Project

General

Profile

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
}
(3-3/3)