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