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