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