Subversion Repositories bacoAlunos

Rev

Rev 1317 | Rev 1554 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 fvelez 1
package pt.estgp.estgweb.services.authenticate;
2
 
1317 jmachado 3
import jomm.dao.impl.AbstractDao;
4
import jomm.utils.BytesUtils;
920 jmachado 5
import jomm.utils.DesUtils;
6
import openldap.ILdapManager;
7
import openldap.LdapManagerFactory;
1 fvelez 8
import org.apache.log4j.Logger;
1085 jmachado 9
import pt.estgp.estgweb.Globals;
162 jmachado 10
import pt.estgp.estgweb.domain.*;
1 fvelez 11
import pt.estgp.estgweb.domain.dao.DaoFactory;
920 jmachado 12
import pt.estgp.estgweb.services.common.CommonServicesManager;
1 fvelez 13
import pt.estgp.estgweb.services.expceptions.ServiceException;
920 jmachado 14
import pt.estgp.estgweb.services.ftpservices.FtpService;
12 jmachado 15
import pt.estgp.estgweb.utils.ConfigProperties;
1 fvelez 16
import pt.utl.ist.berserk.logic.serviceManager.IService;
17
 
1317 jmachado 18
import java.util.*;
1 fvelez 19
 
9 jmachado 20
 
1 fvelez 21
/*
22
 * @author Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt
23
 *
24
 *
25
 * Created at 17/Out/2003 , 23:45:24
26
 *
27
 */
28
/**
29
 * @author Jorge Machado
30
 *
31
 *
32
 * Created at 17/Out/2003 , 23:45:24
33
 *
34
 */
35
public class AuthenticateService implements IService
36
{
37
    private static final 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger = 1.5.0/docs/api/java/util/logging/Logger.html">Logger.getLogger(AuthenticateService.class);
38
 
12 jmachado 39
    private static final boolean USE_LDAP = ConfigProperties.getBooleanProperty("use.ldap");
40
 
9 jmachado 41
    ILdapManager ldapManager = LdapManagerFactory.getLdapManager();
42
 
61 fvelez 43
    public UserSession run(1.5.0/docs/api/java/lang/String.html">String username, 1.5.0/docs/api/java/lang/String.html">String password, UserSession userSession) throws ServiceException
1 fvelez 44
    {
45
        if(userSession.getUser() != null)
46
            throw new AuthenticateException(AuthenticateException.ALREADY_AUTHENTICATED);
47
 
694 jmachado 48
        if(username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0)
806 jmachado 49
            throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
12 jmachado 50
        boolean go = false;
51
        if(USE_LDAP)
52
            go = ldapManager.login(username,password);
1 fvelez 53
 
9 jmachado 54
        User u = null;
55
        if(!go)
56
        {
57
            u = DaoFactory.getUserDaoImpl().loadByUsernameAndPassword(username,password);
58
            if(u == null)
59
            {
60
                logger.warn("user:" + username + " fail password");
61
                throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
62
            }
186 fvelez 63
 
9 jmachado 64
            logger.warn("user:" + username + " fail LDAP but pass local authentication");
65
        }
66
        else
67
            try
68
            {
69
                u = DaoFactory.getUserDaoImpl().loadByUsername(username);
70
            }
186 fvelez 71
            catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e){}
9 jmachado 72
 
1 fvelez 73
        if(u == null)
74
        {
892 jmachado 75
            logger.warn("user:" + username + " does not exist");
76
            throw new AuthenticateException(AuthenticateException.DOES_NOT_EXIST);
77
            /*
9 jmachado 78
            u = getUserInfo(username);
163 jmachado 79
            u.setPassword(password);
80
            //put password to be complete for advising
81
            CommonServicesManager.getInstance().adviseNew(u);
394 jmachado 82
//            u.setPassword(null); OLD Line now we save the last sucessfully password in DB
83
            u.setPassword(jomm.utils.BytesUtils.getDigestMD5Hex(password));
186 fvelez 84
            if(u.getRoles().contains("teacher"))
85
            {
806 jmachado 86
 
186 fvelez 87
            }
88
            else if (u.getRoles().contains("student"))
89
            {
806 jmachado 90
 
892 jmachado 91
            }*/
1 fvelez 92
        }
223 jmachado 93
        else
94
        {
394 jmachado 95
//            String passwordAux = u.getPassword();
223 jmachado 96
            u.setPassword(password);
921 jmachado 97
 
223 jmachado 98
            CommonServicesManager.getInstance().adviseUpdate(u);
394 jmachado 99
//            u.setPassword(passwordAux);
100
            u.setPassword(jomm.utils.BytesUtils.getDigestMD5Hex(password));
223 jmachado 101
        }
806 jmachado 102
 
103
        //CHECK USER BLOCK's
104
        if(!u.isAdmin() && !u.isSuperuser())
105
        {
106
            if(u.isAutoBlockMode() && u.isAutoBlock()
107
                    ||
108
                    !u.isAutoBlockMode() && u.isManualBlock())
109
            {
110
                logger.warn("user:" + username + " blocked");
111
                throw  new AuthenticateException(AuthenticateException.BLOCKED);
112
            }
113
        }
114
 
1 fvelez 115
        logger.warn("user:" + username + " authenticated");
978 jmachado 116
 
979 jmachado 117
        //((UserSessionImpl)userSession).reset();
118
        //((UserSessionImpl)userSession).clearObjectsWithOpenTransaction();
975 jmachado 119
 
979 jmachado 120
        //DaoFactory.getUserSessionDaoImpl().flush();
121
 
921 jmachado 122
        //PASSWORD PARA SERVICOS FTP CLIENT
978 jmachado 123
                ((UserSessionImpl) userSession).put(FtpService.FTP_PASSWORD, DesUtils.getInstance().encrypt(password));
921 jmachado 124
        //put password to be complete for advising
1 fvelez 125
        userSession.setName(u.getName());
126
        userSession.setUsername(u.getUsername());
127
        userSession.setUser(u);
1085 jmachado 128
        if(u.getRoles() == null || u.getRoles().trim().length() == 0)
129
            u.setRoles(Globals.ROLE_INVITED);
162 jmachado 130
 
1 fvelez 131
        DaoFactory.getUserSessionDaoImpl().reattach(userSession);
61 fvelez 132
        return userSession;
1 fvelez 133
    }
