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