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