]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/User.java
412f02ca601f42b6e29b2a0fbcc0425a4548d041
[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         ps.executeUpdate();
145     }
146
147     public void setName(Name name) {
148         this.name = name;
149     }
150
151     public boolean canAssure() {
152         if ( !isOfAge(14)) { // PoJAM
153             return false;
154         }
155         if (getAssurancePoints() < 100) {
156             return false;
157         }
158
159         return hasPassedCATS();
160
161     }
162
163     public boolean hasPassedCATS() {
164         GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `cats_passed` where `user_id`=?");
165         query.setInt(1, getId());
166         GigiResultSet rs = query.executeQuery();
167         if (rs.next()) {
168             return true;
169         } else {
170             return false;
171         }
172     }
173
174     public int getAssurancePoints() {
175         GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT sum(points) FROM `notary` where `to`=? AND `deleted` is NULL");
176         query.setInt(1, getId());
177         GigiResultSet rs = query.executeQuery();
178         int points = 0;
179         if (rs.next()) {
180             points = rs.getInt(1);
181         }
182         rs.close();
183         return points;
184     }
185
186     public int getExperiencePoints() {
187         GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT count(*) FROM `notary` where `from`=? AND `deleted` is NULL");
188         query.setInt(1, getId());
189         GigiResultSet rs = query.executeQuery();
190         int points = 0;
191         if (rs.next()) {
192             points = rs.getInt(1) * 2;
193         }
194         rs.close();
195         return points;
196     }
197
198     @Override
199     public boolean equals(Object obj) {
200         if ( !(obj instanceof User)) {
201             return false;
202         }
203         User s = (User) obj;
204         return name.equals(s.name) && email.equals(s.email) && dob.toString().equals(s.dob.toString()); // This
205                                                                                                         // is
206                                                                                                         // due
207                                                                                                         // to
208                                                                                                         // day
209                                                                                                         // cutoff
210     }
211
212     /**
213      * Gets the maximum allowed points NOW. Note that an assurance needs to
214      * re-check PoJam as it has taken place in the past.
215      * 
216      * @return the maximal points @
217      */
218     public int getMaxAssurePoints() {
219         if ( !isOfAge(18)) {
220             return 10; // PoJAM
221         }
222
223         int exp = getExperiencePoints();
224         int points = 10;
225
226         if (exp >= 10) {
227             points += 5;
228         }
229         if (exp >= 20) {
230             points += 5;
231         }
232         if (exp >= 30) {
233             points += 5;
234         }
235         if (exp >= 40) {
236             points += 5;
237         }
238         if (exp >= 50) {
239             points += 5;
240         }
241         return points;
242     }
243
244     public boolean isOfAge(int desiredAge) {
245         Calendar c = Calendar.getInstance();
246         c.setTime(dob);
247         int year = c.get(Calendar.YEAR);
248         int month = c.get(Calendar.MONTH);
249         int day = c.get(Calendar.DAY_OF_MONTH);
250         c.set(year, month, day);
251         c.add(Calendar.YEAR, desiredAge);
252         return System.currentTimeMillis() >= c.getTime().getTime();
253     }
254
255     public boolean isValidName(String name) {
256         return getName().matches(name);
257     }
258
259     public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
260         EmailAddress[] adrs = getEmails();
261         for (int i = 0; i < adrs.length; i++) {
262             if (adrs[i].getAddress().equals(newMail.getAddress())) {
263                 if ( !adrs[i].isVerified()) {
264                     throw new GigiApiException("Email not verified.");
265                 }
266                 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET email=? WHERE id=?");
267                 ps.setString(1, newMail.getAddress());
268                 ps.setInt(2, getId());
269                 ps.execute();
270                 email = newMail.getAddress();
271                 return;
272             }
273         }
274         throw new GigiApiException("Given address not an address of the user.");
275     }
276
277     public void deleteEmail(EmailAddress mail) throws GigiApiException {
278         if (getEmail().equals(mail.getAddress())) {
279             throw new GigiApiException("Can't delete user's default e-mail.");
280         }
281         EmailAddress[] emails = getEmails();
282         for (int i = 0; i < emails.length; i++) {
283             if (emails[i].getId() == mail.getId()) {
284                 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE emails SET deleted=? WHERE id=?");
285                 ps.setDate(1, new Date(System.currentTimeMillis()));
286                 ps.setInt(2, mail.getId());
287                 ps.execute();
288                 return;
289             }
290         }
291         throw new GigiApiException("Email not one of user's email addresses.");
292     }
293
294     public Assurance[] getReceivedAssurances() {
295         if (receivedAssurances == null) {
296             GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `to`=? AND deleted IS NULL");
297             query.setInt(1, getId());
298             GigiResultSet res = query.executeQuery();
299             res.last();
300             Assurance[] assurances = new Assurance[res.getRow()];
301             res.beforeFirst();
302             for (int i = 0; i < assurances.length; i++) {
303                 res.next();
304                 assurances[i] = new Assurance(res);
305             }
306             this.receivedAssurances = assurances;
307             return assurances;
308         }
309         return receivedAssurances;
310     }
311
312     public Assurance[] getMadeAssurances() {
313         if (madeAssurances == null) {
314             GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `from`=? AND deleted is NULL");
315             query.setInt(1, getId());
316             GigiResultSet res = query.executeQuery();
317             res.last();
318             Assurance[] assurances = new Assurance[res.getRow()];
319             res.beforeFirst();
320             for (int i = 0; i < assurances.length; i++) {
321                 res.next();
322                 assurances[i] = new Assurance(res);
323             }
324             this.madeAssurances = assurances;
325             return assurances;
326         }
327         return madeAssurances;
328     }
329
330     public void invalidateMadeAssurances() {
331         madeAssurances = null;
332     }
333
334     public void invalidateReceivedAssurances() {
335         receivedAssurances = null;
336     }
337
338     public void updateUserData() throws GigiApiException {
339         synchronized (Notary.class) {
340             if (getAssurancePoints() != 0) {
341                 throw new GigiApiException("No change after assurance allowed.");
342             }
343             GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?");
344             update.setString(1, getFname());
345             update.setString(2, getLname());
346             update.setString(3, getMname());
347             update.setString(4, getSuffix());
348             update.setDate(5, getDob());
349             update.setInt(6, getId());
350             update.executeUpdate();
351         }
352     }
353
354     public Locale getPreferredLocale() {
355         return locale;
356     }
357
358     public void setPreferredLocale(Locale locale) {
359         this.locale = locale;
360
361     }
362
363     public boolean wantsDirectoryListing() {
364         GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT listme FROM users WHERE id=?");
365         get.setInt(1, getId());
366         GigiResultSet exec = get.executeQuery();
367         exec.next();
368         return exec.getBoolean("listme");
369     }
370
371     public String getContactInformation() {
372         GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT contactinfo FROM users WHERE id=?");
373         get.setInt(1, getId());
374         GigiResultSet exec = get.executeQuery();
375         exec.next();
376         return exec.getString("contactinfo");
377     }
378
379     public void setDirectoryListing(boolean on) {
380         GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET listme = ? WHERE id = ?");
381         update.setBoolean(1, on);
382         update.setInt(2, getId());
383         update.executeUpdate();
384     }
385
386     public void setContactInformation(String contactInfo) {
387         GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET contactinfo = ? WHERE id = ?");
388         update.setString(1, contactInfo);
389         update.setInt(2, getId());
390         update.executeUpdate();
391     }
392
393     public boolean isInGroup(Group g) {
394         return groups.contains(g);
395     }
396
397     public Set<Group> getGroups() {
398         return Collections.unmodifiableSet(groups);
399     }
400
401     public void grantGroup(User granter, Group toGrant) {
402         groups.add(toGrant);
403         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO user_groups SET user=?, permission=?, grantedby=?");
404         ps.setInt(1, getId());
405         ps.setString(2, toGrant.getDatabaseName());
406         ps.setInt(3, granter.getId());
407         ps.execute();
408     }
409
410     public void revokeGroup(User revoker, Group toRevoke) {
411         groups.remove(toRevoke);
412         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE user_groups SET deleted=CURRENT_TIMESTAMP, revokedby=? WHERE deleted is NULL AND permission=? AND user=?");
413         ps.setInt(1, revoker.getId());
414         ps.setString(2, toRevoke.getDatabaseName());
415         ps.setInt(3, getId());
416         ps.execute();
417     }
418
419     public List<Organisation> getOrganisations() {
420         List<Organisation> orgas = new ArrayList<>();
421         GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT orgid FROM org_admin WHERE `memid`=? AND deleted is NULL");
422         query.setInt(1, getId());
423         GigiResultSet res = query.executeQuery();
424
425         while (res.next()) {
426             orgas.add(Organisation.getById(res.getInt(1)));
427         }
428         return orgas;
429     }
430
431     public static synchronized User getById(int id) {
432         CertificateOwner co = CertificateOwner.getById(id);
433         if (co instanceof User) {
434             return (User) co;
435         }
436         return null;
437     }
438
439     public static User getByEmail(String mail) {
440         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT users.id FROM users inner join certOwners on certOwners.id=users.id WHERE email=? AND deleted is null");
441         ps.setString(1, mail);
442         GigiResultSet rs = ps.executeQuery();
443         if ( !rs.next()) {
444             return null;
445         }
446         return User.getById(rs.getInt(1));
447     }
448
449     public static User[] findByEmail(String mail) {
450         LinkedList<User> results = new LinkedList<User>();
451         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");
452         ps.setString(1, mail);
453         GigiResultSet rs = ps.executeQuery();
454         while (rs.next()) {
455             results.add(User.getById(rs.getInt(1)));
456             System.out.println("Found user");
457         }
458         return results.toArray(new User[results.size()]);
459     }
460
461     public boolean canIssue(CertificateProfile p) {
462         switch (p.getCAId()) {
463         case 0:
464             return true;
465         case 1:
466             return getAssurancePoints() > 50;
467         case 2:
468             return getAssurancePoints() > 50 && isInGroup(Group.getByString("codesigning"));
469         case 3:
470         case 4:
471             return getOrganisations().size() > 0;
472         default:
473             return false;
474         }
475     }
476
477 }