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