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