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