]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/User.java
WIP orga-things
[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` is NULL");
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` is NULL");
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 boolean isValidName(String name) {
251         return getName().matches(name);
252     }
253
254     public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
255         EmailAddress[] adrs = getEmails();
256         for (int i = 0; i < adrs.length; i++) {
257             if (adrs[i].getAddress().equals(newMail.getAddress())) {
258                 if ( !adrs[i].isVerified()) {
259                     throw new GigiApiException("Email not verified.");
260                 }
261                 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET email=? WHERE id=?");
262                 ps.setString(1, newMail.getAddress());
263                 ps.setInt(2, getId());
264                 ps.execute();
265                 email = newMail.getAddress();
266                 return;
267             }
268         }
269         throw new GigiApiException("Given address not an address of the user.");
270     }
271
272     public void deleteEmail(EmailAddress mail) throws GigiApiException {
273         if (getEmail().equals(mail.getAddress())) {
274             throw new GigiApiException("Can't delete user's default e-mail.");
275         }
276         EmailAddress[] emails = getEmails();
277         for (int i = 0; i < emails.length; i++) {
278             if (emails[i].getId() == mail.getId()) {
279                 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE emails SET deleted=? WHERE id=?");
280                 ps.setDate(1, new Date(System.currentTimeMillis()));
281                 ps.setInt(2, mail.getId());
282                 ps.execute();
283                 return;
284             }
285         }
286         throw new GigiApiException("Email not one of user's email addresses.");
287     }
288
289     public Assurance[] getReceivedAssurances() {
290         if (receivedAssurances == null) {
291             GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `to`=? AND deleted IS NULL");
292             query.setInt(1, getId());
293             GigiResultSet res = query.executeQuery();
294             res.last();
295             Assurance[] assurances = new Assurance[res.getRow()];
296             res.beforeFirst();
297             for (int i = 0; i < assurances.length; i++) {
298                 res.next();
299                 assurances[i] = new Assurance(res);
300             }
301             this.receivedAssurances = assurances;
302             return assurances;
303         }
304         return receivedAssurances;
305     }
306
307     public Assurance[] getMadeAssurances() {
308         if (madeAssurances == null) {
309             GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `from`=? AND deleted is NULL");
310             query.setInt(1, getId());
311             GigiResultSet res = query.executeQuery();
312             res.last();
313             Assurance[] assurances = new Assurance[res.getRow()];
314             res.beforeFirst();
315             for (int i = 0; i < assurances.length; i++) {
316                 res.next();
317                 assurances[i] = new Assurance(res);
318             }
319             this.madeAssurances = assurances;
320             return assurances;
321         }
322         return madeAssurances;
323     }
324
325     public void invalidateMadeAssurances() {
326         madeAssurances = null;
327     }
328
329     public void invalidateReceivedAssurances() {
330         receivedAssurances = null;
331     }
332
333     public void updateUserData() throws GigiApiException {
334         synchronized (Notary.class) {
335             if (getAssurancePoints() != 0) {
336                 throw new GigiApiException("No change after assurance allowed.");
337             }
338             GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?");
339             update.setString(1, getFname());
340             update.setString(2, getLname());
341             update.setString(3, getMname());
342             update.setString(4, getSuffix());
343             update.setDate(5, getDob());
344             update.setInt(6, getId());
345             update.executeUpdate();
346         }
347     }
348
349     public Locale getPreferredLocale() {
350         return locale;
351     }
352
353     public void setPreferredLocale(Locale locale) {
354         this.locale = locale;
355
356     }
357
358     public boolean wantsDirectoryListing() {
359         GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT listme FROM users WHERE id=?");
360         get.setInt(1, getId());
361         GigiResultSet exec = get.executeQuery();
362         exec.next();
363         return exec.getBoolean("listme");
364     }
365
366     public String getContactInformation() {
367         GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT contactinfo FROM users WHERE id=?");
368         get.setInt(1, getId());
369         GigiResultSet exec = get.executeQuery();
370         exec.next();
371         return exec.getString("contactinfo");
372     }
373
374     public void setDirectoryListing(boolean on) {
375         GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET listme = ? WHERE id = ?");
376         update.setBoolean(1, on);
377         update.setInt(2, getId());
378         update.executeUpdate();
379     }
380
381     public void setContactInformation(String contactInfo) {
382         GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET contactinfo = ? WHERE id = ?");
383         update.setString(1, contactInfo);
384         update.setInt(2, getId());
385         update.executeUpdate();
386     }
387
388     public boolean isInGroup(Group g) {
389         return groups.contains(g);
390     }
391
392     public Set<Group> getGroups() {
393         return Collections.unmodifiableSet(groups);
394     }
395
396     public void grantGroup(User granter, Group toGrant) {
397         groups.add(toGrant);
398         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO user_groups SET user=?, permission=?, grantedby=?");
399         ps.setInt(1, getId());
400         ps.setString(2, toGrant.getDatabaseName());
401         ps.setInt(3, granter.getId());
402         ps.execute();
403     }
404
405     public void revokeGroup(User revoker, Group toRevoke) {
406         groups.remove(toRevoke);
407         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE user_groups SET deleted=CURRENT_TIMESTAMP, revokedby=? WHERE deleted is NULL AND permission=? AND user=?");
408         ps.setInt(1, revoker.getId());
409         ps.setString(2, toRevoke.getDatabaseName());
410         ps.setInt(3, getId());
411         ps.execute();
412     }
413
414     public static synchronized User getById(int id) {
415         CertificateOwner co = CertificateOwner.getById(id);
416         if (co instanceof User) {
417             return (User) co;
418         }
419         return null;
420     }
421
422     public boolean canIssue(CertificateProfile p) {
423         switch (p.getCAId()) {
424         case 0:
425             return true;
426         case 1:
427             return getAssurancePoints() > 50;
428         case 2:
429             return getAssurancePoints() > 50 && isInGroup(Group.getByString("codesigning"));
430         case 3:
431         case 4:
432             return false; // has an orga
433         default:
434             return false;
435         }
436     }
437 }