]> WPIA git - gigi.git/blob - src/club/wpia/gigi/dbObjects/User.java
add: handling of RA Agent Contract
[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 void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
342         for (EmailAddress email : getEmails()) {
343             if (email.getAddress().equals(newMail.getAddress())) {
344                 if ( !email.isVerified()) {
345                     throw new GigiApiException("Email not verified.");
346                 }
347
348                 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
349                     ps.setString(1, newMail.getAddress());
350                     ps.setInt(2, getId());
351                     ps.execute();
352                 }
353
354                 this.email = newMail.getAddress();
355                 return;
356             }
357         }
358
359         throw new GigiApiException("Given address not an address of the user.");
360     }
361
362     public void deleteEmail(EmailAddress delMail) throws GigiApiException {
363         if (getEmail().equals(delMail.getAddress())) {
364             throw new GigiApiException("Can't delete user's default e-mail.");
365         }
366
367         for (EmailAddress email : getEmails()) {
368             if (email.getId() == delMail.getId()) {
369                 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
370                     ps.setInt(1, delMail.getId());
371                     ps.execute();
372                 }
373                 return;
374             }
375         }
376         throw new GigiApiException("Email not one of user's email addresses.");
377     }
378
379     public synchronized Verification[] getReceivedVerifications() {
380         if (receivedVerifications == null) {
381             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")) {
382                 query.setInt(1, getId());
383
384                 GigiResultSet res = query.executeQuery();
385                 List<Verification> verifications = new LinkedList<Verification>();
386
387                 while (res.next()) {
388                     verifications.add(verificationByRes(res));
389                 }
390
391                 this.receivedVerifications = verifications.toArray(new Verification[0]);
392             }
393         }
394
395         return receivedVerifications;
396     }
397
398     public synchronized Verification[] getMadeVerifications() {
399         if (madeVerifications == null) {
400             try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
401                 query.setInt(1, getId());
402
403                 try (GigiResultSet res = query.executeQuery()) {
404                     List<Verification> verifications = new LinkedList<Verification>();
405
406                     while (res.next()) {
407                         verifications.add(verificationByRes(res));
408                     }
409
410                     this.madeVerifications = verifications.toArray(new Verification[0]);
411                 }
412             }
413         }
414
415         return madeVerifications;
416     }
417
418     public synchronized void invalidateMadeVerifications() {
419         madeVerifications = null;
420     }
421
422     public synchronized void invalidateReceivedVerifications() {
423         receivedVerifications = null;
424     }
425
426     private void rawUpdateUserData() {
427         try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
428             update.setDate(1, getDoB().toSQLDate());
429             update.setInt(2, getId());
430             update.executeUpdate();
431         }
432     }
433
434     public Locale getPreferredLocale() {
435         return locale;
436     }
437
438     public void setPreferredLocale(Locale locale) {
439         this.locale = locale;
440
441     }
442
443     public synchronized Name getPreferredName() {
444         return preferredName;
445     }
446
447     public synchronized void setPreferredName(Name preferred) throws GigiApiException {
448         if (preferred.getOwner() != this) {
449             throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
450         }
451         this.preferredName = preferred;
452         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
453             ps.setInt(1, preferred.getId());
454             ps.setInt(2, getId());
455             ps.executeUpdate();
456         }
457
458     }
459
460     public synchronized String getInitials() {
461         return preferredName.toInitialsString();
462     }
463
464     public boolean isInGroup(Group g) {
465         return groups.contains(g);
466     }
467
468     public Set<Group> getGroups() {
469         return Collections.unmodifiableSet(groups);
470     }
471
472     public void grantGroup(User granter, Group toGrant) throws GigiApiException {
473         if (toGrant.isManagedBySupport() && !granter.isInGroup(Group.SUPPORTER)) {
474             throw new GigiApiException("Group may only be managed by supporter");
475         }
476         if (toGrant.isManagedBySupport() && granter == this) {
477             throw new GigiApiException("Group may only be managed by supporter that is not oneself");
478         }
479         groups.add(toGrant);
480         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
481             ps.setInt(1, getId());
482             ps.setEnum(2, toGrant);
483             ps.setInt(3, granter.getId());
484             ps.execute();
485         }
486     }
487
488     public void revokeGroup(User revoker, Group toRevoke) throws GigiApiException {
489         if (toRevoke.isManagedBySupport() && !revoker.isInGroup(Group.SUPPORTER)) {
490             throw new GigiApiException("Group may only be managed by supporter");
491         }
492         groups.remove(toRevoke);
493         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
494             ps.setInt(1, revoker.getId());
495             ps.setEnum(2, toRevoke);
496             ps.setInt(3, getId());
497             ps.execute();
498         }
499     }
500
501     public List<Organisation> getOrganisations() {
502         return getOrganisations(false);
503     }
504
505     public List<Organisation> getOrganisations(boolean isAdmin) {
506         List<Organisation> orgas = new ArrayList<>();
507         try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
508             query.setInt(1, getId());
509             try (GigiResultSet res = query.executeQuery()) {
510                 while (res.next()) {
511                     orgas.add(Organisation.getById(res.getInt(1)));
512                 }
513
514                 return orgas;
515             }
516         }
517     }
518
519     public static synchronized User getById(int id) {
520         CertificateOwner co = CertificateOwner.getById(id);
521         if (co instanceof User) {
522             return (User) co;
523         }
524
525         return null;
526     }
527
528     public static User getByEmail(String mail) {
529         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
530             ps.setString(1, mail);
531             GigiResultSet rs = ps.executeQuery();
532             if ( !rs.next()) {
533                 return null;
534             }
535
536             return User.getById(rs.getInt(1));
537         }
538     }
539
540     public static User[] findByEmail(String mail) {
541         LinkedList<User> results = new LinkedList<User>();
542         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")) {
543             ps.setString(1, mail);
544             GigiResultSet rs = ps.executeQuery();
545             while (rs.next()) {
546                 results.add(User.getById(rs.getInt(1)));
547             }
548             return results.toArray(new User[results.size()]);
549         }
550     }
551
552     public EmailAddress[] getEmails() {
553         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
554             ps.setInt(1, getId());
555
556             GigiResultSet rs = ps.executeQuery();
557             LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
558
559             while (rs.next()) {
560                 data.add(EmailAddress.getById(rs.getInt(1)));
561             }
562
563             return data.toArray(new EmailAddress[0]);
564         }
565     }
566
567     @Override
568     public boolean isValidEmail(String email) {
569         for (EmailAddress em : getEmails()) {
570             if (em.getAddress().equals(email)) {
571                 return em.isVerified();
572             }
573         }
574
575         return false;
576     }
577
578     public String[] getTrainings() {
579         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")) {
580             prep.setInt(1, getId());
581             GigiResultSet res = prep.executeQuery();
582             List<String> entries = new LinkedList<String>();
583
584             while (res.next()) {
585                 StringBuilder training = new StringBuilder();
586                 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
587                 training.append(" (");
588                 training.append(res.getString(2));
589                 if (res.getString(3).length() > 0) {
590                     training.append(" ");
591                     training.append(res.getString(3));
592                 }
593                 if (res.getString(4).length() > 0) {
594                     training.append(", ");
595                     training.append(res.getString(4));
596                 }
597                 training.append(")");
598                 entries.add(training.toString());
599             }
600
601             return entries.toArray(new String[0]);
602         }
603
604     }
605
606     public int generatePasswordResetTicket(User actor, String token, String privateToken) {
607         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
608             ps.setInt(1, getId());
609             ps.setInt(2, getId());
610             ps.setString(3, token);
611             ps.setString(4, PasswordHash.hash(privateToken));
612             ps.execute();
613             return ps.lastInsertId();
614         }
615     }
616
617     public static User getResetWithToken(int id, String token) {
618         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")) {
619             ps.setInt(1, id);
620             ps.setString(2, token);
621             ps.setInt(3, PasswordResetPage.HOUR_MAX);
622             GigiResultSet res = ps.executeQuery();
623             if ( !res.next()) {
624                 return null;
625             }
626             return User.getById(res.getInt(1));
627         }
628     }
629
630     public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
631         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
632             ps.setInt(1, id);
633             ps.setInt(2, getId());
634             GigiResultSet rs = ps.executeQuery();
635             if ( !rs.next()) {
636                 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
637             }
638             if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
639                 throw new GigiApiException("Private token does not match.");
640             }
641             setPassword(newPassword);
642         }
643         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET  `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
644             ps.setInt(1, id);
645             ps.executeUpdate();
646         }
647     }
648
649     private Verification verificationByRes(GigiResultSet res) {
650         try {
651             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"));
652         } catch (GigiApiException e) {
653             throw new Error(e);
654         }
655     }
656
657     public boolean isInVerificationLimit() {
658         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;")) {
659             ps.setInt(1, getId());
660             ps.setInt(2, VERIFICATION_MONTHS);
661
662             GigiResultSet rs = ps.executeQuery();
663             return rs.next();
664         }
665     }
666
667     private void writeObject(ObjectOutputStream oos) throws IOException {}
668
669     private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {}
670
671     public Country getResidenceCountry() {
672         return residenceCountry;
673     }
674
675     public void setResidenceCountry(Country residenceCountry) {
676         this.residenceCountry = residenceCountry;
677         rawUpdateCountryData();
678     }
679
680     private void rawUpdateCountryData() {
681         try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET country=? WHERE id=?")) {
682             update.setString(1, residenceCountry == null ? null : residenceCountry.getCode());
683             update.setInt(2, getId());
684             update.executeUpdate();
685         }
686     }
687
688     public boolean hasValidRAChallenge() {
689         return CATS.isInCatsLimit(getId(), CATSType.AGENT_CHALLENGE.getId());
690     }
691
692     public boolean hasValidSupportChallenge() {
693         return CATS.isInCatsLimit(getId(), CATSType.SUPPORT_DP_CHALLENGE_NAME.getId());
694     }
695
696     public boolean hasValidOrgAdminChallenge() {
697         return CATS.isInCatsLimit(getId(), CATSType.ORG_ADMIN_DP_CHALLENGE_NAME.getId());
698     }
699
700     public boolean hasValidOrgAgentChallenge() {
701         return CATS.isInCatsLimit(getId(), CATSType.ORG_AGENT_CHALLENGE.getId());
702     }
703
704     public boolean hasValidTTPAgentChallenge() {
705         return CATS.isInCatsLimit(getId(), CATSType.TTP_AGENT_CHALLENGE.getId());
706     }
707
708     public void writeUserLog(User actor, String type) throws GigiApiException {
709         try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `adminLog` SET uid=?, admin=?, type=?")) {
710             prep.setInt(1, actor.getId());
711             prep.setInt(2, getId());
712             prep.setString(3, type);
713             prep.executeUpdate();
714         }
715     }
716 }