Subversion Repositories bacoAlunos

Rev

Rev 1585 | Rev 1691 | 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;
1585 jmachado 13
import pt.estgp.estgweb.services.email.SendEmailService;
14
import pt.estgp.estgweb.services.email.SimpleSendEmailInterface;
1 fvelez 15
import pt.estgp.estgweb.services.expceptions.ServiceException;
920 jmachado 16
import pt.estgp.estgweb.services.ftpservices.FtpService;
12 jmachado 17
import pt.estgp.estgweb.utils.ConfigProperties;
1 fvelez 18
import pt.utl.ist.berserk.logic.serviceManager.IService;
19
 
1317 jmachado 20
import java.util.*;
1 fvelez 21
 
9 jmachado 22
 
1 fvelez 23
/*
24
 * @author Goncalo Luiz gedl [AT] rnl [DOT] ist [DOT] utl [DOT] pt
25
 *
26
 *
27
 * Created at 17/Out/2003 , 23:45:24
28
 *
29
 */
30
/**
31
 * @author Jorge Machado
32
 *
33
 *
34
 * Created at 17/Out/2003 , 23:45:24
35
 *
36
 */
37
public class AuthenticateService implements IService
38
{
39
    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);
40
 
12 jmachado 41
    private static final boolean USE_LDAP = ConfigProperties.getBooleanProperty("use.ldap");
42
 
9 jmachado 43
    ILdapManager ldapManager = LdapManagerFactory.getLdapManager();
44
 
61 fvelez 45
    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 46
    {
1687 jmachado 47
        logger.info("Try LOGIN username:" + username);
1 fvelez 48
        if(userSession.getUser() != null)
49
            throw new AuthenticateException(AuthenticateException.ALREADY_AUTHENTICATED);
50
 
694 jmachado 51
        if(username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0)
806 jmachado 52
            throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
12 jmachado 53
        boolean go = false;
54
        if(USE_LDAP)
55
            go = ldapManager.login(username,password);
1 fvelez 56
 
9 jmachado 57
        User u = null;
58
        if(!go)
59
        {
60
            u = DaoFactory.getUserDaoImpl().loadByUsernameAndPassword(username,password);
61
            if(u == null)
62
            {
63
                logger.warn("user:" + username + " fail password");
64
                throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
65
            }
186 fvelez 66
 
9 jmachado 67
            logger.warn("user:" + username + " fail LDAP but pass local authentication");
68
        }
69
        else
70
            try
71
            {
72
                u = DaoFactory.getUserDaoImpl().loadByUsername(username);
73
            }
186 fvelez 74
            catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e){}
9 jmachado 75
 
1 fvelez 76
        if(u == null)
77
        {
892 jmachado 78
            logger.warn("user:" + username + " does not exist");
79
            throw new AuthenticateException(AuthenticateException.DOES_NOT_EXIST);
80
            /*
9 jmachado 81
            u = getUserInfo(username);
163 jmachado 82
            u.setPassword(password);
83
            //put password to be complete for advising
84
            CommonServicesManager.getInstance().adviseNew(u);
394 jmachado 85
//            u.setPassword(null); OLD Line now we save the last sucessfully password in DB
86
            u.setPassword(jomm.utils.BytesUtils.getDigestMD5Hex(password));
186 fvelez 87
            if(u.getRoles().contains("teacher"))
88
            {
806 jmachado 89
 
186 fvelez 90
            }
91
            else if (u.getRoles().contains("student"))
92
            {
806 jmachado 93
 
892 jmachado 94
            }*/
1 fvelez 95
        }
223 jmachado 96
        else
97
        {
1687 jmachado 98
            logger.info("username:" + username + " login:OK");
394 jmachado 99
//            String passwordAux = u.getPassword();
223 jmachado 100
            u.setPassword(password);
921 jmachado 101
 
223 jmachado 102
            CommonServicesManager.getInstance().adviseUpdate(u);
394 jmachado 103
//            u.setPassword(passwordAux);
104
            u.setPassword(jomm.utils.BytesUtils.getDigestMD5Hex(password));
223 jmachado 105
        }
806 jmachado 106
 
107
        //CHECK USER BLOCK's
108
        if(!u.isAdmin() && !u.isSuperuser())
109
        {
110
            if(u.isAutoBlockMode() && u.isAutoBlock()
111
                    ||
112
                    !u.isAutoBlockMode() && u.isManualBlock())
113
            {
114
                logger.warn("user:" + username + " blocked");
115
                throw  new AuthenticateException(AuthenticateException.BLOCKED);
116
            }
117
        }
118
 
1 fvelez 119
        logger.warn("user:" + username + " authenticated");
978 jmachado 120
 
979 jmachado 121
        //((UserSessionImpl)userSession).reset();
