Repository navigation
Expand file tree
/
Copy pathGetter.java
More file actions
1920 lines (1847 loc) · 69.4 KB
/
Copy pathGetter.java
File metadata and controls
1920 lines (1847 loc) · 69.4 KB
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package dbProcs;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Encoder;
import utils.ScoreboardStatus;
/**
* Used to retrieve information from the Database
* <br/><br/>
* This file is part of the Security Shepherd Project.
*
* The Security Shepherd project is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.<br/>
*
* The Security Shepherd project is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.<br/>
*
* You should have received a copy of the GNU General Public License
* along with the Security Shepherd project. If not, see <http://www.gnu.org/licenses/>.
* @author Mark
*/
public class Getter
{
private static org.apache.log4j.Logger log = Logger.getLogger(Getter.class);
/**
* Used for scoreboards / progress bars
*/
private static int widthOfUnitBar = 11; //px
private static int fieldTrainingCap = 45;
private static int privateCap = 80;
private static int corporalCap = 105;
private static int sergeantCap = 130;
private static int lieutenantCap = 145;
private static int majorCap = 175;
private static int admiralCap = 999; //everything above Major is Admiral
/**
* This method hashes the user submitted password and sends it to the database.
* The database does the rest of the work, including Brute Force prevention.
* @param userName The submitted user name to be used in authentication process
* @param password The submitted password in plain text to be used in authentication
* @return A string array made up of nothing or information to be consumed by the initiating authentication process.
*/
public static String[] authUser (String ApplicationRoot, String userName, String password)
{
String[] result = null;
log.debug("$$$ Getter.authUser $$$");
log.debug("userName = " + userName);
boolean userFound = false;
boolean goOn = false;
Connection conn = Database.getCoreConnection(ApplicationRoot);
try
{
//See if user Exists
CallableStatement callstmt = conn.prepareCall("call userFind(?)");
log.debug("Gathering userFind ResultSet");
callstmt.setString(1, userName);
ResultSet userFind = callstmt.executeQuery();
log.debug("Opening Result Set from userFind");
try
{
userFind.next();
log.debug("User Found"); //User found if a row is in the database, this line will not work if the result set is empty
userFound = true;
}
catch(Exception e)
{
log.debug("User did not exist");
userFound = false;
}
if(userFound)
{
//Authenticate User
callstmt = conn.prepareCall("call authUser(?, ?)");
log.debug("Gathering authUser ResultSet");
callstmt.setString(1, userName);
callstmt.setString(2, password);
ResultSet loginAttempt = callstmt.executeQuery();
log.debug("Opening Result Set from authUser");
try
{
loginAttempt.next();
goOn = true; //Valid password for user submitted
}
catch (SQLException e)
{
//... Outer Catch has preference to this one for some reason... This code is never reached!
// But I'll leave it here just in case. That includes the else block if goOn is false
log.debug("Incorrect Credentials");
goOn = false;
}
if(goOn)
{
//ResultSet Not Empty => Credentials Correct
result = new String[5];
result[0] = loginAttempt.getString(1); //Id
result[1] = loginAttempt.getString(2); //userName
result[2] = loginAttempt.getString(3); //role
result[4] = loginAttempt.getString(6); //classId
if (loginAttempt.getBoolean(5)) //Checking for temp password flag, if true, index View will prompt to change
result[3] = "true";
else
result[3] = "false";
if (!result[1].equals(userName)) //If somehow this functionality has been compromised to sign in as other users, this will limit the expoitability. But the method is sql injection safe, so it should be ok
{
log.fatal("User Name used ("+ userName +") and User Name retrieved ("+ result[1] +") were not the Same. Nulling Result");
result = null;
}
else
{
log.debug("User '" + userName + "' has logged in");
//Before finishing, check if user had a badlogin history, if so, Clear it
if(loginAttempt.getInt(4) > 0)
{
log.debug("Clearing Bad Login History");
callstmt = conn.prepareCall("call userBadLoginReset(?)");
callstmt.setString(1, result[0]);
callstmt.execute();
log.debug("userBadLoginReset executed!");
}
}
//User has logged in, or a Authentication Bypass was detected... You never know! Better safe than sorry
return result;
}
}
}
catch (SQLException e)
{
log.error("Login Failure: " + e.toString());
result = null;
//Lagging Response
}
Database.closeConnection(conn);
log.debug("$$$ End authUser $$$");
return result;
}
/**
* Used to determine if a user has completed a module already
* @param ApplicationRoot The current running context of an application
* @param moduleId The module identifier
* @param userId The user identifier
* @return The module name of the module IF the user has not completed AND the user has previously opened the challenge.
*/
public static String checkPlayerResult(String ApplicationRoot, String moduleId, String userId)
{
log.debug("*** Getter.checkPlayerResult ***");
String result = null;
Connection conn = Database.getCoreConnection(ApplicationRoot);
try
{
log.debug("Preparing userCheckResult call");
CallableStatement callstmnt = conn.prepareCall("call userCheckResult(?, ?)");
callstmnt.setString(1, moduleId);
callstmnt.setString(2, userId);
log.debug("Executing userCheckResult");
ResultSet resultSet = callstmnt.executeQuery();
resultSet.next();
result = resultSet.getString(1);
}
catch(SQLException e)
{
log.debug("userCheckResult Failure: " + e.toString());
result = null;
}
Database.closeConnection(conn);
log.debug("*** END checkPlayerResult ***");
return result;
}
/**
* Used to decipher whether or not a user exists as a player
* @param userId The user identifier of the player to be found
* @return A boolean reflecting the state of existence of the player
*/
public static boolean findPlayerById (String ApplicationRoot, String userId)
{
log.debug("*** Getter.findPlayerById ***");
boolean userFound = false;
//Get connection
Connection conn = Database.getCoreConnection(ApplicationRoot);
try
{
CallableStatement callstmt = conn.prepareCall("call playerFindById(?)");
log.debug("Gathering playerFindById ResultSet");
callstmt.setString(1, userId);
ResultSet userFind = callstmt.executeQuery();
log.debug("Opening Result Set from playerFindById");
userFind.next(); //This will throw an exception if player not found
log.debug("Player Found: " + userFind.getString(1)); //This line will not execute if player not found
userFound = true;
}
catch(Exception e)
{
log.error("Player did not exist: " + e.toString());
userFound = false;
}
Database.closeConnection(conn);
log.debug("*** END findPlayerById ***");
return userFound;
}
/**
* Used to gather all module information for internal functionality. This method is used in creating View's or in control class operations
* @param ApplicationRoot The current runing context of the application
* @return An ArrayList of String arrays that contain the module identifier, module name, module type and module category of each module in the core database.
*/
public static ArrayList<String[]> getAllModuleInfo (String ApplicationRoot)
{
log.debug("*** Getter.getAllModuleInfo ***");
ArrayList<String[]> modules = new ArrayList<String[]>();
Connection conn = Database.getCoreConnection(ApplicationRoot);
try
{
CallableStatement callstmt = conn.prepareCall("call moduleGetAll()");
log.debug("Gathering moduleGetAll ResultSet");
ResultSet resultSet = callstmt.executeQuery();
log.debug("Opening Result Set from moduleGetAll");
int i = 0;
while(resultSet.next())
{
String[] result = new String[4];
i++;
result[0] = resultSet.getString(1); //moduleId
result[1] = resultSet.getString(2); //moduleName
result[2] = resultSet.getString(3); //moduleType
result[3] = resultSet.getString(4); //mdouleCategory
modules.add(result);
}
log.debug("Returning Array list with " + i + " entries.");
}
catch (SQLException e)
{
log.error("Could not execute query: " + e.toString());
}
Database.closeConnection(conn);
log.debug("*** END getAllModuleInfo ***");
return modules;
}
/**
* Returns HTML menu for challenges. Challenges are only referenced by their id,
* The user will have to go through another servlet to get the module's View address
* @param ApplicationRoot The current running context of the application
* @return HTML menu for challenges
*/
public static String getChallenges (String ApplicationRoot, String userId, Locale lang)
{
log.debug("*** Getter.getChallenges ***");
String output = new String();
//Getting Translated Level Names
ResourceBundle bundle = ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", lang);
//Encoder to prevent XSS
Encoder encoder = ESAPI.encoder();
Connection conn = Database.getCoreConnection(ApplicationRoot);
try
{
CallableStatement callstmt = conn.prepareCall("call moduleAllInfo(?, ?)");
callstmt.setString(1, "challenge");
callstmt.setString(2, userId);
log.debug("Gathering moduleAllInfo ResultSet");
ResultSet challenges = callstmt.executeQuery();
log.debug("Opening Result Set from moduleAllInfo");
String challengeCategory = new String();
int rowNumber = 0; // Identifies the first row, ie the start of the list. This is slightly different output to every other row
while(challenges.next())
{
if(!challengeCategory.equalsIgnoreCase(challenges.getString(2)))
{
challengeCategory = challenges.getString(2);
//log.debug("New Category Detected: " + challengeCategory);
if(rowNumber > 0) //output prepared for Every row after row 1
output += "</ul></li><li><a href='javascript:;' class='challengeHeader' >" + encoder.encodeForHTML(bundle.getString("category." + challengeCategory))+ "</a><ul class='challengeList' style='display: none;'>";
else //output prepared for First row in entire challenge
output += "<li><a href='javascript:;' class='challengeHeader'>" + encoder.encodeForHTML(bundle.getString("category." + challengeCategory))+ "</a><ul class='challengeList' style='display: none;'>";
//log.debug("Compiling Challenge Category - " + challengeCategory);
}
output += "<li>"; //Starts next LI element
if(challenges.getString(4) != null)
{
output += "<img src='css/images/completed.png'/>"; //Completed marker
}
else
{
output+= "<img src='css/images/uncompleted.png'/>"; //Incomplete marker
}
//Final out put compilation
output +="<a class='lesson' id='"
+ encoder.encodeForHTMLAttribute(challenges.getString(3))
+ "' href='javascript:;'>"
+ encoder.encodeForHTML(bundle.getString(challenges.getString(1)))
+ "</a>";
output += "</li>";
rowNumber++;
}
//Check if output is empty
if(output.isEmpty())
{
output = "<li><a href='javascript:;'>No challenges found</a></li>";
}
else
{
log.debug("Appending End tags");
output += "</ul></li>";
}
}
catch(Exception e)
{
log.error("Challenge Retrieval: " + e.toString());
}
Database.closeConnection(conn);
log.debug("*** END getChallenges() ***");
return output;
}
/**
* @param ApplicationRoot The current running context of the application
* @return The amount of classes currently existing in the database
*/
public static int getClassCount(String ApplicationRoot)
{
int result = 0;
ResultSet resultSet = null;
log.debug("*** Getter.getClassCount ***");
Connection conn = Database.getCoreConnection(ApplicationRoot);
try
{
CallableStatement callstmt = conn.prepareCall("call classCount()");
log.debug("Gathering classCount ResultSet");
resultSet = callstmt.executeQuery();
log.debug("Opening Result Set from classCount");
resultSet.next();
result = resultSet.getInt(1);
}
catch (SQLException e)
{
log.error("Could not execute query: " + e.toString());
result = 0;
}
Database.closeConnection(conn);
log.debug("*** END getClassCount");
return result;
}
/**
* @param ApplicationRoot The current running context of the application
* @return Result set containing class info in the order classId, className and then classYear
*/
public static ResultSet getClassInfo(String ApplicationRoot)
{
ResultSet result = null;
log.debug("*** Getter.getClassInfo (All Classes) ***");
Connection conn = Database.getCoreConnection(ApplicationRoot);
try
{
CallableStatement callstmt = conn.prepareCall("call classesGetData()");
log.debug("Gathering classesGetData ResultSet");
result = callstmt.executeQuery();
log.debug("Returning Result Set from classesGetData");
}
catch (SQLException e)
{
log.error("Could not execute query: " + e.toString());
result = null;
}
log.debug("*** END getClassInfo");
return result;
}
/**
* @param ApplicationRoot The current running context of the application
* @param classId The identifier of the class
* @return String Array with Class information with the format of {name, year}
*/
public static String[] getClassInfo(String ApplicationRoot, String classId)
{
String[] result = new String[2];
log.debug("*** Getter.getClassInfo (Single Class) ***");
Connection conn = Database.getCoreConnection(ApplicationRoot);
try
{
CallableStatement callstmt = conn.prepareCall("call classFind(?)");
callstmt.setString(1, classId);
log.debug("Gathering classFind ResultSet");
ResultSet resultSet = callstmt.executeQuery();
log.debug("Opening Result Set from classFind");
resultSet.next();
result[0] = resultSet.getString(1);//Name
result[1] = resultSet.getString(2);//Year
}
catch (SQLException e)
{
log.error("Could not execute query: " + e.toString());
result = null;
}
log.debug("*** END getClassInfo");
return result;
}
/**
* The CSRF forum is used in CSRF levels for users to deliver CSRF attacks against each other. URLs are contained in IFRAME tags
* @param ApplicationRoot The current running context of the application
* @param classId Identifier of the class to populate the forum with
* @param moduleId The module in which to return the forum for
* @param bundle Strings Package for the Language Local of the user making the request
* @return A HTML table of a Class's CSRF Submissions for a specific module
*/
public static String getCsrfForumWithIframe (String ApplicationRoot, String classId, String moduleId, ResourceBundle bundle)
{
log.debug("*** Getter.getCsrfForum ***");
log.debug("Getting stored messages from class: " + classId);
Encoder encoder = ESAPI.encoder();
String htmlOutput = new String();
Connection conn = Database.getCoreConnection(ApplicationRoot);
try
{
if(classId != null)
{
CallableStatement callstmt = conn.prepareCall("call resultMessageByClass(?, ?)");
log.debug("Gathering resultMessageByClass ResultSet");
callstmt.setString(1, classId);
callstmt.setString(2, moduleId);
ResultSet resultSet = callstmt.executeQuery();
log.debug("resultMessageByClass executed");
//Table Header
htmlOutput = "<table><tr><th>" + bundle.getString("forum.userName") + "</th><th>" + bundle.getString("forum.message") + "</th></tr>";
log.debug("Opening Result Set from resultMessageByClass");
int counter = 0;
while(resultSet.next())
{
counter++;
//Table content
htmlOutput += "<tr><td>" + encoder.encodeForHTML(resultSet.getString(1)) + "</td><td><iframe sandbox=\"allow-scripts allow-forms\" src=\"" + encoder.encodeForHTMLAttribute(resultSet.getString(2)) + "\"></iframe></td></tr>";
}
if(counter > 0)
log.debug("Added a " + counter + " row table");
else
log.debug("No results from query");
//Table end
htmlOutput += "</table>";
}
else
{
log.error("User with Null Class detected");
htmlOutput = "<p><font color='red'>" + bundle.getString("error.noClass") + "</font></p>";
}
}
catch (SQLException e)
{
log.error("Could not execute query: " + e.toString());
htmlOutput = "<p>" + bundle.getString("error.occurred ") + "</p>";
}
catch (Exception e)
{
log.fatal("Could not return CSRF Forum: " + e.toString());
}
Database.closeConnection(conn);
log.debug("*** END getCsrfForum ***");
return htmlOutput;
}
/**
* The CSRF forum is used in CSRF levels for users to deliver CSRF attacks against each other. URLs are contained in IMG tags
* @param ApplicationRoot The current running context of the application
* @param classId Identifier of the class to populate the forum with
* @param moduleId The module in which to return the forum for
* @param bundle The strings package for the language of the user
* @return A HTML table of a Class's CSRF Submissions for a specific module
*/
public static String getCsrfForumWithImg (String ApplicationRoot, String classId, String moduleId, ResourceBundle bundle)
{
log.debug("*** Getter.getCsrfForum ***");
log.debug("Getting stored messages from class: " + classId);
Encoder encoder = ESAPI.encoder();
String htmlOutput = new String();
Connection conn = Database.getCoreConnection(ApplicationRoot);
try
{
if(classId != null)
{
CallableStatement callstmt = conn.prepareCall("call resultMessageByClass(?, ?)");
log.debug("Gathering resultMessageByClass ResultSet");
callstmt.setString(1, classId);
callstmt.setString(2, moduleId);
ResultSet resultSet = callstmt.executeQuery();
log.debug("resultMessageByClass executed");
//Table Header
htmlOutput = "<table><tr><th>" + bundle.getString("forum.userName") + "</th><th>" + bundle.getString("forum.image") + "</th></tr>";
log.debug("Opening Result Set from resultMessageByClass");
int counter = 0;
while(resultSet.next())
{
counter++;
//Table content
htmlOutput += "<tr><td>" + encoder.encodeForHTML(resultSet.getString(1)) + "</td><td><img src=\"" + encoder.encodeForHTMLAttribute(resultSet.getString(2)) + "\"/></td></tr>";
}
if(counter > 0)
log.debug("Added a " + counter + " row table");
else
log.debug("No results from query");
//Table end
htmlOutput += "</table>";
}
else
{
log.error("User with Null Class detected");
htmlOutput = "<p><font color='red'>" + bundle.getString("error.noClass") + "</font></p>";
}
}
catch (SQLException e)
{
log.error("Could not execute query: " + e.toString());
htmlOutput = "<p>" + bundle.getString("error.occurred") + "</p>";
}
catch (Exception e)
{
log.fatal("Could not return CSRF Forum: " + e.toString());
}
Database.closeConnection(conn);
log.debug("*** END getCsrfForum ***");
return htmlOutput;
}
/**
* Used to present a modules feedback, including averages and raw results.
* @param applicationRoot The current running context of the application.
* @param moduleId The module identifier
* @return A HTML table of the feedback for a specific module
*/
public static String getFeedback(String applicationRoot, String moduleId)
{
log.debug("*** Getter.getFeedback ***");
String result = new String();
Encoder encoder = ESAPI.encoder();
Connection conn = Database.getCoreConnection(applicationRoot);
try
{
log.debug("Preparing userUpdateResult call");
CallableStatement callstmnt = conn.prepareCall("call moduleFeedback(?)");
callstmnt.setString(1, moduleId);
log.debug("Executing moduleFeedback");
ResultSet resultSet = callstmnt.executeQuery();
int resultAmount = 0;
int before = 0;
int after = 0;
int difficulty = 0;
boolean color = true;
while(resultSet.next())
{
if(resultSet.getString(1) != null)
{
resultAmount++;
difficulty += resultSet.getInt(3);
before += resultSet.getInt(4);
after += resultSet.getInt(5);
result += "<tr ";
if(color) //Alternate row color
{
color = !color;
result += "BGCOLOR='A878EF'";
}
else
{
color = !color;
result += "BGCOLOR='D4BCF7'";
}
//A row off information
result += "><td>" + encoder.encodeForHTML(resultSet.getString(1)) + "</td><td>" + encoder.encodeForHTML(resultSet.getString(2)) + "</td><td>" +
resultSet.getInt(3) + "</td><td>" + resultSet.getInt(4) + "</td><td>" +
resultSet.getInt(5) + "</td><td>" + encoder.encodeForHTML(resultSet.getString(6)) + "</td></tr>";
}
}
if(resultAmount > 0)//Table header
result = "<table><tr><th>Player</th><th>Time</th><th>Difficulty</th><th>Before</th><th>After</th><th>Comments</th></tr>" +
"<tr><td>Average</td><td></td><td>" + difficulty/resultAmount + "</td><td>" +
before/resultAmount + "</td><td>" + after/resultAmount + "</td><td></td></tr>" + result + "<table>";
else // If empty, Blank output
result = new String();
}
catch(SQLException e)
{
log.error("moduleFeedback Failure: " + e.toString());
result = null;
}
Database.closeConnection(conn);
log.debug("*** END getFeedback ***");
return result;
}
/**
* This method prepares the incremental module menu. This is when Security Shepherd is in "Game Mode".
* Users are presented with one uncompleted module at a time. This method also returns a script to be executed every time the menu is chanegd.
* This is script defines the animation and operations to be carried out when the menu is interacted with
* @param ApplicationRoot The running context of the application.
* @param userId The user identifier of the user.
* @param csrfToken The cross site request forgery token
* @return A HTML menu of a users current module progress and a script for interaction with this menu
*/
public static String getIncrementalModules (String ApplicationRoot, String userId, String lang, String csrfToken)
{
log.debug("*** Getter.getIncrementalChallenges ***");
String output = new String();
Encoder encoder = ESAPI.encoder();
Connection conn = Database.getCoreConnection(ApplicationRoot);
Locale.setDefault(new Locale("en"));
Locale locale = new Locale(lang);
ResourceBundle bundle = ResourceBundle.getBundle("i18n.text", locale);
ResourceBundle levelNames = ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", locale);
try
{
CallableStatement callstmt = conn.prepareCall("call moduleIncrementalInfo(?)");
callstmt.setString(1, userId);
log.debug("Gathering moduleIncrementalInfo ResultSet");
ResultSet modules = callstmt.executeQuery();
log.debug("Opening Result Set from moduleIncrementalInfo");
boolean lastRow = false;
boolean completedModules = false;
//Preparing first Category header; "Completed"
output = "<li><a id='completedList' href='javascript:;'><div class='menuButton'>" + bundle.getString("getter.button.completed") + "</div></a>\n" +
"<ul id='theCompletedList' style='display: none;' class='levelList'>";
while(modules.next() && !lastRow)
{
//For each row, prepair the modules the users can select
if(modules.getString(4) != null) //If not Last Row
{
completedModules = true;
output += "<li>";
output += "<a class='lesson' id='"
+ encoder.encodeForHTMLAttribute(modules.getString(3))
+ "' href='javascript:;'>"
+ encoder.encodeForHTML(levelNames.getString(modules.getString(1)))
+ "</a>";
output += "</li>";
}
else
{
lastRow = true;
//Last Row - Highlighed Next Challenge
if(completedModules)
{
output += "</ul></li><li>";
}
else
{
//NO completed modules, so dont show any...
output = new String();
}
//Second category - Uncompleted
output += "<a class='lesson' id='"
+ encoder.encodeForHTMLAttribute(modules.getString(3))
+ "' href='javascript:;'>"
+ "<div class='menuButton'>" + bundle.getString("getter.button.nextChallenge")+ "</div>"
+ "</a>";
output += "</li>";
}
}
if(!lastRow) //If true, then the user has completed all challenges
{
output += "<h2 id='uncompletedList'><a href='javascript:;'>" + bundle.getString("getter.button.finished") + "</a></h2>\n" +
"</li>";
}
if(output.isEmpty()) //If this method has gone so far without any output, create a error message
{
output = "<li><a href='javascript:;'>" + bundle.getString("getter.button.noModulesFound") + "</a></li>";
}
else //final tags to ensure valid HTML
{
log.debug("Appending End tags");
//output += "</ul></li>"; //Commented Out to prevent Search Box being pushed into Footer
}
//This is the script for menu interaction
output += "<script>applyMenuButtonActionsCtfMode('" + encoder.encodeForHTML(csrfToken) + "', \"" + encoder.encodeForHTML(bundle.getString("generic.text.sorryError")) + "\");</script>";
}
catch(Exception e)
{
log.error("Challenge Retrieval: " + e.toString());
}
Database.closeConnection(conn);
log.debug("*** END getIncrementalChallenges() ***");
return output;
}
/**
* This method prepares the incremental module menu. This is when Security Shepherd is in "Game Mode".
* Users are presented with one uncompleted module at a time. This method does not return the JS script describing how the menu used should work
* @param ApplicationRoot The running context of the application.
* @param userId The user identifier of the user.
* @param csrfToken The cross site request forgery token
* @return A HTML menu of a users current module progress and a script for interaction with this menu
*/
public static String getIncrementalModulesWithoutScript (String ApplicationRoot, String userId, String lang, String csrfToken)
{
log.debug("*** Getter.getIncrementalChallengesWithoutScript ***");
String output = new String();
Encoder encoder = ESAPI.encoder();
Connection conn = Database.getCoreConnection(ApplicationRoot);
Locale.setDefault(new Locale("en"));
Locale locale = new Locale(lang);
ResourceBundle bundle = ResourceBundle.getBundle("i18n.text", locale);
ResourceBundle levelNames = ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", locale);
try
{
CallableStatement callstmt = conn.prepareCall("call moduleIncrementalInfo(?)");
callstmt.setString(1, userId);
log.debug("Gathering moduleIncrementalInfo ResultSet");
ResultSet modules = callstmt.executeQuery();
log.debug("Opening Result Set from moduleIncrementalInfo");
boolean lastRow = false;
boolean completedModules = false;
//Preparing first Category header; "Completed"
output = "<li><a id='completedList' href='javascript:;'><div class='menuButton'>" + bundle.getString("getter.button.completed") + "</div></a>\n" +
"<ul id='theCompletedList' style='display: none;' class='levelList'>";
while(modules.next() && !lastRow)
{
//For each row, prepair the modules the users can select
if(modules.getString(4) != null) //If not Last Row
{
completedModules = true;
output += "<li>";
output += "<a class='lesson' id='"
+ encoder.encodeForHTMLAttribute(modules.getString(3))
+ "' href='javascript:;'>"
+ encoder.encodeForHTML(levelNames.getString(modules.getString(1)))
+ "</a>";
output += "</li>";
}
else
{
lastRow = true;
//Last Row - Highlighed Next Challenge
if(completedModules)
{
output += "</ul></li><li>";
}
else
{
//NO completed modules, so dont show any...
output = new String();
}
//Second category - Uncompleted
output += "<a class='lesson' id='"
+ encoder.encodeForHTMLAttribute(modules.getString(3))
+ "' href='javascript:;'>"
+ "<div class='menuButton'>" + bundle.getString("getter.button.nextChallenge")+ "</div>"
+ "</a>";
output += "</li>";
}
}
if(!lastRow) //If true, then the user has completed all challenges
{
output += "<h2 id='uncompletedList'><a href='javascript:;'>" + bundle.getString("getter.button.finished") + "</a></h2>\n" +
"</li>";
}
if(output.isEmpty()) //If this method has gone so far without any output, create a error message
{
output = "<li><a href='javascript:;'>" + bundle.getString("getter.button.noModulesFound") + "</a></li>";
}
else //final tags to ensure valid HTML
{
log.debug("Appending End tags");
//output += "</ul></li>"; //Commented Out to prevent Search Box being pushed into Footer
}
}
catch(Exception e)
{
log.error("Challenge Retrieval: " + e.toString());
}
Database.closeConnection(conn);
log.debug("*** END getIncrementalChallengesWithoutScript() ***");
return output;
}
/**
* Use to return the current progress of a class in JSON format with information like userid, user name and score
* @param applicationRoot The current running context of the application
* @param classId The identifier of the class to use in lookup
* @return A JSON representation of a class's score in the order {id, username, userTitle, score, scale, place, order,
* goldmedalcount, goldDisplay, silverMedalCount, silverDisplay, bronzeDisplay, bronzeMedalCount}
*/
@SuppressWarnings("unchecked")
public static String getJsonScore(String applicationRoot, String classId)
{
log.debug("classId: " + classId);
String result = new String();
Connection conn = Database.getCoreConnection(applicationRoot);
try
{
Encoder encoder = ESAPI.encoder();
//Returns User's: Name, # of Completed modules and Score
CallableStatement callstmnt = null;
if(ScoreboardStatus.getScoreboardClass().isEmpty() && !ScoreboardStatus.isClassSpecificScoreboard())
callstmnt = conn.prepareCall("call totalScoreboard()"); //Open Scoreboard not based on a class
else
{
callstmnt = conn.prepareCall("call classScoreboard(?)"); //Class Scoreboard based on classId
callstmnt.setString(1, classId);
}
//log.debug("Executing classScoreboard");
ResultSet resultSet = callstmnt.executeQuery();
JSONArray json = new JSONArray();
JSONObject jsonInner = new JSONObject();
int resultAmount = 0;
int prevPlace = 0;
int prevScore = 0;
int prevGold = 0;
int prevSilver = 0;
int prevBronze = 0;
float baseBarScale = 0; //
float tieBreaker = 0;
while(resultSet.next()) //For each user in a class
{
resultAmount++;
jsonInner = new JSONObject();
if(resultSet.getString(1) != null)
{
int place = resultAmount;
int score = resultSet.getInt(3);
int goldMedals = resultSet.getInt(4);
int silverMedals = resultSet.getInt(5);
int bronzeMedals = resultSet.getInt(6);
if(resultAmount == 1) //First Place is Returned First, so this will be the biggest bar on the scoreboard
{
int highscore = score;
//log.debug("Current Highscore Listing is " + highscore);
//Use the high score to scale the width of the bars for the whole scoreboard
float maxBarScale = 1.02f; //High Score bar will have a scale of 1 //This will get used when a scale is added to the scoreboard
baseBarScale = highscore * maxBarScale;
//setting up variables for Tie Scenario Placings
prevPlace = 1;
prevScore = score;
}
else
{
//Does this score line match the one before (Score and Medals)? if so the place shouldnt change
if (score == prevScore && goldMedals == prevGold && silverMedals == prevSilver && bronzeMedals == prevBronze)
{
place = prevPlace;
tieBreaker = tieBreaker + 0.01f;
}
else
{
prevScore = score;
prevPlace = place;
prevGold = goldMedals;
prevSilver = silverMedals;
prevBronze = bronzeMedals;
tieBreaker = 0;
}
}
String displayMedal = new String("display: inline;");
String goldDisplayStyle = new String("display: none;");
String silverDisplayStyle = new String("display: none;");
String bronzeDisplayStyle = new String("display: none;");
if (goldMedals > 0)
goldDisplayStyle = displayMedal;
if (silverMedals > 0)
silverDisplayStyle = displayMedal;
if (bronzeMedals > 0)
bronzeDisplayStyle = displayMedal;
int barScale = (int)((score*100)/baseBarScale); //bar scale is the percentage the bar should be of the row's context (Highest Possible is depends on scale set in maxBarScale. eg: maxBarScale = 1.1 would mean the max scale would be 91% for a single row)
String userMedalString = new String();
if(goldMedals > 0 || silverMedals > 0 || bronzeMedals > 0)
{
userMedalString += " holding ";
if (goldMedals > 0)
userMedalString += goldMedals + " gold";
if (silverMedals > 0)
{
if (goldMedals > 0) //Medals Before, puncuate
{
if(bronzeMedals > 0) //more medals after silver? Comma
{
userMedalString += ", ";
}
else //Say And
{
userMedalString += " and ";
}
}
userMedalString += silverMedals + " silver";
}
if (bronzeMedals > 0)
{
if (goldMedals > 0 || silverMedals > 0) //Medals Before?
{
userMedalString += " and ";
}
userMedalString += bronzeMedals + " bronze";
}
//Say Medal(s) at the end of the string
userMedalString += " medal";
if(goldMedals + silverMedals + bronzeMedals > 1)
userMedalString += "s";
}
jsonInner.put("id", new String(encoder.encodeForHTML(resultSet.getString(1)))); //User Id
jsonInner.put("username", new String(encoder.encodeForHTML(resultSet.getString(2)))); //User Name
jsonInner.put("userTitle", new String(encoder.encodeForHTML(resultSet.getString(2)) + " with " + score + " points" + userMedalString)); //User name encoded for title attribute
jsonInner.put("score", new Integer(score)); //Score
jsonInner.put("scale", barScale); //Scale of score bar
jsonInner.put("place", place); //Place on board
jsonInner.put("order", (place+tieBreaker)); //Order on board
jsonInner.put("goldMedalCount", new Integer(goldMedals));
jsonInner.put("goldDisplay", goldDisplayStyle);
jsonInner.put("silverMedalCount", new Integer(silverMedals));
jsonInner.put("silverDisplay", silverDisplayStyle);
jsonInner.put("bronzeMedalCount", new Integer(bronzeMedals));
jsonInner.put("bronzeDisplay", bronzeDisplayStyle);
//log.debug("Adding: " + jsonInner.toString());
json.add(jsonInner);
}
}
if(resultAmount > 0)
result = json.toString();
else
result = new String();
}
catch(SQLException e)
{
log.error("getJsonScore Failure: " + e.toString());
result = null;
}
catch(Exception e)
{
log.error("getJsonScore Unexpected Failure: " + e.toString());
result = null;
}
Database.closeConnection(conn);
//log.debug("*** END getJsonScore ***");
return result;
}
/**
* Used to gather a menu of lessons for a user, including markers for each lesson they have completed or not completed
* @param ApplicationRoot The current running context of the application
* @param userId Identifier of the user
* @return HTML lesson menu for Open Floor Plan.
*/
public static String getLessons (String ApplicationRoot, String userId, Locale lang)
{
log.debug("*** Getter.getLesson ***");
//Getting Translated Level Names
ResourceBundle bundle = ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", lang);
String output = new String();
Encoder encoder = ESAPI.encoder();
Connection conn = Database.getCoreConnection(ApplicationRoot);
try
{
//Get the lesson modules
CallableStatement callstmt = conn.prepareCall("call lessonInfo(?)");
callstmt.setString(1, userId);