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