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