]> WPIA git - gigi.git/blob - src/club/wpia/gigi/dbObjects/User.java
Merge "add: ensure org ra agents cannot manage org where they are org admin"
[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     private 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         return hasPassedCATS();
246
247     }
248
249     public boolean hasPassedCATS() {
250         try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
251             query.setInt(1, getId());
252             query.setInt(2, CATSType.AGENT_CHALLENGE.getId());
253             try (GigiResultSet rs = query.executeQuery()) {
254                 if (rs.next()) {
255                     return true;
256                 } else {
257                     return false;
258                 }
259             }
260         }
261     }
262
263     public int getVerificationPoints() {
264         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")) {
265             query.setInt(1, getId());
266
267             GigiResultSet rs = query.executeQuery();
268             int points = 0;
269
270             if (rs.next()) {
271                 points = rs.getInt(1);
272             }
273
274             return points;
275         }
276     }
277
278     public int getExperiencePoints() {
279         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")) {
280             query.setInt(1, getId());
281             query.setEnum(2, VerificationType.FACE_TO_FACE);
282
283             GigiResultSet rs = query.executeQuery();
284             int points = 0;
285
286             if (rs.next()) {
287                 points = rs.getInt(1) * EXPERIENCE_POINTS;
288             }
289
290             return points;
291         }
292     }
293
294     /**
295      * Gets the maximum allowed points NOW. Note that a verification needs to
296      * re-check PoJam as it has taken place in the past.
297      * 
298      * @return the maximal points @
299      */
300     @SuppressWarnings("unused")
301     public int getMaxVerifyPoints() {
302         if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
303             return 10; // PoJAM
304         }
305
306         int exp = getExperiencePoints();
307         int points = 10;
308
309         if (exp >= 5 * EXPERIENCE_POINTS) {
310             points += 5;
311         }
312         if (exp >= 10 * EXPERIENCE_POINTS) {
313             points += 5;
314         }
315         if (exp >= 15 * EXPERIENCE_POINTS) {
316             points += 5;
317         }
318         if (exp >= 20 * EXPERIENCE_POINTS) {
319             points += 5;
320         }
321         if (exp >= 25 * EXPERIENCE_POINTS) {
322             points += 5;
323         }
324
325         return points;
326     }
327
328     public boolean isValidName(String name) {
329         for (Name n : getNames()) {
330             if (n.matches(name) && n.getVerificationPoints() >= 50) {
331                 return true;
332             }
333         }
334         return false;
335     }
336
337     public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
338         for (EmailAddress email : getEmails()) {
339             if (email.getAddress().equals(newMail.getAddress())) {
340                 if ( !email.isVerified()) {
341                     throw new GigiApiException("Email not verified.");
342                 }
343
344                 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
345                     ps.setString(1, newMail.getAddress());
346                     ps.setInt(2, getId());
347                     ps.execute();
348                 }
349
350                 this.email = newMail.getAddress();
351                 return;
352             }
353         }
354
355         throw new GigiApiException("Given address not an address of the user.");
356     }
357
358     public void deleteEmail(EmailAddress delMail) throws GigiApiException {
359         if (getEmail().equals(delMail.getAddress())) {
360             throw new GigiApiException("Can't delete user's default e-mail.");
361         }
362
363         for (EmailAddress email : getEmails()) {
364             if (email.getId() == delMail.getId()) {
365                 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
366                     ps.setInt(1, delMail.getId());
367                     ps.execute();
368                 }
369                 return;
370             }
371         }
372         throw new GigiApiException("Email not one of user's email addresses.");
373     }
374
375     public synchronized Verification[] getReceivedVerifications() {
376         if (receivedVerifications == null) {
377             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")) {
378                 query.setInt(1, getId());
379
380                 GigiResultSet res = query.executeQuery();
381                 List<Verification> verifications = new LinkedList<Verification>();
382
383                 while (res.next()) {
384                     verifications.add(verificationByRes(res));
385                 }
386
387                 this.receivedVerifications = verifications.toArray(new Verification[0]);
388             }
389         }
390
391         return receivedVerifications;
392     }
393
394     public synchronized Verification[] getMadeVerifications() {
395         if (madeVerifications == null) {
396             try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
397                 query.setInt(1, getId());
398
399                 try (GigiResultSet res = query.executeQuery()) {
400                     List<Verification> verifications = new LinkedList<Verification>();
401
402                     while (res.next()) {
403                         verifications.add(verificationByRes(res));
404                     }
405
406                     this.madeVerifications = verifications.toArray(new Verification[0]);
407                 }
408             }
409         }
410
411         return madeVerifications;
412     }
413
414     public synchronized void invalidateMadeVerifications() {
415         madeVerifications = null;
416     }
417
418     public synchronized void invalidateReceivedVerifications() {
419         receivedVerifications = null;
420     }
421
422     private void rawUpdateUserData() {
423         try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
424             update.setDate(1, getDoB().toSQLDate());
425             update.setInt(2, getId());
426             update.executeUpdate();
427         }
428     }
429
430     public Locale getPreferredLocale() {
431         return locale;
432     }
433
434     public void setPreferredLocale(Locale locale) {
435         this.locale = locale;
436
437     }
438
439     public synchronized Name getPreferredName() {
440         return preferredName;
441     }
442
443     public synchronized void setPreferredName(Name preferred) throws GigiApiException {
444         if (preferred.getOwner() != this) {
445             throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
446         }
447         this.preferredName = preferred;
448         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
449             ps.setInt(1, preferred.getId());
450             ps.setInt(2, getId());
451             ps.executeUpdate();
452         }
453
454     }
455
456     public synchronized String getInitials() {
457         return preferredName.toInitialsString();
458     }
459
460     public boolean isInGroup(Group g) {
461         return groups.contains(g);
462     }
463
464     public Set<Group> getGroups() {
465         return Collections.unmodifiableSet(groups);
466     }
467
468     public void grantGroup(User granter, Group toGrant) throws GigiApiException {
469         if (toGrant.isManagedBySupport() && !granter.isInGroup(Group.SUPPORTER)) {
470             throw new GigiApiException("Group may only be managed by supporter");
471         }
472         if (toGrant.isManagedBySupport() && granter == this) {
473             throw new GigiApiException("Group may only be managed by supporter that is not oneself");
474         }
475         groups.add(toGrant);
476         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
477             ps.setInt(1, getId());
478             ps.setEnum(2, toGrant);
479             ps.setInt(3, granter.getId());
480             ps.execute();
481         }
482     }
483
484     public void revokeGroup(User revoker, Group toRevoke) throws GigiApiException {
485         if (toRevoke.isManagedBySupport() && !revoker.isInGroup(Group.SUPPORTER)) {
486             throw new GigiApiException("Group may only be managed by supporter");
487         }
488         groups.remove(toRevoke);
489         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
490             ps.setInt(1, revoker.getId());
491             ps.setEnum(2, toRevoke);
492             ps.setInt(3, getId());
493             ps.execute();
494         }
495     }
496
497     public List<Organisation> getOrganisations() {
498         return getOrganisations(false);
499     }
500
501     public List<Organisation> getOrganisations(boolean isAdmin) {
502         List<Organisation> orgas = new ArrayList<>();
503         try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
504             query.setInt(1, getId());
505             try (GigiResultSet res = query.executeQuery()) {
506                 while (res.next()) {
507                     orgas.add(Organisation.getById(res.getInt(1)));
508                 }
509
510                 return orgas;
511             }
512         }
513     }
514
515     public static synchronized User getById(int id) {
516         CertificateOwner co = CertificateOwner.getById(id);
517         if (co instanceof User) {
518             return (User) co;
519         }
520
521         return null;
522     }
523
524     public static User getByEmail(String mail) {
525         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
526             ps.setString(1, mail);
527             GigiResultSet rs = ps.executeQuery();
528             if ( !rs.next()) {
529                 return null;
530             }
531
532             return User.getById(rs.getInt(1));
533         }
534     }
535
536     public static User[] findByEmail(String mail) {
537         LinkedList<User> results = new LinkedList<User>();
538         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")) {
539             ps.setString(1, mail);
540             GigiResultSet rs = ps.executeQuery();
541             while (rs.next()) {
542                 results.add(User.getById(rs.getInt(1)));
543             }
544             return results.toArray(new User[results.size()]);
545         }
546     }
547
548     public EmailAddress[] getEmails() {
549         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
550             ps.setInt(1, getId());
551
552             GigiResultSet rs = ps.executeQuery();
553             LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
554
555             while (rs.next()) {
556                 data.add(EmailAddress.getById(rs.getInt(1)));
557             }
558
559             return data.toArray(new EmailAddress[0]);
560         }
561     }
562
563     @Override
564     public boolean isValidEmail(String email) {
565         for (EmailAddress em : getEmails()) {
566             if (em.getAddress().equals(email)) {
567                 return em.isVerified();
568             }
569         }
570
571         return false;
572     }
573
574     public String[] getTrainings() {
575         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` ASC")) {
576             prep.setInt(1, getId());
577             GigiResultSet res = prep.executeQuery();
578             List<String> entries = new LinkedList<String>();
579
580             while (res.next()) {
581                 StringBuilder training = new StringBuilder();
582                 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
583                 training.append(" (");
584                 training.append(res.getString(2));
585                 if (res.getString(3).length() > 0) {
586                     training.append(" ");
587                     training.append(res.getString(3));
588                 }
589                 if (res.getString(4).length() > 0) {
590                     training.append(", ");
591                     training.append(res.getString(4));
592                 }
593                 training.append(")");
594                 entries.add(training.toString());
595             }
596
597             return entries.toArray(new String[0]);
598         }
599
600     }
601
602     public int generatePasswordResetTicket(User actor, String token, String privateToken) {
603         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
604             ps.setInt(1, getId());
605             ps.setInt(2, getId());
606             ps.setString(3, token);
607             ps.setString(4, PasswordHash.hash(privateToken));
608             ps.execute();
609             return ps.lastInsertId();
610         }
611     }
612
613     public static User getResetWithToken(int id, String token) {
614         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")) {
615             ps.setInt(1, id);
616             ps.setString(2, token);
617             ps.setInt(3, PasswordResetPage.HOUR_MAX);
618             GigiResultSet res = ps.executeQuery();
619             if ( !res.next()) {
620                 return null;
621             }
622             return User.getById(res.getInt(1));
623         }
624     }
625
626     public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
627         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
628             ps.setInt(1, id);
629             ps.setInt(2, getId());
630             GigiResultSet rs = ps.executeQuery();
631             if ( !rs.next()) {
632                 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
633             }
634             if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
635                 throw new GigiApiException("Private token does not match.");
636             }
637             setPassword(newPassword);
638         }
639         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET  `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
640             ps.setInt(1, id);
641             ps.executeUpdate();
642         }
643     }
644
645     private Verification verificationByRes(GigiResultSet res) {
646         try {
647             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"));
648         } catch (GigiApiException e) {
649             throw new Error(e);
650         }
651     }
652
653     public boolean isInVerificationLimit() {
654         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;")) {
655             ps.setInt(1, getId());
656             ps.setInt(2, VERIFICATION_MONTHS);
657
658             GigiResultSet rs = ps.executeQuery();
659             return rs.next();
660         }
661     }
662
663     private void writeObject(ObjectOutputStream oos) throws IOException {}
664
665     private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {}
666
667     public Country getResidenceCountry() {
668         return residenceCountry;
669     }
670
671     public void setResidenceCountry(Country residenceCountry) {
672         this.residenceCountry = residenceCountry;
673         rawUpdateCountryData();
674     }
675
676     private void rawUpdateCountryData() {
677         try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET country=? WHERE id=?")) {
678             update.setString(1, residenceCountry == null ? null : residenceCountry.getCode());
679             update.setInt(2, getId());
680             update.executeUpdate();
681         }
682     }
683 }