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