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