]> WPIA git - gigi.git/blob - src/club/wpia/gigi/dbObjects/User.java
add: user client certificate must have a verification within <=24 months
[gigi.git] / src / club / wpia / gigi / dbObjects / User.java
1 package club.wpia.gigi.dbObjects;
2
3 import java.io.IOException;
4 import java.io.ObjectInputStream;
5 import java.io.ObjectOutputStream;
6 import java.util.ArrayList;
7 import java.util.Collections;
8 import java.util.HashSet;
9 import java.util.LinkedList;
10 import java.util.List;
11 import java.util.Locale;
12 import java.util.Set;
13 import java.util.TreeSet;
14
15 import club.wpia.gigi.Gigi;
16 import club.wpia.gigi.GigiApiException;
17 import club.wpia.gigi.database.GigiPreparedStatement;
18 import club.wpia.gigi.database.GigiResultSet;
19 import club.wpia.gigi.dbObjects.CATS.CATSType;
20 import club.wpia.gigi.dbObjects.Country.CountryCodeType;
21 import club.wpia.gigi.dbObjects.Verification.VerificationType;
22 import club.wpia.gigi.email.EmailProvider;
23 import club.wpia.gigi.localisation.Language;
24 import club.wpia.gigi.output.DateSelector;
25 import club.wpia.gigi.pages.PasswordResetPage;
26 import club.wpia.gigi.util.CalendarUtil;
27 import club.wpia.gigi.util.DayDate;
28 import club.wpia.gigi.util.Notary;
29 import club.wpia.gigi.util.PasswordHash;
30 import club.wpia.gigi.util.TimeConditions;
31
32 /**
33  * Represents an acting, verifiable user. Synchronizing on user means: no
34  * name-change and no verification.
35  */
36 public class User extends CertificateOwner {
37
38     private static final long serialVersionUID = -7915843843752264176L;
39
40     private DayDate dob;
41
42     private String email;
43
44     private Verification[] receivedVerifications;
45
46     private Verification[] madeVerifications;
47
48     private Locale locale;
49
50     private Set<Group> groups = new HashSet<>();
51
52     public static final int MINIMUM_AGE = 16;
53
54     public static final int MAXIMUM_PLAUSIBLE_AGE = 120;
55
56     public static final int POJAM_AGE = 14;
57
58     public static final int ADULT_AGE = 18;
59
60     public static final boolean POJAM_ENABLED = false;
61
62     public static final int EXPERIENCE_POINTS = 4;
63
64     /**
65      * Time in months a verification is considered "recent".
66      */
67     public static final int VERIFICATION_MONTHS = TimeConditions.getInstance().getVerificationMonths();
68
69     private Name preferredName;
70
71     private Country residenceCountry;
72
73     protected User(GigiResultSet rs) throws GigiApiException {
74         super(rs.getInt("id"));
75
76         dob = new DayDate(rs.getDate("dob"));
77         email = rs.getString("email");
78         preferredName = Name.getById(rs.getInt("preferredName"));
79
80         if (rs.getString("country") != null) {
81             residenceCountry = Country.getCountryByCode(rs.getString("Country"), Country.CountryCodeType.CODE_2_CHARS);
82         }
83
84         String localeStr = rs.getString("language");
85         if (localeStr == null || localeStr.equals("")) {
86             locale = Locale.getDefault();
87         } else {
88             locale = Language.getLocaleFromString(localeStr);
89         }
90
91         refreshGroups();
92     }
93
94     public synchronized void refreshGroups() {
95         HashSet<Group> hs = new HashSet<>();
96         try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
97             psg.setInt(1, getId());
98
99             try (GigiResultSet rs2 = psg.executeQuery()) {
100                 while (rs2.next()) {
101                     hs.add(Group.getByString(rs2.getString(1)));
102                 }
103             }
104         }
105         groups = hs;
106     }
107
108     public User(String email, String password, DayDate dob, Locale locale, Country residenceCountry, NamePart... preferred) throws GigiApiException {
109         super(validate(email));
110
111         this.email = email;
112         this.dob = dob;
113         this.locale = locale;
114         this.preferredName = new Name(this, preferred);
115         try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?, `country` = ?")) {
116             query.setString(1, email);
117             query.setString(2, PasswordHash.hash(password));
118             query.setDate(3, dob.toSQLDate());
119             query.setString(4, locale.toString());
120             query.setInt(5, getId());
121             query.setInt(6, preferredName.getId());
122             query.setString(7, residenceCountry == null ? null : residenceCountry.getCode());
123             query.execute();
124         }
125
126         new EmailAddress(this, email, locale);
127     }
128
129     private static Void validate(String email) {
130         // Avoid storing information that obviously won't get through
131         if ( !EmailProvider.isValidMailAddress(email)) {
132             throw new IllegalArgumentException("Invalid email.");
133         }
134         return null;
135     }
136
137     public Name[] getNames() {
138         try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
139             gps.setInt(1, getId());
140             return fetchNamesToArray(gps);
141         }
142     }
143
144     public Name[] getNonDeprecatedNames() {
145         try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL AND `deprecated` IS NULL", true)) {
146             gps.setInt(1, getId());
147             return fetchNamesToArray(gps);
148         }
149     }
150
151     private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
152         GigiResultSet rs = gps.executeQuery();
153         rs.last();
154         Name[] dt = new Name[rs.getRow()];
155         rs.beforeFirst();
156         for (int i = 0; rs.next(); i++) {
157             dt[i] = Name.getById(rs.getInt(1));
158         }
159         return dt;
160     }
161
162     public DayDate getDoB() {
163         return dob;
164     }
165
166     public void setDoB(DayDate dob) throws GigiApiException {
167         synchronized (Notary.class) {
168             if (getReceivedVerifications().length != 0) {
169                 throw new GigiApiException("No change after verification allowed.");
170             }
171
172             if ( !CalendarUtil.isOfAge(dob, User.MINIMUM_AGE)) {
173                 throw new GigiApiException("Entered date of birth is below the restricted age requirements.");
174             }
175
176             if (CalendarUtil.isYearsInFuture(dob.end(), User.MAXIMUM_PLAUSIBLE_AGE)) {
177                 throw new GigiApiException("Entered date of birth exceeds the maximum age set in our policies. Please check your DoB is correct and contact support if the issue persists.");
178             }
179             this.dob = dob;
180             rawUpdateUserData();
181         }
182
183     }
184
185     protected void setDoBAsSupport(DayDate dob) throws GigiApiException {
186         synchronized (Notary.class) {
187             this.dob = dob;
188             rawUpdateUserData();
189         }
190
191     }
192
193     public String getEmail() {
194         return email;
195     }
196
197     public void changePassword(String oldPass, String newPass) throws GigiApiException {
198         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
199             ps.setInt(1, getId());
200             try (GigiResultSet rs = ps.executeQuery()) {
201                 if ( !rs.next()) {
202                     throw new GigiApiException("User not found... very bad.");
203                 }
204                 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
205                     throw new GigiApiException("Old password does not match.");
206                 }
207             }
208         }
209         setPassword(newPass);
210     }
211
212     public void setPassword(String newPass) throws GigiApiException {
213         Name[] names = getNames();
214         TreeSet<String> nameParts = new TreeSet<>();
215         for (int i = 0; i < names.length; i++) {
216             for (NamePart string : names[i].getParts()) {
217                 nameParts.add(string.getValue());
218             }
219         }
220         GigiApiException gaPassword = Gigi.getPasswordChecker().checkPassword(newPass, nameParts.toArray(new String[nameParts.size()]), getEmail());
221         if (gaPassword != null) {
222             throw gaPassword;
223         }
224         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
225             ps.setString(1, PasswordHash.hash(newPass));
226             ps.setInt(2, getId());
227             ps.executeUpdate();
228         }
229     }
230
231     public boolean canVerify() {
232         if (POJAM_ENABLED) {
233             if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
234                 return false;
235             }
236         } else {
237             if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
238                 return false;
239             }
240         }
241         if (getVerificationPoints() < 100) {
242             return false;
243         }
244
245         if ( !Contract.hasSignedContract(this, Contract.ContractType.RA_AGENT_CONTRACT)) {
246             return false;
247         }
248
249         return hasPassedCATS();
250
251     }
252
253     public boolean hasPassedCATS() {
254         try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
255             query.setInt(1, getId());
256             query.setInt(2, CATSType.AGENT_CHALLENGE.getId());
257             try (GigiResultSet rs = query.executeQuery()) {
258                 if (rs.next()) {
259                     return true;
260                 } else {
261                     return false;
262                 }
263             }
264         }
265     }
266
267     public int getVerificationPoints() {
268         try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT SUM(lastpoints) FROM ( SELECT DISTINCT ON (`from`, `method`) `from`, `points` as lastpoints FROM `notary` INNER JOIN `names` ON `names`.`id`=`to` WHERE `notary`.`deleted` is NULL AND (`expire` IS NULL OR `expire` > CURRENT_TIMESTAMP) AND `names`.`uid` = ? ORDER BY `from`, `method`, `when` DESC) as p")) {
269             query.setInt(1, getId());
270
271             GigiResultSet rs = query.executeQuery();
272             int points = 0;
273
274             if (rs.next()) {
275                 points = rs.getInt(1);
276             }
277
278             return points;
279         }
280     }
281
282     public int getExperiencePoints() {
283         try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT count(*) FROM ( SELECT `names`.`uid` FROM `notary` INNER JOIN `names` ON `names`.`id` = `to` WHERE `from`=? AND `notary`.`deleted` IS NULL AND `method` = ? ::`notaryType` GROUP BY `names`.`uid`) as p")) {
284             query.setInt(1, getId());
285             query.setEnum(2, VerificationType.FACE_TO_FACE);
286
287             GigiResultSet rs = query.executeQuery();
288             int points = 0;
289
290             if (rs.next()) {
291                 points = rs.getInt(1) * EXPERIENCE_POINTS;
292             }
293
294             return points;
295         }
296     }
297
298     /**
299      * Gets the maximum allowed points NOW. Note that a verification needs to
300      * re-check PoJam as it has taken place in the past.
301      * 
302      * @return the maximal points @
303      */
304     @SuppressWarnings("unused")
305     public int getMaxVerifyPoints() {
306         if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
307             return 10; // PoJAM
308         }
309
310         int exp = getExperiencePoints();
311         int points = 10;
312
313         if (exp >= 5 * EXPERIENCE_POINTS) {
314             points += 5;
315         }
316         if (exp >= 10 * EXPERIENCE_POINTS) {
317             points += 5;
318         }
319         if (exp >= 15 * EXPERIENCE_POINTS) {
320             points += 5;
321         }
322         if (exp >= 20 * EXPERIENCE_POINTS) {
323             points += 5;
324         }
325         if (exp >= 25 * EXPERIENCE_POINTS) {
326             points += 5;
327         }
328
329         return points;
330     }
331
332     public boolean isValidName(String name) {
333         for (Name n : getNames()) {
334             if (n.matches(name) && n.getVerificationPoints() >= 50) {
335                 return true;
336             }
337         }
338         return false;
339     }
340
341     public boolean isValidNameVerification(String name) {
342         for (Name n : getNames()) {
343             if (n.matches(name) && n.isValidVerification()) {
344                 return true;
345             }
346         }
347         return false;
348     }
349
350     public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
351         for (EmailAddress email : getEmails()) {
352             if (email.getAddress().equals(newMail.getAddress())) {
353                 if ( !email.isVerified()) {
354                     throw new GigiApiException("Email not verified.");
355                 }
356
357                 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
358                     ps.setString(1, newMail.getAddress());
359                     ps.setInt(2, getId());
360                     ps.execute();
361                 }
362
363                 this.email = newMail.getAddress();
364                 return;
365             }
366         }
367
368         throw new GigiApiException("Given address not an address of the user.");
369     }
370
371     public void deleteEmail(EmailAddress delMail) throws GigiApiException {
372         if (getEmail().equals(delMail.getAddress())) {
373             throw new GigiApiException("Can't delete user's default e-mail.");
374         }
375
376         for (EmailAddress email : getEmails()) {
377             if (email.getId() == delMail.getId()) {
378                 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
379                     ps.setInt(1, delMail.getId());
380                     ps.execute();
381                 }
382                 return;
383             }
384         }
385         throw new GigiApiException("Email not one of user's email addresses.");
386     }
387
388     public synchronized Verification[] getReceivedVerifications() {
389         if (receivedVerifications == null) {
390             try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` INNER JOIN `names` ON `names`.`id` = `notary`.`to` WHERE `names`.`uid`=? AND `notary`.`deleted` IS NULL ORDER BY `when` DESC")) {
391                 query.setInt(1, getId());
392
393                 GigiResultSet res = query.executeQuery();
394                 List<Verification> verifications = new LinkedList<Verification>();
395
396                 while (res.next()) {
397                     verifications.add(verificationByRes(res));
398                 }
399
400                 this.receivedVerifications = verifications.toArray(new Verification[0]);
401             }
402         }
403
404         return receivedVerifications;
405     }
406
407     public synchronized Verification[] getMadeVerifications() {
408         if (madeVerifications == null) {
409             try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
410                 query.setInt(1, getId());
411
412                 try (GigiResultSet res = query.executeQuery()) {
413                     List<Verification> verifications = new LinkedList<Verification>();
414
415                     while (res.next()) {
416                         verifications.add(verificationByRes(res));
417                     }
418
419                     this.madeVerifications = verifications.toArray(new Verification[0]);
420                 }
421             }
422         }
423
424         return madeVerifications;
425     }
426
427     public synchronized void invalidateMadeVerifications() {
428         madeVerifications = null;
429     }
430
431     public synchronized void invalidateReceivedVerifications() {
432         receivedVerifications = null;
433     }
434
435     private void rawUpdateUserData() {
436         try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
437             update.setDate(1, getDoB().toSQLDate());
438             update.setInt(2, getId());
439             update.executeUpdate();
440         }
441     }
442
443     public Locale getPreferredLocale() {
444         return locale;
445     }
446
447     public void setPreferredLocale(Locale locale) {
448         this.locale = locale;
449
450     }
451
452     public synchronized Name getPreferredName() {
453         return preferredName;
454     }
455
456     public synchronized void setPreferredName(Name preferred) throws GigiApiException {
457         if (preferred.getOwner() != this) {
458             throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
459         }
460         this.preferredName = preferred;
461         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
462             ps.setInt(1, preferred.getId());
463             ps.setInt(2, getId());
464             ps.executeUpdate();
465         }
466
467     }
468
469     public synchronized String getInitials() {
470         return preferredName.toInitialsString();
471     }
472
473     public boolean isInGroup(Group g) {
474         return groups.contains(g);
475     }
476
477     public Set<Group> getGroups() {
478         return Collections.unmodifiableSet(groups);
479     }
480
481     public void grantGroup(User granter, Group toGrant) throws GigiApiException {
482         if (toGrant.isManagedBySupport() && !granter.isInGroup(Group.SUPPORTER)) {
483             throw new GigiApiException("Group may only be managed by supporter");
484         }
485         if (toGrant.isManagedBySupport() && granter == this) {
486             throw new GigiApiException("Group may only be managed by supporter that is not oneself");
487         }
488         groups.add(toGrant);
489         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
490             ps.setInt(1, getId());
491             ps.setEnum(2, toGrant);
492             ps.setInt(3, granter.getId());
493             ps.execute();
494         }
495     }
496
497     public void revokeGroup(User revoker, Group toRevoke) throws GigiApiException {
498         if (toRevoke.isManagedBySupport() && !revoker.isInGroup(Group.SUPPORTER)) {
499             throw new GigiApiException("Group may only be managed by supporter");
500         }
501         groups.remove(toRevoke);
502         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
503             ps.setInt(1, revoker.getId());
504             ps.setEnum(2, toRevoke);
505             ps.setInt(3, getId());
506             ps.execute();
507         }
508     }
509
510     public List<Organisation> getOrganisations() {
511         return getOrganisations(false);
512     }
513
514     public List<Organisation> getOrganisations(boolean isAdmin) {
515         List<Organisation> orgas = new ArrayList<>();
516         try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
517             query.setInt(1, getId());
518             try (GigiResultSet res = query.executeQuery()) {
519                 while (res.next()) {
520                     orgas.add(Organisation.getById(res.getInt(1)));
521                 }
522
523                 return orgas;
524             }
525         }
526     }
527
528     public static synchronized User getById(int id) {
529         CertificateOwner co = CertificateOwner.getById(id);
530         if (co instanceof User) {
531             return (User) co;
532         }
533
534         return null;
535     }
536
537     public static User getByEmail(String mail) {
538         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
539             ps.setString(1, mail);
540             GigiResultSet rs = ps.executeQuery();
541             if ( !rs.next()) {
542                 return null;
543             }
544
545             return User.getById(rs.getInt(1));
546         }
547     }
548
549     public static User[] findByEmail(String mail) {
550         LinkedList<User> results = new LinkedList<User>();
551         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `users`.`email` LIKE ? AND `deleted` IS NULL GROUP BY `users`.`id` LIMIT 100")) {
552             ps.setString(1, mail);
553             GigiResultSet rs = ps.executeQuery();
554             while (rs.next()) {
555                 results.add(User.getById(rs.getInt(1)));
556             }
557             return results.toArray(new User[results.size()]);
558         }
559     }
560
561     public EmailAddress[] getEmails() {
562         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
563             ps.setInt(1, getId());
564
565             GigiResultSet rs = ps.executeQuery();
566             LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
567
568             while (rs.next()) {
569                 data.add(EmailAddress.getById(rs.getInt(1)));
570             }
571
572             return data.toArray(new EmailAddress[0]);
573         }
574     }
575
576     @Override
577     public boolean isValidEmail(String email) {
578         for (EmailAddress em : getEmails()) {
579             if (em.getAddress().equals(email)) {
580                 return em.isVerified();
581             }
582         }
583
584         return false;
585     }
586
587     public String[] getTrainings() {
588         try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `pass_date`, `type_text`, `language`, `version` FROM `cats_passed` LEFT JOIN `cats_type` ON `cats_type`.`id`=`cats_passed`.`variant_id`  WHERE `user_id`=? ORDER BY `pass_date` DESC")) {
589             prep.setInt(1, getId());
590             GigiResultSet res = prep.executeQuery();
591             List<String> entries = new LinkedList<String>();
592
593             while (res.next()) {
594                 StringBuilder training = new StringBuilder();
595                 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
596                 training.append(" (");
597                 training.append(res.getString(2));
598                 if (res.getString(3).length() > 0) {
599                     training.append(" ");
600                     training.append(res.getString(3));
601                 }
602                 if (res.getString(4).length() > 0) {
603                     training.append(", ");
604                     training.append(res.getString(4));
605                 }
606                 training.append(")");
607                 entries.add(training.toString());
608             }
609
610             return entries.toArray(new String[0]);
611         }
612
613     }
614
615     public int generatePasswordResetTicket(User actor, String token, String privateToken) {
616         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
617             ps.setInt(1, getId());
618             ps.setInt(2, getId());
619             ps.setString(3, token);
620             ps.setString(4, PasswordHash.hash(privateToken));
621             ps.execute();
622             return ps.lastInsertId();
623         }
624     }
625
626     public static User getResetWithToken(int id, String token) {
627         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?::INTEGER")) {
628             ps.setInt(1, id);
629             ps.setString(2, token);
630             ps.setInt(3, PasswordResetPage.HOUR_MAX);
631             GigiResultSet res = ps.executeQuery();
632             if ( !res.next()) {
633                 return null;
634             }
635             return User.getById(res.getInt(1));
636         }
637     }
638
639     public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
640         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
641             ps.setInt(1, id);
642             ps.setInt(2, getId());
643             GigiResultSet rs = ps.executeQuery();
644             if ( !rs.next()) {
645                 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
646             }
647             if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
648                 throw new GigiApiException("Private token does not match.");
649             }
650             setPassword(newPassword);
651         }
652         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET  `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
653             ps.setInt(1, id);
654             ps.executeUpdate();
655         }
656     }
657
658     private Verification verificationByRes(GigiResultSet res) {
659         try {
660             return new Verification(res.getInt("id"), User.getById(res.getInt("from")), Name.getById(res.getInt("to")), res.getString("location"), res.getString("method"), res.getInt("points"), res.getString("date"), res.getString("country") == null ? null : Country.getCountryByCode(res.getString("country"), CountryCodeType.CODE_2_CHARS), res.getTimestamp("expire"));
661         } catch (GigiApiException e) {
662             throw new Error(e);
663         }
664     }
665
666     public boolean isInVerificationLimit() {
667         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT 1 FROM `notary` INNER JOIN `names` ON `names`.`id`=`to` WHERE `names`.`uid` = ? AND `when` > (now() - (interval '1 month' * ?::INTEGER)) AND (`expire` IS NULL OR `expire` > now()) AND `notary`.`deleted` IS NULL;")) {
668             ps.setInt(1, getId());
669             ps.setInt(2, VERIFICATION_MONTHS);
670
671             GigiResultSet rs = ps.executeQuery();
672             return rs.next();
673         }
674     }
675
676     private void writeObject(ObjectOutputStream oos) throws IOException {}
677
678     private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {}
679
680     public Country getResidenceCountry() {
681         return residenceCountry;
682     }
683
684     public void setResidenceCountry(Country residenceCountry) {
685         this.residenceCountry = residenceCountry;
686         rawUpdateCountryData();
687     }
688
689     private void rawUpdateCountryData() {
690         try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET country=? WHERE id=?")) {
691             update.setString(1, residenceCountry == null ? null : residenceCountry.getCode());
692             update.setInt(2, getId());
693             update.executeUpdate();
694         }
695     }
696
697     public boolean hasValidRAChallenge() {
698         return CATS.isInCatsLimit(getId(), CATSType.AGENT_CHALLENGE.getId());
699     }
700
701     public boolean hasValidSupportChallenge() {
702         return CATS.isInCatsLimit(getId(), CATSType.SUPPORT_DP_CHALLENGE_NAME.getId());
703     }
704
705     public boolean hasValidOrgAdminChallenge() {
706         return CATS.isInCatsLimit(getId(), CATSType.ORG_ADMIN_DP_CHALLENGE_NAME.getId());
707     }
708
709     public boolean hasValidOrgAgentChallenge() {
710         return CATS.isInCatsLimit(getId(), CATSType.ORG_AGENT_CHALLENGE.getId());
711     }
712
713     public boolean hasValidTTPAgentChallenge() {
714         return CATS.isInCatsLimit(getId(), CATSType.TTP_AGENT_CHALLENGE.getId());
715     }
716
717     public void writeUserLog(User actor, String type) throws GigiApiException {
718         try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `adminLog` SET uid=?, admin=?, type=?")) {
719             prep.setInt(1, actor.getId());
720             prep.setInt(2, getId());
721             prep.setString(3, type);
722             prep.executeUpdate();
723         }
724     }
725 }