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