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