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