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