9 jmachado 134
 
135
    private User getUserInfo(1.5.0/docs/api/java/lang/String.html">String username)
136
    {
137
        1.5.0/docs/api/java/util/HashMap.html">HashMap map = ldapManager.getUserInfo(username);
138
        UserImpl u = DomainObjectFactory.createUserImpl();
186 fvelez 139
        u.setUsername(username);
56 fvelez 140
        u.setName(getName(map));
141
        u.setRoles(getRoles(map));
9 jmachado 142
        u.setNewUser(true);
163 jmachado 143
        /*todo call commonServices Manager advise New put Password First*/
9 jmachado 144
        DaoFactory.getUserDaoImpl().save(u);
145
        return u;
146
    }
56 fvelez 147
 
148
    private 1.5.0/docs/api/java/lang/String.html">String getName(1.5.0/docs/api/java/util/HashMap.html">HashMap text)
149
    {
186 fvelez 150
        1.5.0/docs/api/java/util/Set.html">Set s = text.entrySet();
151
        1.5.0/docs/api/java/util/Iterator.html">Iterator iter = s.iterator();
152
        int iterCount=0;
153
        1.5.0/docs/api/java/lang/String.html">String name=null;
56 fvelez 154
 
186 fvelez 155
        while(iter.hasNext())
56 fvelez 156
        {
157
            1.5.0/docs/api/java/util/Map.Entry.html">Map.Entry e = (1.5.0/docs/api/java/util/Map.Entry.html">Map.Entry) iter.next();
158
            if(iterCount==3)
159
            {
186 fvelez 160
                name=e.getValue().toString();
56 fvelez 161
            }
162
            iterCount++;
163
        }
164
        return name;
165
    }
166
 
167
    public 1.5.0/docs/api/java/lang/String.html">String getRoles(1.5.0/docs/api/java/util/HashMap.html">HashMap text)
