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