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