Alejandro Acuña
2024-07-30 65a64a81d30f00f1fffd5da6866850e1308e1135
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
package art.servers.transactionsserver.model.access;
 
import art.library.interop.InteropParameter;
import art.library.interop.InteropParameters;
import art.library.interop.InteropResponse;
import art.library.interop.serialization.Serialization;
import art.library.interop.serialization.SerializationException;
import art.library.model.devices.DeviceAction;
import art.library.model.devices.DeviceActionResult;
import art.library.model.devices.DevicePersistenceAction;
import art.library.model.devices.user.User;
import art.library.model.devices.user.UserAlarmConfiguration;
import art.library.model.devices.user.UserIdentification;
import art.library.model.devices.user.UserInformation;
import art.library.model.devices.user.UserPermission;
import art.library.model.devices.user.UserPrivileges;
import art.library.model.devices.user.UserProperties;
import art.library.model.transactions.sessions.Session;
import art.library.model.transactions.sessions.SessionConfiguration;
import art.library.model.transactions.sessions.SessionIdentification;
import art.library.model.transactions.sessions.SessionWebProperties;
import art.library.utils.licence.Licence;
import art.servers.transactionsserver.Shared;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class ModelSessions
{
    
    public ModelSessions() throws Exception
    {   
    }
    
    //<editor-fold defaultstate="collapsed" desc="Sessions">
     /**
     * @param parameters <code>InteropParameters</code>
     * <p>name: "language" class: <code>String</code>
     * <p>name: "identification" class: <code>SessionIdentification</code>
     * <p>name: "lUserIdentification" class: <code>UserIdentification[]</code>
     * @return <code>InteropResponse</code> 
     * <code>Session</code>
     * @throws SerializationException 
     */
    public InteropResponse startSession(InteropParameters parameters) throws SerializationException
    {
        String language = (String)parameters.getParameterValue("language");
       
        try
        {
            createRootUserIfExistsInParameters(parameters);
            InteropResponse response = createSessionAndAddUsersIntoIt(parameters);
            return response;
        } 
        catch (SerializationException exception)
        {
            exception.printStackTrace();
            String errorMessage = exception.getMessage();
            
            if ((errorMessage.equals("invalid user")) || (errorMessage.equals("invalid password")))
            {
                throw new SerializationException(Shared.getMessage(language, "The provided user or password are not valid"));
            } 
            else
            {
                throw new SerializationException(Shared.getMessage(language, exception.getMessage()));
            }
        } 
        catch (Exception exception)
        {
            exception.printStackTrace();
            throw new SerializationException(Shared.getMessage(language, exception.getMessage()));
        }
    }
 
    private void createRootUserIfExistsInParameters(InteropParameters parameters) throws Exception
    {
        UserIdentification[] luserIdentification = (UserIdentification[]) parameters.getBodyContentValue(UserIdentification[].class);
        //IF EXIST ROOT IDENTIFICATION UPDATE ROOT USER
        int indexRootIdentification = Arrays.binarySearch(luserIdentification, new UserIdentification("Administrator", Licence.encrypt("root"), ""),
                (UserIdentification o1, UserIdentification o2) -> (o1.username.compareTo(o2.username)));
        if (indexRootIdentification >= 0)
        {
            Shared.getModel().initializeRootUser();
        }
    }
 
    private InteropResponse createSessionAndAddUsersIntoIt(InteropParameters parameters) throws SerializationException
    {
        Session session = new Session();    
        session.identification =(parameters.hasParameter("identification") == true) ? (SessionIdentification) parameters.getParameterValue("identification"): new SessionIdentification();
        parameters.addParameter("session", session);
        InteropResponse response = addUsersSession(parameters);
        return response;
    }
    
     /**
     * @param parameters <code>InteropParameters</code>
     * <p>name: "language" class: <code>String</code>
     * <p>name: "session" class: <code>Session</code>
     * <p>name: "lUserIdentification" class: <code>UserIdentification[]</code>
     * @return <code>InteropResponse</code> 
     * <code>Session</code>
     * @throws SerializationException 
     */
    @SuppressWarnings("unchecked")
    public InteropResponse addUsersSession(InteropParameters parameters) throws SerializationException
    {
        String language = (String)parameters.getParameterValue("language");
 
        try
        {
            String computerAction = parameters.getParameterValue("computer");
            Session session = (Session) parameters.getParameterValue("session");
            UserIdentification[] luserIdentification = (UserIdentification[]) parameters.getBodyContentValue(UserIdentification[].class);
            String usernameAction = luserIdentification[0].username;
            boolean secureUser = (parameters.hasParameter("secureUser")) ? Boolean.valueOf((String) parameters.getParameterValue("secureUser")) : true;
 
            session = checkSessionAndAddAllowedUsers(session, luserIdentification, secureUser, usernameAction, computerAction);
            updateSessionConfiguration(session);
            session.token = Long.toHexString(Double.doubleToLongBits(Math.random())) + Long.toHexString(Double.doubleToLongBits(Math.random()));
            if (!secureUser)
            {
                for (UserIdentification userIdentification : session.identification.luser)
                {
                    userIdentification.username = Licence.decrypt(userIdentification.username);
                }
            }
            return new InteropResponse(session);
        } catch (SerializationException e)
        {
            e.printStackTrace();
            throw new SerializationException(e.getMessage());
        } catch (Exception e)
        {
            e.printStackTrace();
            throw new SerializationException(e.getMessage());
        }
    }
 
    /**
     * @param parameters <code>InteropParameters</code>
     * <p>name: "language" class: <code>String</code>
     * <p>name: "session" class: <code>Session</code>
     * <p>name: "lusername" class: <code>String[]</code>
     * @return <code>InteropResponse</code> 
     * <code>Session</code>
     * @throws SerializationException 
     */
    @SuppressWarnings("unchecked")
    public InteropResponse removeUsersSession(InteropParameters parameters) throws SerializationException
    {
        String language = (String)parameters.getParameterValue("language");
        try
        {
            String usernameAction = parameters.getParameterValue("username");
            String computerAction = parameters.getParameterValue("computer");
            
            Session session = (Session) parameters.getParameterValue("session");
            String bodyContent = (String) parameters.getParameterValue("body-content");
            String[] lusername = (String[]) Serialization.deserialize(String[].class, bodyContent);
 
            //REMOVE USERS
            for (String username : lusername)
            {
                //CREATE AND SAVE ACCTION
                User userAction = new User();
                userAction.information = new UserInformation();
                try
                {
                    userAction.information.setIdentifier(Licence.decrypt(username));
                } catch (Exception e)
                {
                    userAction.information.setIdentifier(username);
                }
 
                Session sessionAction = new Session();
                sessionAction.identification = session.identification;
                sessionAction.token = session.token;
                sessionAction.role = session.role; 
 
                DeviceAction action = new DeviceAction(userAction, parameters);
                DeviceActionResult actionResult = new DeviceActionResult(DeviceActionResult.RESULT_CORRECT, Shared.getMessage("log out"));
                action.setResult(actionResult);
                Shared.model.addAction(action);
                
                session.removeUserIdentification(username);
            }
 
            //UPDATE SESSION PERMISSIONS
            updateSessionConfiguration(session);
            
            return new InteropResponse(session);
        } catch (SerializationException e)
        {
            throw new SerializationException(e.getMessage());
        }
    }
 
    /**
     * @param parameters <code>InteropParameters</code>
     * <p>name: "language" class: <code>String</code>
     * <p>name: "identification" class: <code>SessionIdentification</code>
     * @return <code>InteropResponse</code> 
     * <code>Boolean</code>
     * @throws SerializationException 
     */
    public InteropResponse endSession(InteropParameters parameters) throws SerializationException
    {
        String language = (String)parameters.getParameterValue("language");
        SessionIdentification identification = (SessionIdentification)parameters.getParameterValue("identification");
        String[] lusername;
        //FOR ARTIC WEB
        if (identification == null)
        {
            lusername = (String[]) Serialization.deserialize(String[].class, (String) parameters.getParameterValue("body-content"));
            identification = new SessionIdentification();
        } else
        {
            lusername = new String[identification.luser.size()];
            for (int i = 0; i < lusername.length; i++)
            {
                try
                {
                    lusername[i] = Licence.decrypt(identification.luser.get(i).username);
                } catch (Exception ex)
                {
                    lusername[i] = identification.luser.get(i).username;
                    Logger.getLogger(ModelSessions.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        identification.timestampEnd = System.currentTimeMillis();
        
        String usernameAction = parameters.getParameterValue("username")!=null?parameters.getParameterValue("username"):lusername[0];
        String computerAction = parameters.getParameterValue("computer");
        Session session = new Session();
        for (String username : lusername)
        {
            //CREATE AND SAVE ACCTION
            User userAction = new User();
            userAction.information = new UserInformation();
            try
            {
                userAction.information.setIdentifier(Licence.decrypt(username));
            } catch (Exception e)
            {
                userAction.information.setIdentifier(username);
            }
 
            Session sessionAction = new Session();
            sessionAction.identification = session.identification;
            sessionAction.token = session.token;
            sessionAction.role = session.role; 
 
            DeviceAction action = new DeviceAction(userAction, parameters);
            DeviceActionResult actionResult = new DeviceActionResult(DeviceActionResult.RESULT_CORRECT, Shared.getMessage("log out"));
            action.setResult(actionResult);
            Shared.model.addAction(action);
        }
        
        return new InteropResponse(true);
    }
    
    public boolean updateSessionConfiguration(Session session) throws SerializationException
    {
        boolean updated = false;
        if (session.identification.luser.size() > 0)
        {
            if (session.configuration == null)
            {
                session.configuration = new SessionConfiguration();
                updated = true;
            }
            updated = updateSessionPermissions(session, updated);
            updateSessionRole(session);
            updateSessionWebProperties(session);
            updateSessionAlarms(session);
        }
        return updated;
    }
 
    private boolean updateSessionPermissions(Session session, boolean updated) throws SerializationException
    {
        try
        {
            InteropParameters parametersGetUserPermission = new InteropParameters();
            parametersGetUserPermission.addParameter(new InteropParameter("language", Shared.configuration.general.language));
            parametersGetUserPermission.addBodycontent(session.getUsernames());
            parametersGetUserPermission.addParameter(new InteropParameter("timestamp", String.valueOf(session.configuration.timestamp)));
            InteropResponse response = Shared.getModel().modelPermissions.getUserPermission(parametersGetUserPermission);
            UserPermission newPermissions = (UserPermission) response.getValue()[0];
 
            if (!Serialization.equals(session.configuration.permissions, newPermissions))
            {
                session.configuration.permissions = newPermissions;
                session.configuration.timestamp = System.currentTimeMillis();
                updated = true;
            }
        } catch (Exception ex)
        {
            Logger.getLogger(ModelSessions.class.getName()).log(Level.INFO, "", ex);
        }
        return updated;
    }
    
    private void updateSessionRole(Session session) throws SerializationException
    {
        String role = "";
        for (UserIdentification userIdentification : session.identification.luser)
        {
            if (userIdentification.role != null)
            {
                if (userIdentification.role.equals("Administrator"))
                {
                    role = userIdentification.role;
                } else if (userIdentification.equals("Write") && !role.equals("Administrator"))
                {
                    role = userIdentification.role;
                } else if (userIdentification.role.equals("Read") && !role.equals("Administrator") && !role.equals("Write"))
                {
                    role = userIdentification.role;
                }
            }
        }
        session.role = role;
    }
 
    private void updateSessionAlarms(Session session) throws SerializationException
    {
        try
        {
            InteropParameters parametersGetUserPermission = new InteropParameters();
            parametersGetUserPermission.addParameter(new InteropParameter("language", Shared.configuration.general.language));
            parametersGetUserPermission.addBodycontent(session.getUsernames());
            parametersGetUserPermission.addParameter(new InteropParameter("timestamp", String.valueOf(session.configuration.timestamp)));
            InteropResponse response = Shared.getModel().modelAlarms.getAlarmsUserConfiguration(
                    parametersGetUserPermission);
            session.configuration.lalarmConfiguration = Arrays.asList(Arrays.copyOf(response.getValue(), response.getValue().length, UserAlarmConfiguration[].class));
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    //</editor-fold>
 
    //<editor-fold defaultstate="collapsed" desc="Utils">
    
    /**
     * Check UserIdentification[]
     * add to the session all Users with valid UserIdentification user-password
     * @param session
     * @param usersIdentification
     * @return
     * @throws SerializationException
     * @throws Exception 
     */
    
    @SuppressWarnings("unchecked")
    private Session checkSessionAndAddAllowedUsers(Session session, UserIdentification[] usersIdentification,
            boolean secureUser, String usernameAction, String computerAction) throws SerializationException
    {
        String resultMessage = "invalid user";
        try
        {
            //CHECK USER PASSWORD
            byte resultType = DeviceActionResult.RESULT_ERROR;
            for (UserIdentification userIdentification : usersIdentification)
            {
 
                if (!secureUser){
                    userIdentification.username = Licence.encrypt(userIdentification.username);
                    userIdentification.password = Licence.encrypt(userIdentification.password);
                }
                
                User user = new User(userIdentification.username);
                user.username = userIdentification.username;
                user.getDeviceInformation().password = userIdentification.password;
 
                User nextUser = (User) Shared.getModel().getDevice(user.getIdentifier());
                if (user.username.equals(nextUser.username))
                {
                    resultType = DeviceActionResult.RESULT_CORRECT;
                    if ((nextUser.alarms != null) && (nextUser.alarms.alarm_disabled > 0))
                    {
                        continue;
                    }
                    if (user.getDeviceInformation().password.equals(nextUser.getDeviceInformation().password))
                    {
                        userIdentification.group = nextUser.information.group;
                        userIdentification.name = nextUser.information.name;
                        userIdentification.role = nextUser.getDeviceInformation().role;
                        userIdentification.console = session.identification.console;
                        userIdentification.timestampStart = System.currentTimeMillis();
                        session.addUserIdentification(userIdentification);
                        resultMessage = "log in";
                    } else
                    {
                        resultMessage = "invalid password";
                        resultType = DeviceActionResult.RESULT_ERROR;
                    }
                }
                
                addActionCheckSessionAndAddAllowedUsers(user, session, computerAction, resultMessage, resultType);
                
                if (resultType != DeviceActionResult.RESULT_CORRECT)
                {
                    throw new SerializationException(resultMessage);
                } else
                {
                    if (Shared.getModel().loginBlockedManager
                            .isAddressLoginBlocked(computerAction))
                    {
                        resultMessage = "blocked address";
                        throw new SerializationException(resultMessage);
                    }
                    if (Shared.getModel().loginBlockedManager
                            .isUserBlocked(user.username))
                    {
                        resultMessage = "blocked user";
                        throw new SerializationException(resultMessage);
                    }
                }
            }
            
            addUsersGenericIntoSession(session, Shared.getModel().getDevicesUserGenericGroup());
            Shared.getModel().loginBlockedManager.addCorrectLoginAttempt(usersIdentification, computerAction, session.identification.timestampStart);
            return session;
        } catch (Exception exception)
        {
            try
            {
                exception.printStackTrace();
                Shared.getModel().loginBlockedManager
                        .addFailedLoginAttempt(usersIdentification, computerAction, session.identification.timestampStart);
                throw new SerializationException(resultMessage, exception);
            } catch (Exception exceptionLoginBlockedManager)
            {
                exceptionLoginBlockedManager.printStackTrace();
                throw new SerializationException(resultMessage, exceptionLoginBlockedManager);
            }
        }
    }
//</editor-fold>
 
    private void addActionCheckSessionAndAddAllowedUsers(User user, Session session, String computerAction, String resultMessage, byte resultType) throws Exception
    {
        try
        {
            User userAction = new User();
            userAction.information = new UserInformation();
            userAction.information.setIdentifier(Licence.decrypt(user.username));
 
            Session sessionAction = new Session();
            sessionAction.identification = session.identification;
            sessionAction.token = session.token;
            sessionAction.role = session.role;
 
            InteropParameters parameters = new InteropParameters();
            parameters.addParameter("username", Licence.decrypt(user.username));
            parameters.addParameter("computer", computerAction);
            parameters.addParameter("operation", Shared.getMessage(resultMessage));
            DeviceAction action = new DeviceAction(userAction, parameters);
            DeviceActionResult actionResult = new DeviceActionResult(resultType, Shared.getMessage(resultMessage));
            action.setResult(actionResult);
            DevicePersistenceAction persistenceAction = new DevicePersistenceAction(action);
            Shared.model.addAction(action);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw e;
        }
    }
 
    public void addUsersGenericIntoSession(Session session, List<User> luserGeneric)
    {
        try
        {            
            List<UserIdentification> luserIdentificationGeneric = new ArrayList<>();
            for (User userGeneric : luserGeneric)
            {
                addUserGenericIntoSession(session, userGeneric, luserIdentificationGeneric);
            }
            session.identification.luser.addAll(luserIdentificationGeneric);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
 
    /**
     * It adds into the session the user generic given when any user.information.group in the session has the user generic given
     * @param session
     * @param userGeneric 
     */
    private void addUserGenericIntoSession(Session session, User userGeneric, List<UserIdentification> luserIdentificationGeneric)
    {
        boolean foundUserGeneric = false;
        try
        {
            Iterator<UserIdentification> iterator = session.identification.luser.iterator();
            while (!foundUserGeneric && iterator.hasNext())
            {
                UserIdentification nextUserIdentification = iterator.next();
                if ((nextUserIdentification.group.equals(userGeneric.getDeviceInformation().group))
                        && userGeneric.getDeviceInformation().groupManager == true)
                {
                    foundUserGeneric = true;
                    luserIdentificationGeneric.add(new UserIdentification(userGeneric.getDeviceInformation().group, userGeneric.username, userGeneric.getDeviceInformation().password));
                }
            }
        } catch (Exception e)
        {
        }
    }
 
    private void updateSessionWebProperties(Session session) throws SerializationException
    {   
        if (session.configuration == null) session.configuration = new SessionConfiguration();
        SessionWebProperties sessionWebProperties = new SessionWebProperties();
        sessionWebProperties.userPrivileges = new UserPrivileges();
        
        User[] luser = Shared.getModel().getDevices(session.getUsernames(), 0);
        if (luser.length > 0)
        {
            User user = luser[0];
            UserProperties properties = user.getDeviceInformation().properties;
            session.configuration.sessionWebProperties = getSessionWebPropertiesFrom(properties);
        }else new SerializationException("");
    }
 
    private SessionWebProperties getSessionWebPropertiesFrom(UserProperties properties)
    {
        if (properties==null) return null;
        SessionWebProperties sessionWebProperties = new SessionWebProperties();
        if (properties.alarms == null)
            sessionWebProperties.alarms = new String[0];
        else
            sessionWebProperties.alarms = properties.alarms.toArray(new String[0]);
 
        if (properties.weatherNotifications == null)
            sessionWebProperties.weatherNotifcations = new String[0];
        else
            sessionWebProperties.weatherNotifcations = properties.weatherNotifications.toArray(new String[0]);
 
        sessionWebProperties.userDisplayList = properties.userDisplayList;
        sessionWebProperties.userPrivileges = properties.userPrivileges;
 
        return sessionWebProperties;
    }
    
    
    
    
}