]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/User.java
UPD: Stricter name part handling
[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 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() {}
66
67     public Name getName() {
68         return name;
69     }
70
71     public Date getDoB() {
72         return dob;
73     }
74
75     public void setDoB(Date dob) {
76         this.dob = dob;
77     }
78
79     public String getEmail() {
80         return email;
81     }
82
83     public void setEmail(String email) {
84         this.email = email;
85     }
86
87     public void insert(String password) {
88         int id = super.insert();
89         GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("insert into `users` set `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `language`=?, id=?");
90         query.setString(1, email);
91         query.setString(2, PasswordHash.hash(password));
92         query.setString(3, name.getFname());
93         query.setString(4, name.getMname());
94         query.setString(5, name.getLname());
95         query.setString(6, name.getSuffix());
96         query.setDate(7, new java.sql.Date(dob.getTime()));
97         query.setString(8, locale.toString());
98         query.setInt(9, id);
99         query.execute();
100     }
101
102     public void changePassword(String oldPass, String newPass) throws GigiApiException {
103         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `password` FROM users WHERE id=?");
104         ps.setInt(1, getId());
105         try (GigiResultSet rs = ps.executeQuery()) {
106             if ( !rs.next()) {
107                 throw new GigiApiException("User not found... very bad.");
108             }
109             if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
110                 throw new GigiApiException("Old password does not match.");
111             }
112         }
113
114         PasswordStrengthChecker.assertStrongPassword(newPass, this);
115         ps = DatabaseConnection.getInstance().prepare("UPDATE users SET `password`=? WHERE id=?");
116         ps.setString(1, PasswordHash.hash(newPass));
117         ps.setInt(2, getId());
118         ps.executeUpdate();
119     }
120
121     public void setName(Name name) {
122         this.name = name;
123     }
124
125     public boolean canAssure() {
126         if ( !isOfAge(14)) { // PoJAM
127             return false;
128         }
129         if (getAssurancePoints() < 100) {
130             return false;
131         }
132
133         return hasPassedCATS();
134
135     }
136
137     public boolean hasPassedCATS() {
138         GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `cats_passed` where `user_id`=?");
139         query.setInt(1, getId());
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=? WHERE id=?");
255                 ps.setDate(1, new Date(System.currentTimeMillis()));
256                 ps.setInt(2, delMail.getId());
257                 ps.execute();
258                 return;
259             }
260         }
261         throw new GigiApiException("Email not one of user's email addresses.");
262     }
263
264     public synchronized Assurance[] getReceivedAssurances() {
265         if (receivedAssurances == null) {
266             GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `to`=? AND deleted IS NULL");
267             query.setInt(1, getId());
268
269             try (GigiResultSet res = query.executeQuery()) {
270                 List<Assurance> assurances = new LinkedList<Assurance>();
271
272                 while (res.next()) {
273                     assurances.add(new Assurance(res));
274                 }
275
276                 this.receivedAssurances = assurances.toArray(new Assurance[0]);
277             }
278         }
279
280         return receivedAssurances;
281     }
282
283     public synchronized Assurance[] getMadeAssurances() {
284         if (madeAssurances == null) {
285             GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `from`=? AND deleted is NULL");
286             query.setInt(1, getId());
287
288             try (GigiResultSet res = query.executeQuery()) {
289                 List<Assurance> assurances = new LinkedList<Assurance>();
290
291                 while (res.next()) {
292                     assurances.add(new Assurance(res));
293                 }
294
295                 this.madeAssurances = assurances.toArray(new Assurance[0]);
296             }
297         }
298
299         return madeAssurances;
300     }
301
302     public synchronized void invalidateMadeAssurances() {
303         madeAssurances = null;
304     }
305
306     public synchronized void invalidateReceivedAssurances() {
307         receivedAssurances = null;
308     }
309
310     public void updateUserData() throws GigiApiException {
311         synchronized (Notary.class) {
312             // FIXME: No assurance, not no points.
313             if (getAssurancePoints() != 0) {
314                 throw new GigiApiException("No change after assurance allowed.");
315             }
316
317             GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?");
318             update.setString(1, name.getFname());
319             update.setString(2, name.getLname());
320             update.setString(3, name.getMname());
321             update.setString(4, name.getSuffix());
322             update.setDate(5, getDoB());
323             update.setInt(6, getId());
324             update.executeUpdate();
325         }
326     }
327
328     public Locale getPreferredLocale() {
329         return locale;
330     }
331
332     public void setPreferredLocale(Locale locale) {
333         this.locale = locale;
334
335     }
336
337     public boolean wantsDirectoryListing() {
338         GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT listme FROM users WHERE id=?");
339         get.setInt(1, getId());
340         try (GigiResultSet exec = get.executeQuery()) {
341             return exec.next() && exec.getBoolean("listme");
342         }
343     }
344
345     public String getContactInformation() {
346         GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT contactinfo FROM users WHERE id=?");
347         get.setInt(1, getId());
348
349         try (GigiResultSet exec = get.executeQuery()) {
350             exec.next();
351             return exec.getString("contactinfo");
352         }
353     }
354
355     public void setDirectoryListing(boolean on) {
356         GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET listme = ? WHERE id = ?");
357         update.setBoolean(1, on);
358         update.setInt(2, getId());
359         update.executeUpdate();
360     }
361
362     public void setContactInformation(String contactInfo) {
363         GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET contactinfo = ? WHERE id = ?");
364         update.setString(1, contactInfo);
365         update.setInt(2, getId());
366         update.executeUpdate();
367     }
368
369     public boolean isInGroup(Group g) {
370         return groups.contains(g);
371     }
372
373     public Set<Group> getGroups() {
374         return Collections.unmodifiableSet(groups);
375     }
376
377     public void grantGroup(User granter, Group toGrant) {
378         groups.add(toGrant);
379         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO user_groups SET user=?, permission=?, grantedby=?");
380         ps.setInt(1, getId());
381         ps.setString(2, toGrant.getDatabaseName());
382         ps.setInt(3, granter.getId());
383         ps.execute();
384     }
385
386     public void revokeGroup(User revoker, Group toRevoke) {
387         groups.remove(toRevoke);
388         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE user_groups SET deleted=CURRENT_TIMESTAMP, revokedby=? WHERE deleted is NULL AND permission=? AND user=?");
389         ps.setInt(1, revoker.getId());
390         ps.setString(2, toRevoke.getDatabaseName());
391         ps.setInt(3, getId());
392         ps.execute();
393     }
394
395     public List<Organisation> getOrganisations() {
396         List<Organisation> orgas = new ArrayList<>();
397         GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT orgid FROM org_admin WHERE `memid`=? AND deleted is NULL");
398         query.setInt(1, getId());
399         try (GigiResultSet res = query.executeQuery()) {
400             while (res.next()) {
401                 orgas.add(Organisation.getById(res.getInt(1)));
402             }
403
404             return orgas;
405         }
406     }
407
408     public static synchronized User getById(int id) {
409         CertificateOwner co = CertificateOwner.getById(id);
410         if (co instanceof User) {
411             return (User) co;
412         }
413
414         return null;
415     }
416
417     public static User getByEmail(String mail) {
418         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT users.id FROM users INNER JOIN certOwners ON certOwners.id = users.id WHERE email=? AND deleted IS NULL");
419         ps.setString(1, mail);
420         try (GigiResultSet rs = ps.executeQuery()) {
421             if ( !rs.next()) {
422                 return null;
423             }
424
425             return User.getById(rs.getInt(1));
426         }
427     }
428
429     public static User[] findByEmail(String mail) {
430         LinkedList<User> results = new LinkedList<User>();
431         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 ASC LIMIT 100");
432         ps.setString(1, mail);
433         try (GigiResultSet rs = ps.executeQuery()) {
434             while (rs.next()) {
435                 results.add(User.getById(rs.getInt(1)));
436             }
437             return results.toArray(new User[results.size()]);
438         }
439     }
440
441     public boolean canIssue(CertificateProfile p) {
442         // FIXME: Use descriptive constants
443         switch (p.getCAId()) {
444         case 0:
445             return true;
446         case 1:
447             return getAssurancePoints() > 50;
448         case 2:
449             return getAssurancePoints() > 50 && isInGroup(Group.getByString("codesigning"));
450         case 3:
451         case 4:
452             return getOrganisations().size() > 0;
453         default:
454             return false;
455         }
456     }
457
458 }