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