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