122
        //((UserSessionImpl)userSession).clearObjectsWithOpenTransaction();
975 jmachado 123
 
979 jmachado 124
        //DaoFactory.getUserSessionDaoImpl().flush();
125
 
921 jmachado 126
        //PASSWORD PARA SERVICOS FTP CLIENT
978 jmachado 127
                ((UserSessionImpl) userSession).put(FtpService.FTP_PASSWORD, DesUtils.getInstance().encrypt(password));
921 jmachado 128
        //put password to be complete for advising
1 fvelez 129
        userSession.setName(u.getName());
130
        userSession.setUsername(u.getUsername());
131
        userSession.setUser(u);
1085 jmachado 132
        if(u.getRoles() == null || u.getRoles().trim().length() == 0)
133
            u.setRoles(Globals.ROLE_INVITED);
162 jmachado 134
 
1554 jmachado 135
        /**CHECK BASIC SYSTEM ROLES**/
136
        if(u instanceof Teacher && !u.hasRole(Globals.TEACHER_ROLE))
137
            u.addRole(Globals.TEACHER_ROLE);
138
        if(u instanceof Student && !u.hasRole(Globals.STUDENT_ROLE))
139
            u.addRole(Globals.STUDENT_ROLE);
140
 
1 fvelez 141
        DaoFactory.getUserSessionDaoImpl().reattach(userSession);
1687 jmachado 142
        logger.info("LOGIN SERVICE FINISH for username:" + username);
61 fvelez 143
        return userSession;
1 fvelez 144
    }
9 jmachado 145
 
146
    private User getUserInfo(1.5.0/docs/api/java/lang/String.html">String username)
147
    {
148
        1.5.0/docs/api/java/util/HashMap.html">HashMap map = ldapManager.getUserInfo(username);
149
        UserImpl u = DomainObjectFactory.createUserImpl();
186 fvelez 150
        u.setUsername(username);
56 fvelez 151
        u.setName(getName(map));
152
        u.setRoles(getRoles(map));
9 jmachado 153
        u.setNewUser(true);
163 jmachado 154
        /*todo call commonServices Manager advise New put Password First*/
9 jmachado 155
        DaoFactory.getUserDaoImpl().save(u);
156
        return u;
157
    }
56 fvelez 158
 
159
    private 1.5.0/docs/api/java/lang/String.html">String getName(1.5.0/docs/api/java/util/HashMap.html">HashMap text)
160
    {
186 fvelez 161
        1.5.0/docs/api/java/util/Set.html">Set s = text.entrySet();
162
        1.5.0/docs/api/java/util/Iterator.html">Iterator iter = s.iterator();
163
        int iterCount=0;
164
        1.5.0/docs/api/java/lang/String.html">String name=null;
56 fvelez 165
 
186 fvelez 166
        while(iter.hasNext())
56 fvelez 167
        {
168
            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();
169
            if(iterCount==3)
170
            {
186 fvelez 171
                name=e.getValue().toString();
56 fvelez 172
            }
173
            iterCount++;
174
        }
175
        return name;
176
    }
177
 
178
    public 1.5.0/docs/api/java/lang/String.html">String getRoles(1.5.0/docs/api/java/util/HashMap.html">HashMap text)
179
    {
180
        1.5.0/docs/api/java/util/Set.html">Set s = text.entrySet();
181
        1.5.0/docs/api/java/util/Iterator.html">Iterator iter = s.iterator();
182
        int iterCount=0;
183
        1.5.0/docs/api/java/lang/String.html">String roles=null;
184
 
185
        while(iter.hasNext())
186
        {
187
            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();
188
            if(iterCount==0)
189
            {
190
                1.5.0/docs/api/java/lang/String.html">String[] splitText=e.getValue().toString().split(",");
191
                if(splitText[1].contains("CN"))
192
                {
193
                    roles="student";
194
                }
195
                else if(splitText[1].contains("OU"))
196
                {
197
                    roles="teacher";
198
                }
199
            }
200
            iterCount++;
201
        }
202
        return roles;
203
    }
1312 jmachado 204
 
205
 
206
    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
