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