]> WPIA git - gigi.git/blob - src/org/cacert/gigi/User.java
ADD: Enable Language selection.
[gigi.git] / src / org / cacert / gigi / User.java
1 package org.cacert.gigi;
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.database.DatabaseConnection;
11 import org.cacert.gigi.localisation.Language;
12 import org.cacert.gigi.util.Notary;
13 import org.cacert.gigi.util.PasswordHash;
14 import org.cacert.gigi.util.PasswordStrengthChecker;
15
16 public class User {
17
18     private int id;
19
20     private Name name = new Name(null, null, null, null);
21
22     private Date dob;
23
24     private String email;
25
26     private Assurance[] receivedAssurances, madeAssurances;
27
28     private Locale locale;
29
30     public User(int id) {
31         this.id = id;
32         updateName(id);
33     }
34
35     private void updateName(int id) {
36         try {
37             PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `fname`, `lname`,`mname`, `suffix`, `dob`, `email`, `language` FROM `users` WHERE id=?");
38             ps.setInt(1, id);
39             ResultSet rs = ps.executeQuery();
40             if (rs.next()) {
41                 name = new Name(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4));
42                 dob = rs.getDate(5);
43                 email = rs.getString(6);
44                 String localeStr = rs.getString(7);
45                 if (localeStr == null || localeStr.equals("")) {
46                     locale = Locale.getDefault();
47                 } else {
48                     locale = Language.getLocaleFromString(localeStr);
49                 }
50             }
51             rs.close();
52         } catch (SQLException e) {
53             e.printStackTrace();
54         }
55     }
56
57     public User() {}
58
59     public int getId() {
60         return id;
61     }
62
63     public String getFname() {
64         return name.fname;
65     }
66
67     public String getLname() {
68         return name.lname;
69     }
70
71     public String getMname() {
72         return name.mname;
73     }
74
75     public Name getName() {
76         return name;
77     }
78
79     public void setMname(String mname) {
80         this.name.mname = mname;
81     }
82
83     public String getSuffix() {
84         return name.suffix;
85     }
86
87     public void setSuffix(String suffix) {
88         this.name.suffix = suffix;
89     }
90
91     public Date getDob() {
92         return dob;
93     }
94
95     public void setDob(Date dob) {
96         this.dob = dob;
97     }
98
99     public String getEmail() {
100         return email;
101     }
102
103     public void setEmail(String email) {
104         this.email = email;
105     }
106
107     public void setId(int id) {
108         this.id = id;
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) throws SQLException {
120         if (id != 0) {
121             throw new Error("refusing to insert");
122         }
123         PreparedStatement query = DatabaseConnection.getInstance().prepare("insert into `users` set `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `created`=NOW(), locked=0, `language`=?");
124         query.setString(1, email);
125         query.setString(2, PasswordHash.hash(password));
126         query.setString(3, name.fname);
127         query.setString(4, name.mname);
128         query.setString(5, name.lname);
129         query.setString(6, name.suffix);
130         query.setDate(7, new java.sql.Date(dob.getTime()));
131         query.setString(8, locale.toString());
132         query.execute();
133         id = DatabaseConnection.lastInsertId(query);
134     }
135
136     public void changePassword(String oldPass, String newPass) throws GigiApiException {
137         try {
138             PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `password` FROM users WHERE id=?");
139             ps.setInt(1, id);
140             ResultSet rs = ps.executeQuery();
141             if ( !rs.next()) {
142                 throw new GigiApiException("User not found... very bad.");
143             }
144             if ( !PasswordHash.verifyHash(oldPass, rs.getString(1))) {
145                 throw new GigiApiException("Old password does not match.");
146             }
147             rs.close();
148             PasswordStrengthChecker.assertStrongPassword(newPass, this);
149             ps = DatabaseConnection.getInstance().prepare("UPDATE users SET `password`=? WHERE id=?");
150             ps.setString(1, PasswordHash.hash(newPass));
151             ps.setInt(2, id);
152             if (ps.executeUpdate() != 1) {
153                 throw new GigiApiException("Password update failed.");
154             }
155         } catch (SQLException e) {
156             throw new GigiApiException(e);
157         }
158     }
159
160     public boolean canAssure() throws SQLException {
161         if (getAssurancePoints() < 100) {
162             return false;
163         }
164
165         return hasPassedCATS();
166
167     }
168
169     public boolean hasPassedCATS() throws SQLException {
170         PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `cats_passed` where `user_id`=?");
171         query.setInt(1, id);
172         ResultSet rs = query.executeQuery();
173         if (rs.next()) {
174             return true;
175         } else {
176             return false;
177         }
178     }
179
180     public int getAssurancePoints() throws SQLException {
181         PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT sum(points) FROM `notary` where `to`=? AND `deleted`=0");
182         query.setInt(1, id);
183         ResultSet rs = query.executeQuery();
184         int points = 0;
185         if (rs.next()) {
186             points = rs.getInt(1);
187         }
188         rs.close();
189         return points;
190     }
191
192     public int getExperiencePoints() throws SQLException {
193         PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0");
194         query.setInt(1, id);
195         ResultSet rs = query.executeQuery();
196         int points = 0;
197         if (rs.next()) {
198             points = rs.getInt(1) * 2;
199         }
200         rs.close();
201         return points;
202     }
203
204     @Override
205     public boolean equals(Object obj) {
206         if ( !(obj instanceof User)) {
207             return false;
208         }
209         User s = (User) obj;
210         return name.equals(s.name) && email.equals(s.email) && dob.toString().equals(s.dob.toString()); // This
211                                                                                                         // is
212                                                                                                         // due
213                                                                                                         // to
214                                                                                                         // day
215                                                                                                         // cutoff
216     }
217
218     /**
219      * Gets the maximum allowed points NOW. Note that an assurance needs to
220      * re-check PoJam as it has taken place in the past.
221      * 
222      * @return the maximal points
223      * @throws SQLException
224      */
225     public int getMaxAssurePoints() throws SQLException {
226         int exp = getExperiencePoints();
227         int points = 10;
228         Calendar c = Calendar.getInstance();
229         c.setTime(dob);
230         int year = c.get(Calendar.YEAR);
231         int month = c.get(Calendar.MONTH);
232         int day = c.get(Calendar.DAY_OF_MONTH);
233         c.set(year + 18, month, day);
234         if (System.currentTimeMillis() < c.getTime().getTime()) {
235             return points; // not 18 Years old.
236         }
237
238         if (exp >= 10) {
239             points += 5;
240         }
241         if (exp >= 20) {
242             points += 5;
243         }
244         if (exp >= 30) {
245             points += 5;
246         }
247         if (exp >= 40) {
248             points += 5;
249         }
250         if (exp >= 50) {
251             points += 5;
252         }
253         return points;
254     }
255
256     public static User getById(int id) {
257         return new User(id);
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                 updateUserData();
447                 throw new GigiApiException("No change after assurance allowed.");
448             }
449             PreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?");
450             update.setString(1, getFname());
451             update.setString(2, getLname());
452             update.setString(3, getMname());
453             update.setString(4, getSuffix());
454             update.setDate(5, getDob());
455             update.setInt(6, getId());
456             update.executeUpdate();
457         }
458     }
459
460     public Locale getPreferredLocale() {
461         return locale;
462     }
463
464     public void setPreferredLocale(Locale locale) {
465         this.locale = locale;
466
467     }
468
469     public boolean wantsDirectoryListing() throws SQLException {
470         PreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT listme FROM users WHERE id=?");
471         get.setInt(1, getId());
472         ResultSet exec = get.executeQuery();
473         exec.next();
474         return exec.getBoolean("listme");
475     }
476
477     public String getContactInformation() throws SQLException {
478         PreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT contactinfo FROM users WHERE id=?");
479         get.setInt(1, getId());
480         ResultSet exec = get.executeQuery();
481         exec.next();
482         return exec.getString("contactinfo");
483     }
484
485     public void setDirectoryListing(boolean on) throws SQLException {
486         PreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET listme = ? WHERE id = ?");
487         update.setBoolean(1, on);
488         update.setInt(2, getId());
489         update.executeUpdate();
490     }
491
492     public void setContactInformation(String contactInfo) throws SQLException {
493         PreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET contactinfo = ? WHERE id = ?");
494         update.setString(1, contactInfo);
495         update.setInt(2, getId());
496         update.executeUpdate();
497     }
498
499 }