207
    {
208
        if(userSession.getUser() != null)
209
        {
1314 jmachado 210
            new LogoutService().run(userSession);
1312 jmachado 211
        }
212
 
213
        if(username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0)
214
            throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
215
 
216
        User u = null;
217
 
218
        boolean go = false;
219
        try{
220
            try{
221
            u = DaoFactory.getUserDaoImpl().loadBySigesCode(new 1.5.0/docs/api/java/lang/Integer.html">Integer(username));
222
            }catch(1.5.0/docs/api/java/lang/Exception.html">Exception e){}
223
            if(u == null)
224
                u = DaoFactory.getUserDaoImpl().loadByUsername(username);
225
 
226
            if(u == null)
227
                throw new AuthenticateException(AuthenticateException.DOES_NOT_EXIST);
228
            go = u.getPasswordSiges() != null && u.getPasswordSiges().equals(jomm.utils.BytesUtils.getDigestMD5Hex(password));
229
            if(go)
230
            {
231
                logger.info("siges:" + username + " login:PASSSIGES");
232
            }
233
            else
234
            {
235
                go = u.getPassword() != null && u.getPassword().equals(jomm.utils.BytesUtils.getDigestMD5Hex(password));
236
                if(go)
237
                {
238
                    logger.info("siges:" + username + " login:PASSBACO");
239
                }
240
                else
241
                {
242
                    go = u.getBi() != null && u.getBi().equals(password);
243
                    if(go)
244
                    {
245
                        logger.info("siges:" + username + " login:BI");
246
                    }
247
                }
248
            }
249
        }
250
        catch(1.5.0/docs/api/java/lang/Throwable.html">Throwable e)
251
        {
252
 
253
        }
254
        if(!go)
255
        {
256
            logger.warn("siges:" + username + " fail password");
257
            throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
258
        }
259
 
260
 
261
 
262
 
263
        //CHECK USER BLOCK's
264
        if(!u.isAdmin() && !u.isSuperuser())
265
        {
266
            if(u.isAutoBlockMode() && u.isAutoBlock()
267
                    ||
268
                    !u.isAutoBlockMode() && u.isManualBlock())
269
            {
270
                logger.warn("siges:" + username + " blocked");
271
                throw new AuthenticateException(AuthenticateException.BLOCKED);
272
            }
273
        }
274
 
275
        logger.warn("siges:" + username + " authenticated");
276
 
277
        userSession.setName(u.getName());
278
        userSession.setUsername(u.getUsername());
279
        userSession.setUser(u);
280
        if(u.getRoles() == null || u.getRoles().trim().length() == 0)
281
            u.setRoles(Globals.ROLE_INVITED);
282
 
283
        DaoFactory.getUserSessionDaoImpl().reattach(userSession);
284
        return userSession;
285
    }
1317 jmachado 286
 
1585 jmachado 287
 
288
    public UserSession changePassword(1.5.0/docs/api/java/lang/String.html">String password, UserSession userSession) throws ServiceException
289
    {
290
        userSession.getUser().setPassword(password);
291
        CommonServicesManager.getInstance().adviseUpdate(userSession.getUser());
292
        userSession.getUser().setPassword(jomm.utils.BytesUtils.getDigestMD5Hex(password));
293
        return userSession;
294
    }
295
 
296
    public User requestChangePassword(1.5.0/docs/api/java/lang/String.html">String identifier) throws ServiceException
297
    {
298
 
299
        List<User> users = DaoFactory.getUserDaoImpl().loadBySigesCodeUsernameEmailsBiSiges(identifier);
300
        if(users.size() == 0)
301
            return null;
302
        else if(users.size() > 1)
303
        {
304
            1.5.0/docs/api/java/lang/String.html">String subject = "DANGER two or more users sharing identifier property " + identifier;
305
            logger.warn(subject);
306
            1.5.0/docs/api/java/lang/String.html">String msg = "";
307
            for(User u: users)
308
            {
309
                logger.warn(u.getId() + " " + u.getUsername() + " " + u.getEmail());
310
                msg += " ( " + u.getId() + " " + u.getUsername() + " " + u.getEmail() + " )";
311
            }
312
            new SendEmailService().sendNotificationAdmin(msg,"Ao tentar recuperar password idenficamos mais de um caso com o mesmo identificador:" + msg);
313
            return null;
314
        }
315
        else
316
        {
317
            User u = users.get(0);
318
            logger.info("User " + u.getId() + " " + u.getName() + " identificado vamos criar um certificado e enviar um email para reposição de password");
319
 
320
            1.5.0/docs/api/java/lang/String.html">String text = "Caro " + u.getName() + " vimos por este meio informá-lo que já pode redifinir a sua password no seguinte endereço web. " +
321
                    "Este endereço expira em " +
322
                    +Globals.CERTIFICATES_EXPIRTATION_IN_DAYS + " dias. Se por algum motivo for alheio a este pedido por favor ignore este email. " +
323
                    "A sua password no PAE será mantida.";
324
 
325
            SimpleSendEmailInterface.createCertificatedEmailJobAndSendNow(u,
326
                    "Sistema de Recuperação de Passwords PAE-IPP",
327
                    "Pedido de Recuperação de Password",
328
                    text,
329
                    Globals.SITE_URL + "/user/ChangePassword.do",
330
                    "Message Email (request change password from user with id " + u.getId()
331
            );
332
            return u;
333
        }
334
 
335
    }
336
 
337
 
1317 jmachado 338
    public UserSession loginCertificate(1.5.0/docs/api/java/lang/String.html">String certificate, UserSession userSession) throws ServiceException
339
    {
340
        if(userSession.getUser() != null)
341
        {
342
            new LogoutService().run(userSession);
343
        }
344
 
345
        if(certificate == null || certificate.trim().length() == 0)
346
            throw new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
347
 
348
        User u = null;
349
 
350
        List<User> users = DaoFactory.getUserDaoImpl().loadByCertificate(certificate);
351
        if(users == null || users.size() > 1 || users.size()== 0)
352
        {
353
            if(users.size() > 1)
354
                logger.error("Erro dois users com o mesmo certificado");
355
            throw  new AuthenticateException(AuthenticateException.FAIL_AUTHENTICATION);
356
        }
357
        u = users.get(0);
358
        logger.info("certificate:" + u.getUsername() + " login:certificate:" + certificate);
359
        //CHECK USER BLOCK's
360
        if(!u.isAdmin() && !u.isSuperuser())
361
        {
362
            if(u.isAutoBlockMode() && u.isAutoBlock()
363
                    ||
364
                    !u.isAutoBlockMode() && u.isManualBlock())
365
            {
366
                logger.warn("certificate:" + u.getUsername() + " blocked");
367
                throw new AuthenticateException(AuthenticateException.BLOCKED);
368
            }
369
        }
370
 
371
        logger.warn("certificate:" + u.getUsername() + " authenticated");
372
 
373
        userSession.setName(u.getName());
374
        userSession.setUsername(u.getUsername());
375
        userSession.setUser(u);
376
        if(u.getRoles() == null || u.getRoles().trim().length() == 0)
377
            u.setRoles(Globals.ROLE_INVITED);
378
 
379
        DaoFactory.getUserSessionDaoImpl().reattach(userSession);
380
        return userSession;
381
    }
382
 
383
    /**
384
     * Create a new Certificate for usage in URL auto login
385
     *
386
     * @param userId
387
     * @return the certificate string to use in URL
388
     */
1339 jmachado 389
    public 1.5.0/docs/api/java/lang/String.html">String createCertificateForId(long userId, UserSession usersession)
1317 jmachado 390
    {
391
        User u = DaoFactory.getUserDaoImpl().load(userId);
1339 jmachado 392
        return createCertificate(u, usersession);
1317 jmachado 393
    }
1429 jmachado 394
    public 1.5.0/docs/api/java/lang/String.html">String createCertificateForId(long userId)
395
    {
396
        User u = DaoFactory.getUserDaoImpl().load(userId);
397
        return createCertificate(u);
398
    }
399
    public 1.5.0/docs/api/java/lang/String.html">String createCertificate(User user)
400
    {
401
        return createCertificate(user,null);
402
    }
1317 jmachado 403
    /**
404
     * Create a new Certificate for usage in URL auto login
405
     *
406
     * @param user to crate certificate
407
     * @return the certificate string
408
     */
1339 jmachado 409
    public 1.5.0/docs/api/java/lang/String.html">String createCertificate(User user, UserSession usersession)
1317 jmachado 410
    {
411
        1.5.0/docs/api/java/lang/String.html">String certificate = user.getId()
412
                + "-" + 1.5.0/docs/api/java/lang/System.html">System.currentTimeMillis()
413
                + "-" + 1.5.0/docs/api/java/lang/Thread.html">Thread.currentThread().hashCode()
414
                + "-" +  1.5.0/docs/api/java/lang/Runtime.html">Runtime.getRuntime().freeMemory();
415
        1.5.0/docs/api/java/lang/String.html">String md5 = BytesUtils.getMD5(certificate);
416
        user.setAuthenticationCertificate(md5);
417
        //3600 seconds = 1 hour = 3600.000 milis * 24 = 1 day * 15 = 15 days
418
        long daysInMilis =  3600 * 1000 * 24 * Globals.CERTIFICATES_EXPIRTATION_IN_DAYS;
419
        user.setAuthenticationCertificateExpire(new 5+0%2Fdocs%2Fapi+Date">Date(1.5.0/docs/api/java/lang/System.html">System.currentTimeMillis()+daysInMilis));
420
        return md5;
421
    }
422
 
423
    public static void main(1.5.0/docs/api/java/lang/String.html">String [] args)
424
    {
425
        AbstractDao.getCurrentSession().beginTransaction();
1339 jmachado 426
        1.5.0/docs/api/java/lang/String.html">String certificate = new AuthenticateService().createCertificateForId(1691,null);
1317 jmachado 427
        AbstractDao.getCurrentSession().getTransaction().commit();
428
 
429
    }
1 fvelez 430
}
22 fvelez 431
 
432