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