]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/User.java
Test+implement: object cache for email and domain.
[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     public 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 (getAssurancePoints() < 100) {
166             return false;
167         }
168
169         return hasPassedCATS();
170
171     }
172
173     public boolean hasPassedCATS() throws SQLException {
174         PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `cats_passed` where `user_id`=?");
175         query.setInt(1, id);
176         ResultSet rs = query.executeQuery();
177         if (rs.next()) {
178             return true;
179         } else {
180             return false;
181         }
182     }
183
184     public int getAssurancePoints() throws SQLException {
185         PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT sum(points) FROM `notary` where `to`=? AND `deleted`=0");
186         query.setInt(1, id);
187         ResultSet rs = query.executeQuery();
188         int points = 0;
189         if (rs.next()) {
190             points = rs.getInt(1);
191         }
192         rs.close();
193         return points;
194     }
195
196     public int getExperiencePoints() throws SQLException {
197         PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0");
198         query.setInt(1, id);
199         ResultSet rs = query.executeQuery();
200         int points = 0;
201         if (rs.next()) {
202             points = rs.getInt(1) * 2;
203         }
204         rs.close();
205         return points;
206     }
207
208     @Override
209     public boolean equals(Object obj) {
210         if ( !(obj instanceof User)) {
211             return false;
212         }
213         User s = (User) obj;
214         return name.equals(s.name) && email.equals(s.email) && dob.toString().equals(s.dob.toString()); // This
215                                                                                                         // is
216                                                                                                         // due
217                                                                                                         // to
218                                                                                                         // day
219                                                                                                         // cutoff
220     }
221
222     /**
223      * Gets the maximum allowed points NOW. Note that an assurance needs to
224      * re-check PoJam as it has taken place in the past.
225      * 
226      * @return the maximal points
227      * @throws SQLException
228      */
229     public int getMaxAssurePoints() throws SQLException {
230         int exp = getExperiencePoints();
231         int points = 10;
232         Calendar c = Calendar.getInstance();
233         c.setTime(dob);
234         int year = c.get(Calendar.YEAR);
235         int month = c.get(Calendar.MONTH);
236         int day = c.get(Calendar.DAY_OF_MONTH);
237         c.set(year + 18, month, day);
238         if (System.currentTimeMillis() < c.getTime().getTime()) {
239             return points; // not 18 Years old.
240         }
241
242         if (exp >= 10) {
243             points += 5;
244         }
245         if (exp >= 20) {
246             points += 5;
247         }
248         if (exp >= 30) {
249             points += 5;
250         }
251         if (exp >= 40) {
252             points += 5;
253         }
254         if (exp >= 50) {
255             points += 5;
256         }
257         return points;
258     }
259
260     public EmailAddress[] getEmails() {
261         try {
262             PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM emails WHERE memid=? AND deleted=0");
263             ps.setInt(1, id);
264             ResultSet rs = ps.executeQuery();
265             rs.last();
266             int count = rs.getRow();
267             EmailAddress[] data = new EmailAddress[count];
268             rs.beforeFirst();
269             for (int i = 0; i < data.length; i++) {
270                 if ( !rs.next()) {
271                     throw new Error("Internal sql api violation.");
272                 }
273                 data[i] = EmailAddress.getById(rs.getInt(1));
274             }
275             rs.close();
276             return data;
277         } catch (SQLException e) {
278             e.printStackTrace();
279         }
280
281         return null;
282     }
283
284     public Domain[] getDomains() {
285         try {
286             PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM domains WHERE memid=? AND deleted IS NULL");
287             ps.setInt(1, id);
288             ResultSet rs = ps.executeQuery();
289             rs.last();
290             int count = rs.getRow();
291             Domain[] data = new Domain[count];
292             rs.beforeFirst();
293             for (int i = 0; i < data.length; i++) {
294                 if ( !rs.next()) {
295                     throw new Error("Internal sql api violation.");
296                 }
297                 data[i] = Domain.getById(rs.getInt(1));
298             }
299             rs.close();
300             return data;
301         } catch (SQLException e) {
302             e.printStackTrace();
303         }
304
305         return null;
306     }
307
308     public Certificate[] getCertificates() {
309         try {
310             PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT serial FROM certs WHERE memid=? AND revoked=0");
311             ps.setInt(1, id);
312             ResultSet rs = ps.executeQuery();
313             rs.last();
314             int count = rs.getRow();
315             Certificate[] data = new Certificate[count];
316             rs.beforeFirst();
317             for (int i = 0; i < data.length; i++) {
318                 if ( !rs.next()) {
319                     throw new Error("Internal sql api violation.");
320                 }
321                 data[i] = Certificate.getBySerial(rs.getString(1));
322             }
323             rs.close();
324             return data;
325         } catch (SQLException e) {
326             e.printStackTrace();
327         }
328
329         return null;
330     }
331
332     public boolean isValidDomain(String domainname) {
333         for (Domain d : getDomains()) {
334             String sfx = d.getSuffix();
335             if (domainname.equals(sfx) || domainname.endsWith("." + sfx)) {
336                 return true;
337             }
338         }
339         return false;
340     }
341
342     public boolean isValidEmail(String email) {
343         for (EmailAddress em : getEmails()) {
344             if (em.getAddress().equals(email)) {
345                 return true;
346             }
347         }
348         return false;
349     }
350
351     public boolean isValidName(String name) {
352         return getName().matches(name);
353     }
354
355     public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
356         try {
357             EmailAddress[] adrs = getEmails();
358             for (int i = 0; i < adrs.length; i++) {
359                 if (adrs[i].getAddress().equals(newMail.getAddress())) {
360                     if ( !adrs[i].isVerified()) {
361                         throw new GigiApiException("Email not verified.");
362                     }
363                     PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET email=? WHERE id=?");
364                     ps.setString(1, newMail.getAddress());
365                     ps.setInt(2, getId());
366                     ps.execute();
367                     email = newMail.getAddress();
368                     return;
369                 }
370             }
371             throw new GigiApiException("Given address not an address of the user.");
372         } catch (SQLException e) {
373             throw new GigiApiException(e);
374         }
375     }
376
377     public void deleteEmail(EmailAddress mail) throws GigiApiException {
378         if (getEmail().equals(mail.getAddress())) {
379             throw new GigiApiException("Can't delete user's default e-mail.");
380         }
381         EmailAddress[] emails = getEmails();
382         for (int i = 0; i < emails.length; i++) {
383             if (emails[i].getId() == mail.getId()) {
384                 try {
385                     PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE emails SET deleted=? WHERE id=?");
386                     ps.setDate(1, new Date(System.currentTimeMillis()));
387                     ps.setInt(2, mail.getId());
388                     ps.execute();
389                 } catch (SQLException e) {
390                     e.printStackTrace();
391                     throw new GigiApiException(e);
392                 }
393                 return;
394             }
395         }
396         throw new GigiApiException("Email not one of user's email addresses.");
397     }
398
399     public Assurance[] getReceivedAssurances() throws SQLException {
400         if (receivedAssurances == null) {
401             PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `to`=? AND deleted=0");
402             query.setInt(1, getId());
403             ResultSet res = query.executeQuery();
404             res.last();
405             Assurance[] assurances = new Assurance[res.getRow()];
406             res.beforeFirst();
407             for (int i = 0; i < assurances.length; i++) {
408                 res.next();
409                 assurances[i] = new Assurance(res);
410             }
411             this.receivedAssurances = assurances;
412             return assurances;
413         }
414         return receivedAssurances;
415     }
416
417     public Assurance[] getMadeAssurances() throws SQLException {
418         if (madeAssurances == null) {
419             PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `from`=? AND deleted=0");
420             query.setInt(1, getId());
421             ResultSet res = query.executeQuery();
422             res.last();
423             Assurance[] assurances = new Assurance[res.getRow()];
424             res.beforeFirst();
425             for (int i = 0; i < assurances.length; i++) {
426                 res.next();
427                 assurances[i] = new Assurance(res);
428             }
429             this.madeAssurances = assurances;
430             return assurances;
431         }
432         return madeAssurances;
433     }
434
435     public void invalidateMadeAssurances() {
436         madeAssurances = null;
437     }
438
439     public void invalidateReceivedAssurances() {
440         receivedAssurances = null;
441     }
442
443     public void updateUserData() throws SQLException, GigiApiException {
444         synchronized (Notary.class) {
445             if (getAssurancePoints() != 0) {
446                 throw new GigiApiException("No change after assurance allowed.");
447             }
448             PreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?");
449             update.setString(1, getFname());
450             update.setString(2, getLname());
451             update.setString(3, getMname());
452             update.setString(4, getSuffix());
453             update.setDate(5, getDob());
454             update.setInt(6, getId());
455             update.executeUpdate();
456         }
457     }
458
459     public Locale getPreferredLocale() {
460         return locale;
461     }
462
463     public void setPreferredLocale(Locale locale) {
464         this.locale = locale;
465
466     }
467
468     public boolean wantsDirectoryListing() throws SQLException {
469         PreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT listme FROM users WHERE id=?");
470         get.setInt(1, getId());
471         ResultSet exec = get.executeQuery();
472         exec.next();
473         return exec.getBoolean("listme");
474     }
475
476     public String getContactInformation() throws SQLException {
477         PreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT contactinfo FROM users WHERE id=?");
478         get.setInt(1, getId());
479         ResultSet exec = get.executeQuery();
480         exec.next();
481         return exec.getString("contactinfo");
482     }
483
484     public void setDirectoryListing(boolean on) throws SQLException {
485         PreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET listme = ? WHERE id = ?");
486         update.setBoolean(1, on);
487         update.setInt(2, getId());
488         update.executeUpdate();
489     }
490
491     public void setContactInformation(String contactInfo) throws SQLException {
492         PreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET contactinfo = ? WHERE id = ?");
493         update.setString(1, contactInfo);
494         update.setInt(2, getId());
495         update.executeUpdate();
496     }
497
498     private static ObjectCache<User> myCache = new ObjectCache<>();
499
500     public static User getById(int id) {
501         User u = myCache.get(id);
502         if (u == null) {
503             synchronized (User.class) {
504                 myCache.put(u = new User(id));
505             }
506         }
507         return u;
508     }
509 }