]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/User.java
fix: Proper synchronization when retrieving the preferred name
[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     @SuppressWarnings("unused")
261     public int getMaxAssurePoints() {
262         if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
263             return 10; // PoJAM
264         }
265
266         int exp = getExperiencePoints();
267         int points = 10;
268
269         if (exp >= 5 * EXPERIENCE_POINTS) {
270             points += 5;
271         }
272         if (exp >= 10 * EXPERIENCE_POINTS) {
273             points += 5;
274         }
275         if (exp >= 15 * EXPERIENCE_POINTS) {
276             points += 5;
277         }
278         if (exp >= 20 * EXPERIENCE_POINTS) {
279             points += 5;
280         }
281         if (exp >= 25 * EXPERIENCE_POINTS) {
282             points += 5;
283         }
284
285         return points;
286     }
287
288     public boolean isValidName(String name) {
289         for (Name n : getNames()) {
290             if (n.matches(name) && n.getAssurancePoints() >= 50) {
291                 return true;
292             }
293         }
294         return false;
295     }
296
297     public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
298         for (EmailAddress email : getEmails()) {
299             if (email.getAddress().equals(newMail.getAddress())) {
300                 if ( !email.isVerified()) {
301                     throw new GigiApiException("Email not verified.");
302                 }
303
304                 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
305                     ps.setString(1, newMail.getAddress());
306                     ps.setInt(2, getId());
307                     ps.execute();
308                 }
309
310                 this.email = newMail.getAddress();
311                 return;
312             }
313         }
314
315         throw new GigiApiException("Given address not an address of the user.");
316     }
317
318     public void deleteEmail(EmailAddress delMail) throws GigiApiException {
319         if (getEmail().equals(delMail.getAddress())) {
320             throw new GigiApiException("Can't delete user's default e-mail.");
321         }
322
323         for (EmailAddress email : getEmails()) {
324             if (email.getId() == delMail.getId()) {
325                 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
326                     ps.setInt(1, delMail.getId());
327                     ps.execute();
328                 }
329                 return;
330             }
331         }
332         throw new GigiApiException("Email not one of user's email addresses.");
333     }
334
335     public synchronized Assurance[] getReceivedAssurances() {
336         if (receivedAssurances == null) {
337             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")) {
338                 query.setInt(1, getId());
339
340                 GigiResultSet res = query.executeQuery();
341                 List<Assurance> assurances = new LinkedList<Assurance>();
342
343                 while (res.next()) {
344                     assurances.add(assuranceByRes(res));
345                 }
346
347                 this.receivedAssurances = assurances.toArray(new Assurance[0]);
348             }
349         }
350
351         return receivedAssurances;
352     }
353
354     public synchronized Assurance[] getMadeAssurances() {
355         if (madeAssurances == null) {
356             try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
357                 query.setInt(1, getId());
358
359                 try (GigiResultSet res = query.executeQuery()) {
360                     List<Assurance> assurances = new LinkedList<Assurance>();
361
362                     while (res.next()) {
363                         assurances.add(assuranceByRes(res));
364                     }
365
366                     this.madeAssurances = assurances.toArray(new Assurance[0]);
367                 }
368             }
369         }
370
371         return madeAssurances;
372     }
373
374     public synchronized void invalidateMadeAssurances() {
375         madeAssurances = null;
376     }
377
378     public synchronized void invalidateReceivedAssurances() {
379         receivedAssurances = null;
380     }
381
382     private void rawUpdateUserData() {
383         try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
384             update.setDate(1, getDoB().toSQLDate());
385             update.setInt(2, getId());
386             update.executeUpdate();
387         }
388     }
389
390     public Locale getPreferredLocale() {
391         return locale;
392     }
393
394     public void setPreferredLocale(Locale locale) {
395         this.locale = locale;
396
397     }
398
399     public synchronized Name getPreferredName() {
400         return preferredName;
401     }
402
403     public synchronized void setPreferredName(Name preferred) throws GigiApiException {
404         if (preferred.getOwner() != this) {
405             throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
406         }
407         this.preferredName = preferred;
408         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
409             ps.setInt(1, preferred.getId());
410             ps.setInt(2, getId());
411             ps.executeUpdate();
412         }
413
414     }
415
416     public boolean isInGroup(Group g) {
417         return groups.contains(g);
418     }
419
420     public Set<Group> getGroups() {
421         return Collections.unmodifiableSet(groups);
422     }
423
424     public void grantGroup(User granter, Group toGrant) {
425         groups.add(toGrant);
426         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
427             ps.setInt(1, getId());
428             ps.setString(2, toGrant.getDatabaseName());
429             ps.setInt(3, granter.getId());
430             ps.execute();
431         }
432     }
433
434     public void revokeGroup(User revoker, Group toRevoke) {
435         groups.remove(toRevoke);
436         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
437             ps.setInt(1, revoker.getId());
438             ps.setString(2, toRevoke.getDatabaseName());
439             ps.setInt(3, getId());
440             ps.execute();
441         }
442     }
443
444     public List<Organisation> getOrganisations() {
445         return getOrganisations(false);
446     }
447
448     public List<Organisation> getOrganisations(boolean isAdmin) {
449         List<Organisation> orgas = new ArrayList<>();
450         try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
451             query.setInt(1, getId());
452             try (GigiResultSet res = query.executeQuery()) {
453                 while (res.next()) {
454                     orgas.add(Organisation.getById(res.getInt(1)));
455                 }
456
457                 return orgas;
458             }
459         }
460     }
461
462     public static synchronized User getById(int id) {
463         CertificateOwner co = CertificateOwner.getById(id);
464         if (co instanceof User) {
465             return (User) co;
466         }
467
468         return null;
469     }
470
471     public static User getByEmail(String mail) {
472         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
473             ps.setString(1, mail);
474             GigiResultSet rs = ps.executeQuery();
475             if ( !rs.next()) {
476                 return null;
477             }
478
479             return User.getById(rs.getInt(1));
480         }
481     }
482
483     public static User[] findByEmail(String mail) {
484         LinkedList<User> results = new LinkedList<User>();
485         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")) {
486             ps.setString(1, mail);
487             GigiResultSet rs = ps.executeQuery();
488             while (rs.next()) {
489                 results.add(User.getById(rs.getInt(1)));
490             }
491             return results.toArray(new User[results.size()]);
492         }
493     }
494
495     public EmailAddress[] getEmails() {
496         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
497             ps.setInt(1, getId());
498
499             GigiResultSet rs = ps.executeQuery();
500             LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
501
502             while (rs.next()) {
503                 data.add(EmailAddress.getById(rs.getInt(1)));
504             }
505
506             return data.toArray(new EmailAddress[0]);
507         }
508     }
509
510     @Override
511     public boolean isValidEmail(String email) {
512         for (EmailAddress em : getEmails()) {
513             if (em.getAddress().equals(email)) {
514                 return em.isVerified();
515             }
516         }
517
518         return false;
519     }
520
521     public String[] getTrainings() {
522         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")) {
523             prep.setInt(1, getId());
524             GigiResultSet res = prep.executeQuery();
525             List<String> entries = new LinkedList<String>();
526
527             while (res.next()) {
528                 StringBuilder training = new StringBuilder();
529                 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
530                 training.append(" (");
531                 training.append(res.getString(2));
532                 if (res.getString(3).length() > 0) {
533                     training.append(" ");
534                     training.append(res.getString(3));
535                 }
536                 if (res.getString(4).length() > 0) {
537                     training.append(", ");
538                     training.append(res.getString(4));
539                 }
540                 training.append(")");
541                 entries.add(training.toString());
542             }
543
544             return entries.toArray(new String[0]);
545         }
546
547     }
548
549     public int generatePasswordResetTicket(User actor, String token, String privateToken) {
550         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
551             ps.setInt(1, getId());
552             ps.setInt(2, getId());
553             ps.setString(3, token);
554             ps.setString(4, PasswordHash.hash(privateToken));
555             ps.execute();
556             return ps.lastInsertId();
557         }
558     }
559
560     public static User getResetWithToken(int id, String token) {
561         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
562             ps.setInt(1, id);
563             ps.setString(2, token);
564             ps.setInt(3, PasswordResetPage.HOUR_MAX);
565             GigiResultSet res = ps.executeQuery();
566             if ( !res.next()) {
567                 return null;
568             }
569             return User.getById(res.getInt(1));
570         }
571     }
572
573     public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
574         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
575             ps.setInt(1, id);
576             ps.setInt(2, getId());
577             GigiResultSet rs = ps.executeQuery();
578             if ( !rs.next()) {
579                 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
580             }
581             if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
582                 throw new GigiApiException("Private token does not match.");
583             }
584             setPassword(newPassword);
585         }
586         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET  `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
587             ps.setInt(1, id);
588             ps.executeUpdate();
589         }
590     }
591
592     private Assurance assuranceByRes(GigiResultSet res) {
593         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"));
594     }
595
596     public boolean isInVerificationLimit() {
597         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;")) {
598             ps.setInt(1, getId());
599             ps.setInt(2, VERIFICATION_MONTHS);
600
601             GigiResultSet rs = ps.executeQuery();
602             return rs.next();
603         }
604     }
605
606 }