source: contrib/funambol/v71ga/funambol/ds/ds-server/src/main/java/com/funambol/server/security/LdapUserProvisioningOfficer.java @ 1345

Revision 1345, 26.7 KB checked in by emersonfaria, 15 years ago (diff)

Ticket #626 - Feito check-in da versão inicial do módulo LdapUserProvisioningOfficer?.

Line 
1/*******************************************************************************
2 * Author: Emerson faria Nobre - emerson-faria.nobre@serpro.gov.br - january/09
3 * Organization: SERPRO - Servico Federal de Processamento de Dados
4 * Description: This source code is an extension of UserProvisioningOfficer.java
5 *              New capabilities implemented:
6 *              - Authenticate user in Ldap.
7 *              - Automatically Create/Update the MailServerAccount
8 *                (tables: fnbl_email_account, fnbl_email_enable_account,
9 *                 fnbl_email_push_registry)
10 * Changes:
11 * Author/Date/Description:
12 * Emerson Faria Nobre - june/2009 - Inserted parameters UserFieldName and
13 *              PwdFieldName because the LDAP Server of each Company that I
14 *              need to install Funambol use diferent names for this fields.
15 *
16 *******************************************************************************
17 *
18 *
19 *
20 * Funambol is a mobile platform developed by Funambol, Inc.
21 * Copyright (C) 2006 - 2007 Funambol, Inc.
22 *
23 * This program is free software; you can redistribute it and/or modify it under
24 * the terms of the GNU Affero General Public License version 3 as published by
25 * the Free Software Foundation with the addition of the following permission
26 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
27 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
28 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
29 *
30 * This program is distributed in the hope that it will be useful, but WITHOUT
31 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
32 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
33 * details.
34 *
35 * You should have received a copy of the GNU Affero General Public License
36 * along with this program; if not, see http://www.gnu.org/licenses or write to
37 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
38 * MA 02110-1301 USA.
39 *
40 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
41 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
42 *
43 * The interactive user interfaces in modified source and object code versions
44 * of this program must display Appropriate Legal Notices, as required under
45 * Section 5 of the GNU Affero General Public License version 3.
46 *
47 * In accordance with Section 7(b) of the GNU Affero General Public License
48 * version 3, these Appropriate Legal Notices must retain the display of the
49 * "Powered by Funambol" logo. If the display of the logo is not reasonably
50 * feasible for technical reasons, the Appropriate Legal Notices must display
51 * the words "Powered by Funambol".
52 */
53package com.funambol.server.security;
54
55import com.funambol.framework.core.Authentication;
56import com.funambol.framework.core.Cred;
57import com.funambol.framework.security.Sync4jPrincipal;
58import com.funambol.framework.server.Sync4jUser;
59import com.funambol.framework.server.store.NotFoundException;
60import com.funambol.framework.server.store.PersistentStoreException;
61import com.funambol.framework.tools.Base64;
62import com.funambol.framework.tools.beans.LazyInitBean;
63
64import com.funambol.server.admin.AdminException;
65import com.funambol.server.admin.UserManager;
66import com.funambol.server.config.Configuration;
67
68// Imports for LDAP customization - SERPRO
69import java.util.Hashtable;
70import javax.naming.*;
71import javax.naming.directory.*;
72
73// Imports for Insert/Update MailServerAccount - SERPRO
74import com.funambol.email.model.*;
75import com.funambol.email.console.dao.ConsoleDAO;
76import com.funambol.email.exception.*;
77import com.funambol.email.util.Def;
78import com.funambol.pushlistener.service.registry.RegistryEntryStatus;
79import com.funambol.framework.filter.*;
80
81/**
82 * This is an implementation of the <i>Officier</i> interface. It provides
83 * the user provisioning so if an user is not in the database he will be added.
84 * It requires basic authentication
85 *
86 * @version $Id: UserProvisioningOfficer.java,v 1.4 2008-06-24 12:50:06 piter_may Exp $
87 */
88public class LdapUserProvisioningOfficer
89        extends DBOfficer
90        implements LazyInitBean {
91
92    // New properties - SERPRO
93    ldap objLdap;
94    MailServerAccount msa;
95    Boolean InsertMSA;
96    String ldapIP;
97    String ldapPort;
98
99    // New propertie - SERPRO - 2009/06
100    String ldapStartSearchPath;
101
102    boolean MsaEnablePush;
103    boolean MsaEnablePolling;
104    int MsaRefreshTime;
105    int MsaMaxEmailNumber;
106    int MsaMaxImapEmails;
107
108    // ------------------------------------------------------------ Constructors
109    public LdapUserProvisioningOfficer() {
110        super();
111
112        // New instance - SERPRO
113        msa = new MailServerAccount();
114    }
115
116    // ---------------------------------------------------------- Public methods
117    public void init() {
118        super.init();
119
120    }
121
122    /**
123     * Authenticates a credential.
124     *
125     * @param credential the credential to be authenticated
126     *
127     * @return the Sync4jUser if the credential is autenticated, null otherwise
128     */
129    public Sync4jUser authenticateUser(Cred credential) {
130
131        Configuration config = Configuration.getConfiguration();
132        ps = config.getStore();
133
134        userManager = (UserManager) config.getUserManager();
135
136        String type = credential.getType();
137
138        if ((Cred.AUTH_TYPE_BASIC).equals(type)) {
139            return authenticateBasicCredential(credential);
140        } else if ((Cred.AUTH_TYPE_MD5).equals(type)) {
141            return authenticateMD5Credential(credential);
142        }
143
144        return null;
145    }
146
147    /**
148     * Gets the supported authentication type
149     *
150     * @return the basic authentication type
151     */
152    public String getClientAuth() {
153        return Cred.AUTH_TYPE_BASIC;
154    }
155
156    // ------------------------------------------------------- Protected Methods
157
158    // Insert/Update MailServerAccount (MSA) - SERPRO
159    protected void InsertUpdateMSA(String user, String pwd) {
160
161        if (log.isTraceEnabled()) {
162            log.trace("LdapUserProvisioningOfficer - I will create cdao object");
163        }
164        try {
165            ConsoleDAO cdao = new ConsoleDAO();
166
167            //
168            // Insert/Update MailServerAccount - SERPRO
169            //
170            if (log.isTraceEnabled()) {
171                log.trace("LdapUserProvisioningOfficer - I will verify if it is insert or update");
172            }
173            msa = null;
174
175            if (log.isTraceEnabled()) {
176                log.trace("LdapUserProvisioningOfficer - before command cdao.getUser(user)");
177            }
178
179            msa = cdao.getUser(user);
180
181            if (log.isTraceEnabled()) {
182                log.trace("LdapUserProvisioningOfficer - after command cdao.getUser(user)");
183            }
184
185            if (msa == null) {
186                msa = new MailServerAccount();
187                this.InsertMSA = true;
188            } else {
189                this.InsertMSA = false;
190            }
191
192            if (log.isTraceEnabled()) {
193                log.trace("LdapUserProvisioningOfficer - after if (msa == null)");
194            }
195
196            if (log.isTraceEnabled()) {
197                log.trace("LdapUserProvisioningOfficer - msa.getUsername() = " + msa.getUsername());
198            }
199
200            if ((log.isTraceEnabled()) && (this.InsertMSA == true)) {
201                log.trace("LdapUserProvisioningOfficer - It is Insert - username = " + msa.getUsername());
202            }
203
204            if ((log.isTraceEnabled()) && (this.InsertMSA == false)) {
205                log.trace("LdapUserProvisioningOfficer - It is Update - username = " + msa.getUsername());
206            }
207
208
209            if (!this.InsertMSA) {
210                if (log.isTraceEnabled()) {
211                    log.trace("LdapUserProvisioningOfficer - The key Id = " + msa.getId());
212                    log.trace("LdapUserProvisioningOfficer - The key UserName = " + msa.getUsername());
213                }
214            }
215            if (this.InsertMSA) {
216                if (log.isTraceEnabled()) {
217                    log.trace("LdapUserProvisioningOfficer - I will set setUserName" + user);
218                }
219                msa.setUsername(user);
220            }
221            if (log.isTraceEnabled()) {
222                log.trace("LdapUserProvisioningOfficer - I already set setMsLogin" + user);
223            }
224            msa.setMsLogin(user);
225            if (log.isTraceEnabled()) {
226                log.trace("LdapUserProvisioningOfficer - I will set setMsPassword");
227            }
228            msa.setMsPassword(pwd);
229            if (log.isTraceEnabled()) {
230                log.trace("LdapUserProvisioningOfficer - I will set setMsAddress = " + objLdap.getmail());
231            }
232            msa.setMsAddress(objLdap.getmail());
233            if (log.isTraceEnabled()) {
234                log.trace("LdapUserProvisioningOfficer - I will set setPush = " + this.getMsaEnablePush());
235            }
236            msa.setPush(this.getMsaEnablePush());
237            if (log.isTraceEnabled()) {
238                log.trace("LdapUserProvisioningOfficer - I will set setMaxEmailNumber = " + this.getMsaMaxEmailNumber());
239            }
240            msa.setMaxEmailNumber(this.getMsaMaxEmailNumber());
241            if (log.isTraceEnabled()) {
242                log.trace("LdapUserProvisioningOfficer - I will set setMaxImapEmail = " + this.getMsaMaxImapEmails());
243            }
244            msa.setMaxImapEmail(this.getMsaMaxImapEmails());
245            if (log.isTraceEnabled()) {
246                log.trace("LdapUserProvisioningOfficer - I will set setPeriod = " + this.getMsaRefreshTime());
247            }
248            msa.setPeriod(this.getMsaRefreshTime());
249            if (log.isTraceEnabled()) {
250                log.trace("LdapUserProvisioningOfficer - I will set setActive = " + this.getMsaEnablePolling());
251            }
252            msa.setActive(this.getMsaEnablePolling());
253
254            // set the push listener framework properties
255            if (log.isTraceEnabled()) {
256                log.trace("LdapUserProvisioningOfficer - I will set fnbl_email_push_registry");
257            }
258            msa.setTaskBeanFile(Def.DEFAULT_INBOX_LISTENER_BEAN_FILE);
259            if (this.InsertMSA) {
260                msa.setStatus(RegistryEntryStatus.NEW);
261            } else {
262                msa.setStatus(RegistryEntryStatus.UPDATED);
263            }
264
265            msa.setLastUpdate(System.currentTimeMillis());
266            if (log.isTraceEnabled()) {
267                log.trace("LdapUserProvisioningOfficer - I already set fnbl_email_push_registry");
268            }
269
270            /*if (log.isTraceEnabled()) {
271            log.trace("LdapUserProvisioningOfficer - I will set 100 to cdao.getPubMailServer");
272            }
273            msa.setMailServer(cdao.getPubMailServer("100"));*/
274
275            String[] param = {"description"};
276            String[] value = {"expresso"};
277            String[] operator = {WhereClause.OPT_EQ};
278            MailServer[] ms = cdao.getPubMailServers(new WhereClause(param[0], new String[]{value[0]}, operator[0], false));
279            if (log.isTraceEnabled()) {
280                log.trace("LdapUserProvisioningOfficer - I found the MailServer expresso -  ID = " + ms[0].getMailServerId());
281            }
282            msa.setMailServer(cdao.getPubMailServer(ms[0].getMailServerId()));
283
284            if (this.InsertMSA) {
285                if (log.isTraceEnabled()) {
286                    log.trace("LdapUserProvisioningOfficer - I will call insertUser(msa)");
287                }
288                cdao.insertUser(msa);
289            } else {
290                if (log.isTraceEnabled()) {
291                    log.trace("LdapUserProvisioningOfficer - I will call updateUser(msa)");
292                }
293                cdao.updateUser(msa);
294            }
295        } catch (InboxListenerConfigException e) {
296            log.error("LdapUserProvisioningOfficer - Error creating DAO layer to Insert/Update Mail User: ", e);
297        } catch (DBAccessException e) {
298            log.error("LdapUserProvisioningOfficer - Error accessing Database to Insert/Update Mail User:  ", e);
299        }
300    }
301
302    /**
303     * Checks the given credential. If the user or the principal isn't found,
304     * they are created.
305     *
306     * @param credential the credential to check
307     *
308     * @return the Sync4jUser if the credential is autenticated, null otherwise
309     */
310    protected Sync4jUser authenticateBasicCredential(Cred credential) {
311        String username = null, password = null;
312
313        Authentication auth = credential.getAuthentication();
314        String deviceId = auth.getDeviceId();
315
316        String userpwd = new String(Base64.decode(auth.getData()));
317
318        int p = userpwd.indexOf(':');
319
320        if (p == -1) {
321            username = userpwd;
322            password = "";
323        } else {
324            username = (p > 0) ? userpwd.substring(0, p) : "";
325            password = (p == (userpwd.length() - 1)) ? "" : userpwd.substring(p + 1);
326        }
327
328        if (log.isTraceEnabled()) {
329            log.trace("User to check: " + username);
330        }
331
332        //
333        // Gets the user without checking the password
334        //
335        Sync4jUser user = getUser(username, null);
336        if (user == null) {
337
338            if (log.isTraceEnabled()) {
339                log.trace("User '" +
340                        username +
341                        "' not found. A new user will be created");
342            }
343
344            //
345            // LDAP Checkpoint - SERPRO
346            //
347            if (log.isTraceEnabled()) {
348                log.trace("LdapUserProvisioningOfficer - CheckPoint LDAP - getLdapIP: " + this.getLdapIP() + "  getLdapPort: " + this.getLdapPort());
349            }
350//            objLdap = new ldap(this.getLdapIP(), this.getLdapPort(), username, password);
351            objLdap = new ldap(this.getLdapIP(), this.getLdapPort(), username, password, this.getLdapStartSearchPath());
352
353            // Try to althenticate in LDAP - SERPRO
354            if (objLdap.getreturnStatus() == false) {
355                if (log.isTraceEnabled()) {
356                    log.trace("LdapUserProvisioningOfficer - LDAP Authentication Failure: " + objLdap.geterrorMsg() + " - " + objLdap.geterrorStatus());
357                }
358                return null;
359            }
360
361            try {
362                user = insertUser(username, password);
363                if (log.isTraceEnabled()) {
364                    log.trace("User '" + username + "' created");
365                }
366            } catch (Exception e) {
367                log.error("Error inserting a new user", e);
368                return null;
369            }
370
371            //
372            // Insert/Update MailServerAccount - SERPRO
373            //
374            this.InsertUpdateMSA(username, password);
375
376        } else {
377            if (log.isTraceEnabled()) {
378                log.trace("User '" + username + "' found");
379            }
380            //
381            // Check the password
382            //
383            //String storedPassword = user.getPassword();
384            //if (!password.equals(storedPassword)) {
385            //
386            // The user isn't authenticated
387            //
388            //if (log.isTraceEnabled()) {
389            //    log.trace("The sent password is different from the stored " + "one. User not authenticated");
390            //}
391            //return null;
392            //} else {
393            //
394            // Check the roles
395            //
396            boolean isASyncUser = isASyncUser(user);
397
398            if (isASyncUser) {
399                //
400                // User authenticated
401                //
402                if (log.isTraceEnabled()) {
403                    log.trace("User is a SyncUser");
404                }
405
406                //
407                // LDAP Checkpoint - SERPRO
408                //
409                if (log.isTraceEnabled()) {
410                    log.trace("LdapUserProvisioningOfficer - CheckPoint LDAP - getLdapIP: " + this.getLdapIP() + "  getLdapPort: " + this.getLdapPort());
411                }
412                objLdap = new ldap(this.getLdapIP(), this.getLdapPort(), username, password, this.getLdapStartSearchPath());
413
414                // Try to althenticate in LDAP - SERPRO
415                if (objLdap.getreturnStatus() == false) {
416                    if (log.isTraceEnabled()) {
417                        log.trace("LDAP Authentication Failure: " + objLdap.geterrorMsg() + " - " + objLdap.geterrorStatus());
418                    }
419                    return null;
420                }
421
422                //
423                // Insert/Update MailServerAccount - SERPRO
424                //
425                this.InsertUpdateMSA(username, password);
426            } else {
427                //
428                // User not authenticated
429                //
430                if (log.isTraceEnabled()) {
431                    log.trace("The user is not a '" + ROLE_USER + "'");
432                }
433                return null;
434            }
435        //}
436        }
437
438        //
439        // Verify that the principal for the specify deviceId and username exists
440        // Otherwise a new principal will be created
441        //
442        try {
443            handlePrincipal(user.getUsername(), deviceId);
444        } catch (PersistentStoreException e) {
445            log.error("Error handling the principal", e);
446            return null;
447        }
448        return user;
449    }
450
451    /**
452     * Insert a new user with the given username and password
453     *
454     * @param userName the username
455     * @param password the password
456     *
457     * @return the new user
458     *
459     * @throws AdminException in case of admin errors
460     * @throws PersistentStoreException if an error occurs
461     */
462    protected Sync4jUser insertUser(
463            String userName, String password)
464            throws AdminException, PersistentStoreException {
465
466        Sync4jUser user = new Sync4jUser();
467        user.setUsername(userName);
468        user.setPassword(password);
469        user.setFirstname(objLdap.getcn());
470        user.setRoles(new String[]{ROLE_USER});
471
472        // Update e-mail field of user table - Emerson Faria Nobre - SERPRO
473        user.setEmail(objLdap.getmail());
474
475        userManager.insertUser(user);
476        return user;
477    }
478
479    /**
480     * Returns the principal with the given username and deviceId.
481     * <code>null</code> if not found
482     * @param userName the username
483     * @param deviceId the device id
484     * @return the principal found or null.
485     * @throws PersistentStoreException if an error occurs
486     */
487    protected Sync4jPrincipal getPrincipal(String userName, String deviceId)
488            throws PersistentStoreException {
489
490        Sync4jPrincipal principal = null;
491
492        //
493        // Verify that exist the principal for the specify deviceId and username
494        //
495        principal =
496                Sync4jPrincipal.createPrincipal(userName, deviceId);
497
498        try {
499            ps.read(principal);
500        } catch (NotFoundException ex) {
501            return null;
502        }
503
504        return principal;
505    }
506
507    /**
508     * Inserts a new principal with the given userName and deviceId
509     * @param userName the username
510     * @param deviceId the device id
511     * @return the principal created
512     * @throws PersistentStoreException if an error occurs creating the principal
513     */
514    protected Sync4jPrincipal insertPrincipal(String userName, String deviceId)
515            throws PersistentStoreException {
516
517        //
518        // We must create a new principal
519        //
520        Sync4jPrincipal principal =
521                Sync4jPrincipal.createPrincipal(userName, deviceId);
522
523        ps.store(principal);
524
525        return principal;
526    }
527
528    /**
529     * Searchs if there is a principal with the given username and device id.
530     * if no principal is found, a new one is created.
531     * @param userName the user name
532     * @param deviceId the device id
533     * @return the found principal or the new one
534     */
535    protected Sync4jPrincipal handlePrincipal(String username, String deviceId)
536            throws PersistentStoreException {
537
538        Sync4jPrincipal principal = null;
539
540        //
541        // Verify if the principal for the specify deviceId and username exists
542        //
543
544        principal =
545                getPrincipal(username, deviceId);
546
547        if (log.isTraceEnabled()) {
548            log.trace("Principal '" + username +
549                    "/" +
550                    deviceId + "' " +
551                    ((principal != null) ? "found" : "not found. A new principal will be created"));
552        }
553
554        if (principal == null) {
555            principal = insertPrincipal(username, deviceId);
556            if (log.isTraceEnabled()) {
557                log.trace("Principal '" + username +
558                        "/" +
559                        deviceId + "' created");
560            }
561
562        }
563
564        return principal;
565    }
566
567    // Getters and Setters - SERPRO
568    public void setLdapIP(String pldapIP) {
569        this.ldapIP = pldapIP;
570    }
571
572    public String getLdapIP() {
573        return this.ldapIP;
574    }
575
576    public void setLdapPort(String pLdapPort) {
577        this.ldapPort = pLdapPort;
578    }
579
580    public String getLdapPort() {
581        return this.ldapPort;
582    }
583   
584    public void setLdapStartSearchPath(String pLdapStartSearchPath) {
585        this.ldapStartSearchPath = pLdapStartSearchPath;
586    }
587
588    public String getLdapStartSearchPath() {
589        return this.ldapStartSearchPath;
590    }
591
592    public void setMsaEnablePush(boolean pMsaEnablePush) {
593        this.MsaEnablePush = pMsaEnablePush;
594    }
595
596    public boolean getMsaEnablePush() {
597        return this.MsaEnablePush;
598    }
599
600    public void setMsaEnablePolling(boolean pMsaEnablePolling) {
601        this.MsaEnablePolling = pMsaEnablePolling;
602    }
603
604    public boolean getMsaEnablePolling() {
605        return this.MsaEnablePolling;
606    }
607
608    public void setMsaRefreshTime(int pMsaRefreshTime) {
609        this.MsaRefreshTime = pMsaRefreshTime;
610    }
611
612    public int getMsaRefreshTime() {
613        return this.MsaRefreshTime;
614    }
615
616    public void setMsaMaxEmailNumber(int pMsaMaxEmailNumber) {
617        this.MsaMaxEmailNumber = pMsaMaxEmailNumber;
618    }
619
620    public int getMsaMaxEmailNumber() {
621        return this.MsaMaxEmailNumber;
622    }
623
624    public void setMsaMaxImapEmails(int pMsaMaxImapEmails) {
625        this.MsaMaxImapEmails = pMsaMaxImapEmails;
626    }
627
628    public int getMsaMaxImapEmails() {
629        return this.MsaMaxImapEmails;
630    }
631}
632
633// Class to manage LDAP - SERPRO
634class ldap {
635
636    private String ldapServer;
637    private String ldapPort;
638    private String ldapSearchPath;
639    private String UserID;
640    private String userDN;
641    private String pwd;
642    private String cn;
643    private String mail;
644    private String errorMsg;
645    private String errorStatus;
646    private boolean returnStatus;
647
648    public ldap(String ldapServer, String ldapPort, String UserID, String pwd, String ldapSearchPath) {
649        this.ldapServer = ldapServer;
650        this.ldapPort = ldapPort;
651        this.UserID = UserID;
652        this.pwd = pwd;
653        this.ldapSearchPath = ldapSearchPath;
654        this.returnStatus = processLDAP();
655
656    }
657
658    private boolean processLDAP() {
659        // Password cannot be null
660        if ((pwd.trim().length()) == 0) {
661            //TODO Create exception to null pwd
662            this.errorMsg = "Password Cannot be null";
663            this.errorStatus = "nullPwd";
664            return false;
665        }
666        // Connecting as anonymous to get information about the user
667        Hashtable env = new Hashtable();
668        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
669        env.put(Context.PROVIDER_URL, "ldap://" + this.ldapServer + ":" + this.ldapPort);
670        try {
671            // Connecting
672            DirContext ctx = new InitialDirContext(env);
673            // Searching User
674            SearchControls ctls = new SearchControls();
675            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
676            ctls.setCountLimit(1);
677            ctls.setTimeLimit(10000); // Espera no max 10 segundos
678            String filter = "(uid=" + this.UserID + ")";
679//            NamingEnumeration answer = ctx.search("dc=serpro,dc=gov,dc=br", filter, ctls);
680            NamingEnumeration answer = ctx.search(this.getLdapSearchPath(), filter, ctls);
681            if (answer.hasMore()) {
682                SearchResult sr = (SearchResult) answer.next();
683//                this.userDN = sr.getName() + ",dc=serpro,dc=gov,dc=br";
684                this.userDN = sr.getName() + "," + this.getLdapSearchPath();
685                try {
686                    // Getting User attributes
687                    this.cn = sr.getAttributes().get("cn").get(0).toString();
688                    this.mail = sr.getAttributes().get("mail").get(0).toString();
689                } catch (Exception e) {
690                    e.printStackTrace();
691                    this.errorMsg = e.toString();
692                    this.errorStatus = "notGetAttributes";
693                    return false;
694                }
695            } else {
696                //TODO  Create exception
697                this.errorMsg = "User/Password not Found in LDAP";
698                this.errorStatus = "notFound";
699                return false;
700            }
701
702        /*// This lines was used to DEBUG
703        answer.close();
704        try {
705        answer = ctx.search("dc=serpro,dc=gov,dc=br", filter, ctls);
706        //                formatResults(answer);
707        } catch (Exception e) {
708        e.printStackTrace();
709        return false;
710        }
711        // END - This lines was used to DEBUG*/
712
713        } catch (NamingException e) {
714            e.printStackTrace();
715            this.errorMsg = e.toString();
716            this.errorStatus = "notConnect";
717            return false;
718        }
719
720        // Binding (Verifing Credentials)
721        Hashtable env2 = new Hashtable();
722        env2.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
723        env2.put(Context.PROVIDER_URL, "ldap://" + this.ldapServer + ":" + this.ldapPort);
724        env2.put(Context.SECURITY_AUTHENTICATION, "simple");
725        env2.put(Context.SECURITY_PRINCIPAL, this.userDN); // specify the username
726        env2.put(Context.SECURITY_CREDENTIALS, this.pwd); // specify the password
727
728        try {
729            DirContext ctx = new InitialDirContext(env2);
730            ctx.close();
731        } catch (NamingException e) {
732            e.printStackTrace();
733            this.errorMsg = e.toString();
734            this.errorStatus = "notBind";
735            return false;
736        }
737        return true;
738    }
739
740    // Getters methods
741    public String getldapServer() {
742        return this.ldapServer;
743    }
744
745    public String getldapPort() {
746        return this.ldapPort;
747    }
748
749    public String getUserID() {
750        return this.UserID;
751    }
752
753    public String getuserDN() {
754        return this.userDN;
755    }
756
757    public String getcn() {
758        return this.cn;
759    }
760
761    public String getmail() {
762        return this.mail;
763    }
764
765    public String geterrorMsg() {
766        return this.errorMsg;
767    }
768
769    public String geterrorStatus() {
770        return this.errorStatus;
771    }
772
773    public boolean getreturnStatus() {
774        return this.returnStatus;
775    }
776
777    public String getLdapSearchPath() {
778        return this.ldapSearchPath;
779    }
780}
Note: See TracBrowser for help on using the repository browser.