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