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