7dabe4f2720e1836dfa5e383df61a433ae80310f
[gigi.git] / util-testing / club / wpia / gigi / pages / Manager.java
1 package club.wpia.gigi.pages;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.lang.reflect.Field;
6 import java.security.GeneralSecurityException;
7 import java.security.KeyPair;
8 import java.security.KeyPairGenerator;
9 import java.security.Signature;
10 import java.sql.Timestamp;
11 import java.text.SimpleDateFormat;
12 import java.util.Base64;
13 import java.util.Calendar;
14 import java.util.Date;
15 import java.util.GregorianCalendar;
16 import java.util.HashMap;
17 import java.util.Iterator;
18 import java.util.LinkedList;
19 import java.util.List;
20 import java.util.Locale;
21 import java.util.Map;
22 import java.util.Properties;
23 import java.util.Random;
24 import java.util.TreeSet;
25 import java.util.regex.Matcher;
26 import java.util.regex.Pattern;
27
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
30
31 import club.wpia.gigi.Gigi;
32 import club.wpia.gigi.GigiApiException;
33 import club.wpia.gigi.crypto.SPKAC;
34 import club.wpia.gigi.database.GigiPreparedStatement;
35 import club.wpia.gigi.dbObjects.CATS;
36 import club.wpia.gigi.dbObjects.CATS.CATSType;
37 import club.wpia.gigi.dbObjects.Certificate;
38 import club.wpia.gigi.dbObjects.Certificate.CertificateStatus;
39 import club.wpia.gigi.dbObjects.CertificateOwner;
40 import club.wpia.gigi.dbObjects.Contract;
41 import club.wpia.gigi.dbObjects.Contract.ContractType;
42 import club.wpia.gigi.dbObjects.Country;
43 import club.wpia.gigi.dbObjects.Digest;
44 import club.wpia.gigi.dbObjects.Domain;
45 import club.wpia.gigi.dbObjects.DomainPingConfiguration;
46 import club.wpia.gigi.dbObjects.DomainPingExecution;
47 import club.wpia.gigi.dbObjects.DomainPingType;
48 import club.wpia.gigi.dbObjects.EmailAddress;
49 import club.wpia.gigi.dbObjects.Group;
50 import club.wpia.gigi.dbObjects.Name;
51 import club.wpia.gigi.dbObjects.NamePart;
52 import club.wpia.gigi.dbObjects.NamePart.NamePartType;
53 import club.wpia.gigi.dbObjects.User;
54 import club.wpia.gigi.dbObjects.Verification.VerificationType;
55 import club.wpia.gigi.email.DelegateMailProvider;
56 import club.wpia.gigi.email.EmailProvider;
57 import club.wpia.gigi.localisation.Language;
58 import club.wpia.gigi.output.template.IterableDataset;
59 import club.wpia.gigi.output.template.Template;
60 import club.wpia.gigi.pages.account.certs.CertificateRequest;
61 import club.wpia.gigi.ping.DomainPinger;
62 import club.wpia.gigi.ping.PingerDaemon;
63 import club.wpia.gigi.util.AuthorizationContext;
64 import club.wpia.gigi.util.DayDate;
65 import club.wpia.gigi.util.DomainAssessment;
66 import club.wpia.gigi.util.HTMLEncoder;
67 import club.wpia.gigi.util.Notary;
68 import club.wpia.gigi.util.TimeConditions;
69 import sun.security.x509.X509Key;
70
71 public class Manager extends Page {
72
73     public static String validVerificationDateString() {
74         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
75         Calendar c = Calendar.getInstance();
76         c.setTimeInMillis(System.currentTimeMillis());
77         c.add(Calendar.MONTH, -Notary.LIMIT_MAX_MONTHS_VERIFICATION + 1);
78         return sdf.format(new Date(c.getTimeInMillis()));
79     }
80
81     public static Country getRandomCountry() {
82         List<Country> cc = Country.getCountries();
83         int rnd = new Random().nextInt(cc.size());
84         return cc.get(rnd);
85     }
86
87     public static final String PATH = "/manager";
88
89     private static HashMap<DomainPingType, DomainPinger> dps;
90
91     private Manager() {
92         super("Test Manager");
93
94         try {
95             Field gigiInstance = Gigi.class.getDeclaredField("instance");
96             gigiInstance.setAccessible(true);
97             Gigi g = (Gigi) gigiInstance.get(null);
98
99             Field gigiPinger = Gigi.class.getDeclaredField("pinger");
100             gigiPinger.setAccessible(true);
101             PingerDaemon pd = (PingerDaemon) gigiPinger.get(g);
102
103             Field f = PingerDaemon.class.getDeclaredField("pingers");
104             f.setAccessible(true);
105             dps = (HashMap<DomainPingType, DomainPinger>) f.get(pd);
106             HashMap<DomainPingType, DomainPinger> pingers = new HashMap<>();
107             for (DomainPingType dpt : DomainPingType.values()) {
108                 pingers.put(dpt, new PingerFetcher(dpt));
109             }
110             f.set(pd, pingers);
111         } catch (ReflectiveOperationException e) {
112             e.printStackTrace();
113         }
114     }
115
116     public User getSupporter() {
117         if (supporter != null) {
118             return supporter;
119         }
120         try {
121             User u = createAgent( -1);
122             if ( !u.isInGroup(Group.SUPPORTER)) {
123                 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
124                     ps.setInt(1, u.getId());
125                     ps.setString(2, Group.SUPPORTER.getDBName());
126                     ps.setInt(3, u.getId());
127                     ps.execute();
128                 }
129                 u.refreshGroups();
130             }
131             supporter = u;
132         } catch (ReflectiveOperationException | GigiApiException e) {
133             e.printStackTrace();
134         }
135         return supporter;
136     }
137
138     public User getAgent(int i) {
139         if (agents[i] != null) {
140             return agents[i];
141         }
142         try {
143             User u = createAgent(i);
144             agents[i] = u;
145
146         } catch (ReflectiveOperationException | GigiApiException e) {
147             e.printStackTrace();
148         }
149         return agents[i];
150     }
151
152     private User createAgent(int i) throws GigiApiException, IllegalAccessException {
153         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?, `country`=?")) {
154             String mail = "test-agent" + i + "@example.com";
155             User u = User.getByEmail(mail);
156             if (u == null) {
157                 System.out.println("Creating RA-Agent");
158                 createUser(mail);
159                 u = User.getByEmail(mail);
160                 passCATS(u, CATSType.AGENT_CHALLENGE);
161                 ps.setInt(1, u.getId());
162                 ps.setInt(2, u.getPreferredName().getId());
163                 ps.setInt(3, 100);
164                 ps.setString(4, "Manager init code");
165                 ps.setString(5, "1990-01-01");
166                 ps.setString(6, getRandomCountry().getCode());
167                 ps.execute();
168             }
169             if ( !Contract.hasSignedContract(u, ContractType.RA_AGENT_CONTRACT)) {
170                 new Contract(u, ContractType.RA_AGENT_CONTRACT);
171             }
172             return u;
173         }
174     }
175
176     private void passCATS(User u, CATSType t) {
177         CATS.enterResult(u, t, new Date(System.currentTimeMillis()), "en_EN", "1");
178     }
179
180     private void expireCATS(User u, CATSType t) {
181         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `cats_passed` SET `pass_date`=? WHERE `user_id`=? AND `variant_id`=? AND `pass_date`>?")) {
182             ps.setTimestamp(1, new Timestamp(System.currentTimeMillis() - DayDate.MILLI_DAY * 367));
183             ps.setInt(2, u.getId());
184             ps.setInt(3, t.getId());
185             ps.setTimestamp(4, new Timestamp(System.currentTimeMillis() - DayDate.MILLI_DAY * 366));
186             ps.execute();
187             ps.close();
188         }
189     }
190
191     private static Manager instance;
192
193     private static final Template t = new Template(Manager.class.getResource("ManagerMails.templ"));
194
195     HashMap<String, LinkedList<String>> emails = new HashMap<>();
196
197     private static TreeSet<String> pingExempt = new TreeSet<>();
198
199     public static Manager getInstance() {
200         if (instance == null) {
201             instance = new Manager();
202         }
203         return instance;
204     }
205
206     public static class MailFetcher extends DelegateMailProvider {
207
208         Pattern[] toForward;
209
210         public MailFetcher(Properties props) {
211             super(props, props.getProperty("emailProvider.manager.target"));
212             String str = props.getProperty("emailProvider.manager.filter");
213             if (str == null) {
214                 toForward = new Pattern[0];
215             } else {
216                 String[] parts = str.split(" ");
217                 toForward = new Pattern[parts.length];
218                 for (int i = 0; i < parts.length; i++) {
219                     toForward[i] = Pattern.compile(parts[i]);
220                 }
221             }
222         }
223
224         @Override
225         public String checkEmailServer(int forUid, String address) throws IOException {
226             return OK;
227         }
228
229         @Override
230         public synchronized void sendMail(String to, String subject, String message, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException {
231             HashMap<String, LinkedList<String>> mails = Manager.getInstance().emails;
232             LinkedList<String> hismails = mails.get(to);
233             if (hismails == null) {
234                 mails.put(to, hismails = new LinkedList<>());
235             }
236             hismails.addFirst(subject + "\n" + message);
237             for (int i = 0; i < toForward.length; i++) {
238                 if (toForward[i].matcher(to).matches()) {
239                     super.sendMail(to, subject, message, replyto, toname, fromname, errorsto, extra);
240                     return;
241                 }
242             }
243         }
244
245     }
246
247     public class PingerFetcher extends DomainPinger {
248
249         private DomainPingType dpt;
250
251         public PingerFetcher(DomainPingType dpt) {
252             this.dpt = dpt;
253         }
254
255         @Override
256         public DomainPingExecution ping(Domain domain, String configuration, CertificateOwner target, DomainPingConfiguration conf) {
257             System.err.println("TestManager: " + domain.getSuffix());
258             if (pingExempt.contains(domain.getSuffix())) {
259                 return enterPingResult(conf, DomainPinger.PING_SUCCEDED, "Succeeded by TestManager pass-by", null);
260             } else {
261                 DomainPinger pinger = dps.get(dpt);
262                 System.err.println("Forward to old pinger: " + pinger);
263                 return pinger.ping(domain, configuration, target, conf);
264             }
265         }
266
267     }
268
269     public void batchCreateUsers(String mailPrefix, String domain, int amount, PrintWriter out) {
270
271         try {
272             if (amount > 100) {
273                 out.print("100 at most, please.");
274                 return;
275             }
276             for (int i = 0; i < amount; i++) {
277                 String email = mailPrefix + i + "@" + domain;
278                 createUser(email);
279             }
280         } catch (ReflectiveOperationException e) {
281             out.println("failed");
282             e.printStackTrace();
283         } catch (GigiApiException e) {
284             out.println("failed: " + e.getMessage());
285             e.printStackTrace();
286         }
287     }
288
289     private void createUser(String email) throws GigiApiException, IllegalAccessException {
290         Calendar gc = GregorianCalendar.getInstance();
291         gc.setTimeInMillis(0);
292         gc.set(1990, 0, 1);
293
294         Country country = getRandomCountry();
295
296         User u = new User(email, "xvXV12°§", new DayDate(gc.getTime().getTime()), Locale.ENGLISH, country, //
297                 new NamePart(NamePartType.FIRST_NAME, "Först"), new NamePart(NamePartType.FIRST_NAME, "Müddle"), //
298                 new NamePart(NamePartType.LAST_NAME, "Läst"), new NamePart(NamePartType.SUFFIX, "Süffix"));
299         EmailAddress ea = u.getEmails()[0];
300         verify(email, ea);
301     }
302
303     private void verify(String email, EmailAddress ea) throws GigiApiException {
304         LinkedList<String> i = emails.get(email);
305         while (i.size() > 0 && !ea.isVerified()) {
306             String lst = i.getLast();
307             Pattern p = Pattern.compile("hash=([a-zA-Z0-9]+)");
308             Matcher m = p.matcher(lst);
309             if (m.find()) {
310                 ea.verify(m.group(1));
311             }
312             i.removeLast();
313         }
314         // ea.verify(hash);
315     }
316
317     User[] agents = new User[25];
318
319     User supporter;
320
321     @Override
322     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
323         AuthorizationContext sessionAc = (AuthorizationContext) req.getSession().getAttribute(Gigi.AUTH_CONTEXT);
324         if (req.getParameter("create") != null) {
325             String prefix = req.getParameter("prefix");
326             String domain = req.getParameter("suffix");
327             try {
328                 if (null == prefix) {
329                     throw new GigiApiException("No prefix given.");
330                 }
331                 if (null == domain) {
332                     throw new GigiApiException("No domain given.");
333                 }
334
335                 DomainAssessment.checkCertifiableDomain(domain, false, true);
336
337                 if ( !EmailProvider.isValidMailAddress(prefix + "@" + domain)) {
338                     throw new GigiApiException("Invalid email address template.");
339                 }
340
341                 batchCreateUsers(prefix, domain, Integer.parseInt(req.getParameter("amount")), resp.getWriter());
342                 resp.getWriter().println("User batch created.");
343             } catch (GigiApiException e) {
344                 throw new Error(e);
345             }
346         } else if (req.getParameter("addpriv") != null || req.getParameter("delpriv") != null) {
347             User userByEmail = User.getByEmail(req.getParameter("email"));
348             if (userByEmail == null) {
349                 resp.getWriter().println("User not found.");
350                 return;
351             }
352             try {
353                 if (req.getParameter("addpriv") != null) {
354                     userByEmail.grantGroup(getSupporter(), Group.getByString(req.getParameter("priv")));
355                     resp.getWriter().println("Privilege granted");
356                 } else {
357                     userByEmail.revokeGroup(getSupporter(), Group.getByString(req.getParameter("priv")));
358                     resp.getWriter().println("Privilege revoked");
359                 }
360             } catch (GigiApiException e) {
361                 throw new Error(e);
362             }
363         } else if (req.getParameter("fetch") != null) {
364             String mail = req.getParameter("femail");
365             fetchMails(req, resp, mail);
366         } else if (req.getParameter("cats") != null) {
367             String mail = req.getParameter("catsEmail");
368             String catsTypeId = req.getParameter("catsType");
369             User byEmail = User.getByEmail(mail);
370             if (byEmail == null) {
371                 resp.getWriter().println("User not found.");
372                 return;
373             }
374             if (catsTypeId == null) {
375                 resp.getWriter().println("No test given.");
376                 return;
377             }
378             CATSType test = null;
379             try {
380                 test = CATSType.values()[Integer.parseInt(catsTypeId)];
381             } catch (NumberFormatException e) {
382                 resp.getWriter().println("No valid integer given.");
383                 return;
384             }
385             passCATS(byEmail, test);
386             resp.getWriter().println("Test '" + test.getDisplayName() + "' was added to user account.");
387         } else if (req.getParameter("catsexpire") != null) {
388             String mail = req.getParameter("catsEmail");
389             String catsTypeId = req.getParameter("catsType");
390             User userByEmail = User.getByEmail(mail);
391             if (userByEmail == null) {
392                 resp.getWriter().println("User not found.");
393                 return;
394             }
395             if (catsTypeId == null) {
396                 resp.getWriter().println("No test given.");
397                 return;
398             }
399             CATSType test = null;
400             try {
401                 test = CATSType.values()[Integer.parseInt(catsTypeId)];
402             } catch (NumberFormatException e) {
403                 resp.getWriter().println("No valid integer given.");
404                 return;
405             }
406             expireCATS(userByEmail, test);
407             resp.getWriter().println("Test '" + test.getDisplayName() + "' is set expired for user account.");
408         } else if (req.getParameter("verify") != null) {
409             String mail = req.getParameter("verifyEmail");
410             String verificationPoints = req.getParameter("verificationPoints");
411             User userByEmail = User.getByEmail(mail);
412
413             if (userByEmail == null) {
414                 resp.getWriter().println("User not found.");
415                 return;
416             }
417
418             int vp = 0;
419             int verifications = 0;
420             String info = "";
421
422             try {
423                 try {
424                     vp = Integer.parseInt(verificationPoints);
425                 } catch (NumberFormatException e) {
426                     resp.getWriter().println("The value for Verification Points must be an integer.</br>");
427                     vp = 0;
428                 }
429
430                 int agentNumber = addVerificationPoints(vp, userByEmail);
431
432                 while (vp > 0) {
433                     int currentVP = 10;
434                     if (vp < 10) {
435                         currentVP = vp;
436                     }
437                     if (Notary.checkVerificationIsPossible(getAgent(agentNumber), userByEmail.getPreferredName())) {
438
439                         Notary.verify(getAgent(agentNumber), userByEmail, userByEmail.getPreferredName(), userByEmail.getDoB(), currentVP, "Testmanager Verify up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
440                         vp -= currentVP;
441                         verifications += 1;
442
443                     }
444                     agentNumber += 1;
445                     if (agentNumber >= agents.length) {
446                         info = "<br/>The limit of agents is reached. You cannot add any more Verification Points to the preferred name of this user using this method.";
447                         break;
448                     }
449                 }
450
451             } catch (GigiApiException e) {
452                 throw new Error(e);
453             }
454
455             resp.getWriter().println("User has been verified " + verifications + " times." + info);
456
457         } else if (req.getParameter("verifyexpire") != null) {
458             String mail = req.getParameter("verifyEmail");
459             User byEmail = User.getByEmail(mail);
460             if (byEmail == null) {
461                 resp.getWriter().println("User not found.");
462                 return;
463             } else {
464                 setVerificationDateToPast(byEmail.getPreferredName());
465             }
466
467             resp.getWriter().println("Verification set to time past the limit.");
468         } else if (req.getParameter("letverify") != null) {
469             String mail = req.getParameter("letverifyEmail");
470             User userByEmail = User.getByEmail(mail);
471             if (userByEmail == null || !userByEmail.canVerify()) {
472                 resp.getWriter().println("User not found, or found user is not allowed to verify.");
473             } else {
474                 try {
475                     for (int i = 0; i < 25; i++) {
476                         User a = getAgent(i);
477                         Notary.verify(userByEmail, a, a.getNames()[0], a.getDoB(), 10, "Testmanager exp up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
478                     }
479                     resp.getWriter().println("Successfully added experience points.");
480                 } catch (GigiApiException e) {
481                     throw new Error(e);
482                 }
483             }
484         } else if (req.getParameter("addEmail") != null) {
485             User userByEmail = User.getByEmail(req.getParameter("addEmailEmail"));
486             try {
487                 EmailAddress ea = new EmailAddress(userByEmail, req.getParameter("addEmailNew"), Locale.ENGLISH);
488                 verify(ea.getAddress(), ea);
489             } catch (IllegalArgumentException e) {
490                 e.printStackTrace();
491                 resp.getWriter().println("An internal error occured.");
492             } catch (GigiApiException e) {
493                 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH), getDefaultVars(req));
494             }
495         } else if (req.getParameter("addCert") != null) {
496             User userByEmail = User.getByEmail(req.getParameter("addCertEmail"));
497             try {
498                 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
499                 kpg.initialize(4096);
500                 KeyPair kp = kpg.generateKeyPair();
501                 SPKAC s = new SPKAC((X509Key) kp.getPublic(), "challenge");
502                 Signature sign = Signature.getInstance("SHA512withRSA");
503                 sign.initSign(kp.getPrivate());
504
505                 byte[] res = s.getEncoded(sign);
506
507                 CertificateRequest cr = new CertificateRequest(new AuthorizationContext(userByEmail, userByEmail, sessionAc.isStronglyAuthenticated()), Base64.getEncoder().encodeToString(res), "challenge");
508                 cr.update(CertificateRequest.DEFAULT_CN, Digest.SHA512.toString(), "client", null, "", "email:" + userByEmail.getEmail());
509                 Certificate draft = cr.draft();
510                 draft.issue(null, "2y", userByEmail).waitFor(10000);
511                 if (draft.getStatus() == CertificateStatus.ISSUED) {
512                     resp.getWriter().println("added certificate");
513                 } else {
514                     resp.getWriter().println("signer failed");
515                 }
516             } catch (GeneralSecurityException e1) {
517                 e1.printStackTrace();
518                 resp.getWriter().println("error");
519             } catch (GigiApiException e) {
520                 e.format(resp.getWriter(), Language.getInstance(Locale.ENGLISH), getDefaultVars(req));
521             }
522
523         } else if (req.getParameter("addExDom") != null) {
524             String dom = req.getParameter("exemptDom");
525             pingExempt.add(dom);
526             resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
527             resp.getWriter().println(HTMLEncoder.encodeHTML(pingExempt.toString()));
528         } else if (req.getParameter("delExDom") != null) {
529             String dom = req.getParameter("exemptDom");
530             pingExempt.remove(dom);
531             resp.getWriter().println("Updated domains exempt from pings. Current set: <br/>");
532             resp.getWriter().println(HTMLEncoder.encodeHTML(pingExempt.toString()));
533         } else if (req.getParameter("makeAgent") != null) {
534             User userByEmail = User.getByEmail(req.getParameter("agentEmail"));
535             if (userByEmail == null) {
536                 resp.getWriter().println("User not found, or found user is not allowed to verify.");
537             } else {
538                 if (userByEmail.getVerificationPoints() < 100) {
539                     addVerificationPoints(100, userByEmail);
540                 }
541                 if ( !userByEmail.hasPassedCATS()) {
542                     passCATS(userByEmail, CATSType.AGENT_CHALLENGE);
543                 }
544                 if ( !Contract.hasSignedContract(userByEmail, Contract.ContractType.RA_AGENT_CONTRACT)) {
545                     try {
546                         new Contract(userByEmail, Contract.ContractType.RA_AGENT_CONTRACT);
547                     } catch (GigiApiException e) {
548                         throw new Error(e);
549                     }
550                 }
551                 resp.getWriter().println("User has all requirements to be an RA Agent");
552             }
553         }
554         resp.getWriter().println("<br/><a href='" + PATH + "'>Go back</a>");
555     }
556
557     private int addVerificationPoints(int vp, User byEmail) throws Error {
558         int agentNumber = 0;
559
560         try {
561             if (vp > 100) { // only allow max 100 Verification points
562                 vp = 100;
563             }
564
565             while (vp > 0) {
566                 int currentVP = 10;
567                 if (vp < 10) {
568                     currentVP = vp;
569                 }
570                 Notary.verify(getAgent(agentNumber), byEmail, byEmail.getPreferredName(), byEmail.getDoB(), currentVP, "Testmanager Verify up code", validVerificationDateString(), VerificationType.FACE_TO_FACE, getRandomCountry());
571                 agentNumber += 1;
572                 vp -= currentVP;
573             }
574
575         } catch (GigiApiException e) {
576             throw new Error(e);
577         }
578         return agentNumber;
579     }
580
581     private void fetchMails(HttpServletRequest req, HttpServletResponse resp, String mail) throws IOException {
582         final LinkedList<String> mails = emails.get(mail);
583         HashMap<String, Object> vars = new HashMap<>();
584         vars.put("mail", mail);
585         if (mails != null) {
586             vars.put("mails", new IterableDataset() {
587
588                 Iterator<String> s = mails.iterator();
589
590                 @Override
591                 public boolean next(Language l, Map<String, Object> vars) {
592                     if ( !s.hasNext()) {
593                         return false;
594                     }
595                     vars.put("body", s.next().replaceAll("(https?://\\S+)", "<a href=\"$1\">$1</a>"));
596                     return true;
597                 }
598             });
599         }
600         t.output(resp.getWriter(), getLanguage(req), vars);
601         if (mails == null) {
602             resp.getWriter().println("No mails");
603
604         }
605     }
606
607     private static final Template form = new Template(Manager.class.getResource("Manager.templ"));
608
609     @Override
610     public boolean needsLogin() {
611         return false;
612     }
613
614     @Override
615     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
616         String pi = req.getPathInfo().substring(PATH.length());
617         if (pi.length() > 1 && pi.startsWith("/fetch-")) {
618             String mail = pi.substring(pi.indexOf('-', 2) + 1);
619             fetchMails(req, resp, mail);
620             return;
621         }
622         HashMap<String, Object> vars = new HashMap<>();
623         vars.put("cats_types", new IterableDataset() {
624
625             CATSType[] type = CATSType.values();
626
627             int i = 0;
628
629             @Override
630             public boolean next(Language l, Map<String, Object> vars) {
631                 if (i >= type.length) {
632                     return false;
633                 }
634                 CATSType t = type[i++];
635                 vars.put("id", i - 1);
636                 vars.put("name", t.getDisplayName());
637                 return true;
638             }
639         });
640
641         vars.put("testValidMonths", TimeConditions.getInstance().getTestMonths());
642         vars.put("reverificationDays", TimeConditions.getInstance().getVerificationLimitDays());
643         vars.put("verificationFreshMonths", TimeConditions.getInstance().getVerificationMonths());
644         vars.put("verificationMaxAgeMonths", TimeConditions.getInstance().getVerificationMaxAgeMonths());
645         vars.put("emailPingMonths", TimeConditions.getInstance().getEmailPingMonths());
646
647         form.output(resp.getWriter(), getLanguage(req), vars);
648     }
649
650     private static void setVerificationDateToPast(Name name) {
651         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
652         Calendar c = Calendar.getInstance();
653         c.setTimeInMillis(System.currentTimeMillis());
654         c.add(Calendar.MONTH, -TimeConditions.getInstance().getVerificationMonths());
655         String date = sdf.format(new Date(c.getTimeInMillis()));
656         GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `notary` SET `date`=? WHERE `to`=? AND `date`>?");
657         ps.setString(1, date);
658         ps.setInt(2, name.getId());
659         ps.setString(3, date);
660         ps.execute();
661         ps.close();
662     }
663 }