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