]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/User.java
99d44a7c3674a1b6fcc329e76be731bc5de90025
[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     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 ( !CalendarUtil.isOfAge(dob, 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 ( !CalendarUtil.isOfAge(dob, 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 isValidName(String name) {
224         return getName().matches(name);
225     }
226
227     public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
228         for (EmailAddress email : getEmails()) {
229             if (email.getAddress().equals(newMail.getAddress())) {
230                 if ( !email.isVerified()) {
231                     throw new GigiApiException("Email not verified.");
232                 }
233
234                 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
235                     ps.setString(1, newMail.getAddress());
236                     ps.setInt(2, getId());
237                     ps.execute();
238                 }
239
240                 this.email = newMail.getAddress();
241                 return;
242             }
243         }
244
245         throw new GigiApiException("Given address not an address of the user.");
246     }
247
248     public void deleteEmail(EmailAddress delMail) throws GigiApiException {
249         if (getEmail().equals(delMail.getAddress())) {
250             throw new GigiApiException("Can't delete user's default e-mail.");
251         }
252
253         for (EmailAddress email : getEmails()) {
254             if (email.getId() == delMail.getId()) {
255                 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
256                     ps.setInt(1, delMail.getId());
257                     ps.execute();
258                 }
259                 return;
260             }
261         }
262         throw new GigiApiException("Email not one of user's email addresses.");
263     }
264
265     public synchronized Assurance[] getReceivedAssurances() {
266         if (receivedAssurances == null) {
267             try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` WHERE `to`=? AND `deleted` IS NULL")) {
268                 query.setInt(1, getId());
269
270                 GigiResultSet res = query.executeQuery();
271                 List<Assurance> assurances = new LinkedList<Assurance>();
272
273                 while (res.next()) {
274                     assurances.add(assuranceByRes(res));
275                 }
276
277                 this.receivedAssurances = assurances.toArray(new Assurance[0]);
278             }
279         }
280
281         return receivedAssurances;
282     }
283
284     public synchronized Assurance[] getMadeAssurances() {
285         if (madeAssurances == null) {
286             try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL")) {
287                 query.setInt(1, getId());
288
289                 try (GigiResultSet res = query.executeQuery()) {
290                     List<Assurance> assurances = new LinkedList<Assurance>();
291
292                     while (res.next()) {
293                         assurances.add(assuranceByRes(res));
294                     }
295
296                     this.madeAssurances = assurances.toArray(new Assurance[0]);
297                 }
298             }
299         }
300
301         return madeAssurances;
302     }
303
304     public synchronized void invalidateMadeAssurances() {
305         madeAssurances = null;
306     }
307
308     public synchronized void invalidateReceivedAssurances() {
309         receivedAssurances = null;
310     }
311
312     public void updateUserData() throws GigiApiException {
313         synchronized (Notary.class) {
314             if (getReceivedAssurances().length != 0) {
315                 throw new GigiApiException("No change after assurance allowed.");
316             }
317             rawUpdateUserData();
318         }
319     }
320
321     protected void rawUpdateUserData() {
322         try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?")) {
323             update.setString(1, name.getFname());
324             update.setString(2, name.getLname());
325             update.setString(3, name.getMname());
326             update.setString(4, name.getSuffix());
327             update.setDate(5, getDoB().toSQLDate());
328             update.setInt(6, getId());
329             update.executeUpdate();
330         }
331     }
332
333     public Locale getPreferredLocale() {
334         return locale;
335     }
336
337     public void setPreferredLocale(Locale locale) {
338         this.locale = locale;
339
340     }
341
342     public boolean wantsDirectoryListing() {
343         try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT listme FROM users WHERE id=?")) {
344             get.setInt(1, getId());
345             GigiResultSet exec = get.executeQuery();
346             return exec.next() && exec.getBoolean("listme");
347         }
348     }
349
350     public String getContactInformation() {
351         try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT contactinfo FROM users WHERE id=?")) {
352             get.setInt(1, getId());
353
354             GigiResultSet exec = get.executeQuery();
355             exec.next();
356             return exec.getString("contactinfo");
357         }
358     }
359
360     public void setDirectoryListing(boolean on) {
361         try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET listme = ? WHERE id = ?")) {
362             update.setBoolean(1, on);
363             update.setInt(2, getId());
364             update.executeUpdate();
365         }
366     }
367
368     public void setContactInformation(String contactInfo) {
369         try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET contactinfo = ? WHERE id = ?")) {
370             update.setString(1, contactInfo);
371             update.setInt(2, getId());
372             update.executeUpdate();
373         }
374     }
375
376     public boolean isInGroup(Group g) {
377         return groups.contains(g);
378     }
379
380     public Set<Group> getGroups() {
381         return Collections.unmodifiableSet(groups);
382     }
383
384     public void grantGroup(User granter, Group toGrant) {
385         groups.add(toGrant);
386         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
387             ps.setInt(1, getId());
388             ps.setString(2, toGrant.getDatabaseName());
389             ps.setInt(3, granter.getId());
390             ps.execute();
391         }
392     }
393
394     public void revokeGroup(User revoker, Group toRevoke) {
395         groups.remove(toRevoke);
396         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
397             ps.setInt(1, revoker.getId());
398             ps.setString(2, toRevoke.getDatabaseName());
399             ps.setInt(3, getId());
400             ps.execute();
401         }
402     }
403
404     public List<Organisation> getOrganisations() {
405         return getOrganisations(false);
406     }
407
408     public List<Organisation> getOrganisations(boolean isAdmin) {
409         List<Organisation> orgas = new ArrayList<>();
410         try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
411             query.setInt(1, getId());
412             try (GigiResultSet res = query.executeQuery()) {
413                 while (res.next()) {
414                     orgas.add(Organisation.getById(res.getInt(1)));
415                 }
416
417                 return orgas;
418             }
419         }
420     }
421
422     public static synchronized User getById(int id) {
423         CertificateOwner co = CertificateOwner.getById(id);
424         if (co instanceof User) {
425             return (User) co;
426         }
427
428         return null;
429     }
430
431     public static User getByEmail(String mail) {
432         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
433             ps.setString(1, mail);
434             GigiResultSet rs = ps.executeQuery();
435             if ( !rs.next()) {
436                 return null;
437             }
438
439             return User.getById(rs.getInt(1));
440         }
441     }
442
443     public static User[] findByEmail(String mail) {
444         LinkedList<User> results = new LinkedList<User>();
445         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")) {
446             ps.setString(1, mail);
447             GigiResultSet rs = ps.executeQuery();
448             while (rs.next()) {
449                 results.add(User.getById(rs.getInt(1)));
450             }
451             return results.toArray(new User[results.size()]);
452         }
453     }
454
455     public EmailAddress[] getEmails() {
456         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
457             ps.setInt(1, getId());
458
459             GigiResultSet rs = ps.executeQuery();
460             LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
461
462             while (rs.next()) {
463                 data.add(EmailAddress.getById(rs.getInt(1)));
464             }
465
466             return data.toArray(new EmailAddress[0]);
467         }
468     }
469
470     @Override
471     public boolean isValidEmail(String email) {
472         for (EmailAddress em : getEmails()) {
473             if (em.getAddress().equals(email)) {
474                 return em.isVerified();
475             }
476         }
477
478         return false;
479     }
480
481     public String[] getTrainings() {
482         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")) {
483             prep.setInt(1, getId());
484             GigiResultSet res = prep.executeQuery();
485             List<String> entries = new LinkedList<String>();
486
487             while (res.next()) {
488
489                 entries.add(DateSelector.getDateFormat().format(res.getTimestamp(1)) + " (" + res.getString(2) + ")");
490             }
491
492             return entries.toArray(new String[0]);
493         }
494
495     }
496
497     public int generatePasswordResetTicket(User actor, String token, String privateToken) {
498         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
499             ps.setInt(1, getId());
500             ps.setInt(2, getId());
501             ps.setString(3, token);
502             ps.setString(4, PasswordHash.hash(privateToken));
503             ps.execute();
504             return ps.lastInsertId();
505         }
506     }
507
508     public static User getResetWithToken(int id, String token) {
509         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL")) {
510             ps.setInt(1, id);
511             ps.setString(2, token);
512             GigiResultSet res = ps.executeQuery();
513             if ( !res.next()) {
514                 return null;
515             }
516             return User.getById(res.getInt(1));
517         }
518     }
519
520     public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
521         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
522             ps.setInt(1, id);
523             ps.setInt(2, getId());
524             GigiResultSet rs = ps.executeQuery();
525             if ( !rs.next()) {
526                 throw new GigiApiException("Token not found... very bad.");
527             }
528             if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
529                 throw new GigiApiException("Private token does not match.");
530             }
531             setPassword(newPassword);
532         }
533         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET  `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
534             ps.setInt(1, id);
535             ps.executeUpdate();
536         }
537     }
538
539     private Assurance assuranceByRes(GigiResultSet res) {
540         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"));
541     }
542 }