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