168
    {
169
        1.5.0/docs/api/java/util/Set.html">Set s = text.entrySet();
170
        1.5.0/docs/api/java/util/Iterator.html">Iterator iter = s.iterator();
171
        int iterCount=0;
172
        1.5.0/docs/api/java/lang/String.html">String roles=null;
173
 
174
        while(iter.hasNext())
175
        {
176
            1.5.0/docs/api/java/util/Map.Entry.html">Map.Entry e = (1.5.0/docs/api/java/util/Map.Entry.html">Map.Entry) iter.next();
177
            if(iterCount==0)
178
            {
179
                1.5.0/docs/api/java/lang/String.html">String[] splitText=e.getValue().toString().split(",");
180
                if(splitText[1].contains("CN"))
181
                {
182
                    roles="student";
183
                }
184
                else if(splitText[1].contains("OU"))
185
                {
186
                    roles="teacher";
187
                }
188
            }
189
            iterCount++;
190
        }
191
        return roles;
192
    }
1312 jmachado 193
 
194
 
195
    public UserSession loginPae(1.5.0/docs/api/java/lang/String.html">String username, 1.5.0/docs/api/java/lang/String.html">String password, UserSession userSession) throws ServiceException
196
    {
197
        if(userSession.getUser() != null)
198
        {
1314 jmachado 199
            new LogoutService().run(userSession);
1312 jmachado 200
        }
201
 
202
        if(username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0)
203
            throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
204
 
205
        User u = null;
206
 
207
        boolean go = false;
208
        try{
209
            try{
210
            u = DaoFactory.getUserDaoImpl().loadBySigesCode(new 1.5.0/docs/api/java/lang/Integer.html">Integer(username));
211
            }catch(1.5.0/docs/api/java/lang/Exception.html">Exception e){}
212
            if(u == null)
213
                u = DaoFactory.getUserDaoImpl().loadByUsername(username);
214
 
215
            if(u == null)
216
                throw new AuthenticateException(AuthenticateException.DOES_NOT_EXIST);
217
            go = u.getPasswordSiges() != null && u.getPasswordSiges().equals(jomm.utils.BytesUtils.getDigestMD5Hex(password));
218
            if(go)
219
            {
220
                logger.info("siges:" + username + " login:PASSSIGES");
221
            }
222
            else
223
            {
224
                go = u.getPassword() != null && u.getPassword().equals(jomm.utils.BytesUtils.getDigestMD5Hex(password));
225
                if(go)
226
                {
227
                    logger.info("siges:" + username + " login:PASSBACO");
228
                }
229
                else
230
                {
231
                    go = u.getBi() != null && u.getBi().equals(password);
232
                    if(go)
233
                    {
234
                        logger.info("siges:" + username + " login:BI");
235
                    }
236
                }
237
            }
238
        }
239
        catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
240
        {
241
 
242
        }
243
        if(!go)
244
        {
245
            logger.warn("siges:" + username + " fail password");
246
            throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
247
        }
248
 
249
 
250
 
251
 
252
        //CHECK USER BLOCK's
253
        if(!u.isAdmin() && !u.isSuperuser())
254
        {
255
            if(u.isAutoBlockMode() && u.isAutoBlock()
256
                    ||
257
                    !u.isAutoBlockMode() && u.isManualBlock())
258
            {
259
                logger.warn("siges:" + username + " blocked");
260
                throw new AuthenticateException(AuthenticateException.BLOCKED);
261
            }
262
        }
263
 
264
        logger.warn("siges:" + username + " authenticated");
265
 
266
        userSession.setName(u.getName());
267
        userSession.setUsername(u.getUsername());
268
        userSession.setUser(u);
269
        if(u.getRoles() == null || u.getRoles().trim().length() == 0)
270
            u.setRoles(Globals.ROLE_INVITED);
271
 
272
        DaoFactory.getUserSessionDaoImpl().reattach(userSession);
273
        return userSession;
274
    }
1317 jmachado 275
 
276
    public UserSession loginCertificate(1.5.0/docs/api/java/lang/String.html">String certificate, UserSession userSession) throws ServiceException
277
    {
278
        if(userSession.getUser() != null)
279
        {
280
            new LogoutService().run(userSession);
281
        }
282
 
283
        if(certificate == null || certificate.trim().length() == 0)
284
            throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
285
 
286
        User u = null;
287
 
288
        List<User> users = DaoFactory.getUserDaoImpl().loadByCertificate(certificate);
289
        if(users == null || users.size() > 1 || users.size()== 0)
290
        {
291
            if(users.size() > 1)
292
                logger.error("Erro dois users com o mesmo certificado");
293
            throw  new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
294
        }
295
        u = users.get(0);
296
        logger.info("certificate:" + u.getUsername() + " login:certificate:" + certificate);
297
        //CHECK USER BLOCK's
298
        if(!u.isAdmin() && !u.isSuperuser())
299
        {
300
            if(u.isAutoBlockMode() && u.isAutoBlock()
301
                    ||
302
                    !u.isAutoBlockMode() && u.isManualBlock())
303
            {
304
                logger.warn("certificate:" + u.getUsername() + " blocked");
305
                throw new AuthenticateException(AuthenticateException.BLOCKED);
306
            }
307
        }
308
 
309
        logger.warn("certificate:" + u.getUsername() + " authenticated");
310
 
311
        userSession.setName(u.getName());
312
        userSession.setUsername(u.getUsername());
313
        userSession.setUser(u);
314
        if(u.getRoles() == null || u.getRoles().trim().length() == 0)
315
            u.setRoles(Globals.ROLE_INVITED);
316
 
317
        DaoFactory.getUserSessionDaoImpl().reattach(userSession);
318
        return userSession;
319
    }
320
 
321
    /**
322
     * Create a new Certificate for usage in URL auto login
323
     *
324
     * @param userId
325
     * @return the certificate string to use in URL
326
     */
1339 jmachado 327
    public 1.5.0/docs/api/java/lang/String.html">String createCertificateForId(long userId, UserSession usersession)
1317 jmachado 328
    {
329
        User u = DaoFactory.getUserDaoImpl().load(userId);
1339 jmachado 330
        return createCertificate(u, usersession);
1317 jmachado 331
    }
332
    /**
333
     * Create a new Certificate for usage in URL auto login
334
     *
335
     * @param user to crate certificate
336
     * @return the certificate string
337
     */
1339 jmachado 338
    public 1.5.0/docs/api/java/lang/String.html">String createCertificate(User user, UserSession usersession)
1317 jmachado 339
    {
340
        1.5.0/docs/api/java/lang/String.html">String certificate = user.getId()
341
                + "-" + 1.5.0/docs/api/java/lang/System.html">System.currentTimeMillis()
342
                + "-" + 1.5.0/docs/api/java/lang/Thread.html">Thread.currentThread().hashCode()
343
                + "-" +  1.5.0/docs/api/java/lang/Runtime.html">Runtime.getRuntime().freeMemory();
344
        1.5.0/docs/api/java/lang/String.html">String md5 = BytesUtils.getMD5(certificate);
345
        user.setAuthenticationCertificate(md5);
346
        //3600 seconds = 1 hour = 3600.000 milis * 24 = 1 day * 15 = 15 days
347
        long daysInMilis =  3600 * 1000 * 24 * Globals.CERTIFICATES_EXPIRTATION_IN_DAYS;
348
        user.setAuthenticationCertificateExpire(new 5+0%2Fdocs%2Fapi+Date">Date(1.5.0/docs/api/java/lang/System.html">System.currentTimeMillis()+daysInMilis));
349
        return md5;
350
    }
351
 
352
    public static void main(1.5.0/docs/api/java/lang/String.html">String [] args)
353
    {
354
        AbstractDao.getCurrentSession().beginTransaction();
1339 jmachado 355
        1.5.0/docs/api/java/lang/String.html">String certificate = new AuthenticateService().createCertificateForId(1691,null);
1317 jmachado 356
        AbstractDao.getCurrentSession().getTransaction().commit();
357
 
358
    }
1 fvelez 359
}
22 fvelez 360
 
361