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