]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/User.java
upd: remove directory listing information
[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 isInGroup(Group g) {
366         return groups.contains(g);
367     }
368
369     public Set<Group> getGroups() {
370         return Collections.unmodifiableSet(groups);
371     }
372
373     public void grantGroup(User granter, Group toGrant) {
374         groups.add(toGrant);
375         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
376             ps.setInt(1, getId());
377             ps.setString(2, toGrant.getDatabaseName());
378             ps.setInt(3, granter.getId());
379             ps.execute();
380         }
381     }
382
383     public void revokeGroup(User revoker, Group toRevoke) {
384         groups.remove(toRevoke);
385         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
386             ps.setInt(1, revoker.getId());
387             ps.setString(2, toRevoke.getDatabaseName());
388             ps.setInt(3, getId());
389             ps.execute();
390         }
391     }
392
393     public List<Organisation> getOrganisations() {
394         return getOrganisations(false);
395     }
396
397     public List<Organisation> getOrganisations(boolean isAdmin) {
398         List<Organisation> orgas = new ArrayList<>();
399         try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
400             query.setInt(1, getId());
401             try (GigiResultSet res = query.executeQuery()) {
402                 while (res.next()) {
403                     orgas.add(Organisation.getById(res.getInt(1)));
404                 }
405
406                 return orgas;
407             }
408         }
409     }
410
411     public static synchronized User getById(int id) {
412         CertificateOwner co = CertificateOwner.getById(id);
413         if (co instanceof User) {
414             return (User) co;
415         }
416
417         return null;
418     }
419
420     public static User getByEmail(String mail) {
421         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
422             ps.setString(1, mail);
423             GigiResultSet rs = ps.executeQuery();
424             if ( !rs.next()) {
425                 return null;
426             }
427
428             return User.getById(rs.getInt(1));
429         }
430     }
431
432     public static User[] findByEmail(String mail) {
433         LinkedList<User> results = new LinkedList<User>();
434         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")) {
435             ps.setString(1, mail);
436             GigiResultSet rs = ps.executeQuery();
437             while (rs.next()) {
438                 results.add(User.getById(rs.getInt(1)));
439             }
440             return results.toArray(new User[results.size()]);
441         }
442     }
443
444     public EmailAddress[] getEmails() {
445         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
446             ps.setInt(1, getId());
447
448             GigiResultSet rs = ps.executeQuery();
449             LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
450
451             while (rs.next()) {
452                 data.add(EmailAddress.getById(rs.getInt(1)));
453             }
454
455             return data.toArray(new EmailAddress[0]);
456         }
457     }
458
459     @Override
460     public boolean isValidEmail(String email) {
461         for (EmailAddress em : getEmails()) {
462             if (em.getAddress().equals(email)) {
463                 return em.isVerified();
464             }
465         }
466
467         return false;
468     }
469
470     public String[] getTrainings() {
471         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")) {
472             prep.setInt(1, getId());
473             GigiResultSet res = prep.executeQuery();
474             List<String> entries = new LinkedList<String>();
475
476             while (res.next()) {
477                 StringBuilder training = new StringBuilder();
478                 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
479                 training.append(" (");
480                 training.append(res.getString(2));
481                 if (res.getString(3).length() > 0) {
482                     training.append(" ");
483                     training.append(res.getString(3));
484                 }
485                 if (res.getString(4).length() > 0) {
486                     training.append(", ");
487                     training.append(res.getString(4));
488                 }
489                 training.append(")");
490                 entries.add(training.toString());
491             }
492
493             return entries.toArray(new String[0]);
494         }
495
496     }
497
498     public int generatePasswordResetTicket(User actor, String token, String privateToken) {
499         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
500             ps.setInt(1, getId());
501             ps.setInt(2, getId());
502             ps.setString(3, token);
503             ps.setString(4, PasswordHash.hash(privateToken));
504             ps.execute();
505             return ps.lastInsertId();
506         }
507     }
508
509     public static User getResetWithToken(int id, String token) {
510         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
511             ps.setInt(1, id);
512             ps.setString(2, token);
513             ps.setInt(3, PasswordResetPage.HOUR_MAX);
514             GigiResultSet res = ps.executeQuery();
515             if ( !res.next()) {
516                 return null;
517             }
518             return User.getById(res.getInt(1));
519         }
520     }
521
522     public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
523         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
524             ps.setInt(1, id);
525             ps.setInt(2, getId());
526             GigiResultSet rs = ps.executeQuery();
527             if ( !rs.next()) {
528                 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
529             }
530             if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
531                 throw new GigiApiException("Private token does not match.");
532             }
533             setPassword(newPassword);
534         }
535         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET  `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
536             ps.setInt(1, id);
537             ps.executeUpdate();
538         }
539     }
540
541     private Assurance assuranceByRes(GigiResultSet res) {
542         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"));
543     }
544
545     public static boolean isInVerificationLimit(int id) {
546         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;")) {
547             ps.setInt(1, id);
548             ps.setInt(2, VERIFICATION_MONTHS);
549
550             GigiResultSet rs = ps.executeQuery();
551             return rs.next();
552         }
553     }
554 }