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