1 package org.cacert.gigi.dbObjects;
4 import java.util.Calendar;
5 import java.util.Collections;
6 import java.util.HashSet;
7 import java.util.Locale;
10 import org.cacert.gigi.GigiApiException;
11 import org.cacert.gigi.database.DatabaseConnection;
12 import org.cacert.gigi.database.GigiPreparedStatement;
13 import org.cacert.gigi.database.GigiResultSet;
14 import org.cacert.gigi.localisation.Language;
15 import org.cacert.gigi.util.Notary;
16 import org.cacert.gigi.util.PasswordHash;
17 import org.cacert.gigi.util.PasswordStrengthChecker;
19 public class User implements IdCachable {
23 private Name name = new Name(null, null, null, null);
29 private Assurance[] receivedAssurances, madeAssurances;
31 private Locale locale;
33 private Set<Group> groups = new HashSet<>();
35 private User(int id) {
40 private void updateName(int id) {
41 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `fname`, `lname`,`mname`, `suffix`, `dob`, `email`, `language` FROM `users` WHERE id=?");
43 GigiResultSet rs = ps.executeQuery();
45 name = new Name(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4));
47 email = rs.getString(6);
48 String localeStr = rs.getString(7);
49 if (localeStr == null || localeStr.equals("")) {
50 locale = Locale.getDefault();
52 locale = Language.getLocaleFromString(localeStr);
56 GigiPreparedStatement psg = DatabaseConnection.getInstance().prepare("SELECT permission FROM user_groups WHERE user=? AND deleted is NULL");
58 GigiResultSet rs2 = psg.executeQuery();
60 groups.add(Group.getByString(rs2.getString(1)));
71 public String getFname() {
75 public String getLname() {
79 public String getMname() {
83 public Name getName() {
87 public void setMname(String mname) {
88 this.name.mname = mname;
91 public String getSuffix() {
95 public void setSuffix(String suffix) {
96 this.name.suffix = suffix;
99 public Date getDob() {
103 public void setDob(Date dob) {
107 public String getEmail() {
111 public void setEmail(String email) {
115 public void setId(int id) {
119 public void setFname(String fname) {
120 this.name.fname = fname;
123 public void setLname(String lname) {
124 this.name.lname = lname;
127 public void insert(String password) {
129 throw new Error("refusing to insert");
131 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("insert into `users` set `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `created`=NOW(), locked=0, `language`=?");
132 query.setString(1, email);
133 query.setString(2, PasswordHash.hash(password));
134 query.setString(3, name.fname);
135 query.setString(4, name.mname);
136 query.setString(5, name.lname);
137 query.setString(6, name.suffix);
138 query.setDate(7, new java.sql.Date(dob.getTime()));
139 query.setString(8, locale.toString());
140 synchronized (User.class) {
142 id = query.lastInsertId();
147 public void changePassword(String oldPass, String newPass) throws GigiApiException {
148 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `password` FROM users WHERE id=?");
150 GigiResultSet rs = ps.executeQuery();
152 throw new GigiApiException("User not found... very bad.");
154 if ( !PasswordHash.verifyHash(oldPass, rs.getString(1))) {
155 throw new GigiApiException("Old password does not match.");
158 PasswordStrengthChecker.assertStrongPassword(newPass, this);
159 ps = DatabaseConnection.getInstance().prepare("UPDATE users SET `password`=? WHERE id=?");
160 ps.setString(1, PasswordHash.hash(newPass));
162 if (ps.executeUpdate() != 1) {
163 throw new GigiApiException("Password update failed.");
167 public boolean canAssure() {
168 if ( !isOfAge(14)) { // PoJAM
171 if (getAssurancePoints() < 100) {
175 return hasPassedCATS();
179 public boolean hasPassedCATS() {
180 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `cats_passed` where `user_id`=?");
182 GigiResultSet rs = query.executeQuery();
190 public int getAssurancePoints() {
191 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT sum(points) FROM `notary` where `to`=? AND `deleted`=0");
193 GigiResultSet rs = query.executeQuery();
196 points = rs.getInt(1);
202 public int getExperiencePoints() {
203 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0");
205 GigiResultSet rs = query.executeQuery();
208 points = rs.getInt(1) * 2;
215 public boolean equals(Object obj) {
216 if ( !(obj instanceof User)) {
220 return name.equals(s.name) && email.equals(s.email) && dob.toString().equals(s.dob.toString()); // This
229 * Gets the maximum allowed points NOW. Note that an assurance needs to
230 * re-check PoJam as it has taken place in the past.
232 * @return the maximal points @
234 public int getMaxAssurePoints() {
239 int exp = getExperiencePoints();
260 public boolean isOfAge(int desiredAge) {
261 Calendar c = Calendar.getInstance();
263 int year = c.get(Calendar.YEAR);
264 int month = c.get(Calendar.MONTH);
265 int day = c.get(Calendar.DAY_OF_MONTH);
266 c.set(year, month, day);
267 c.add(Calendar.YEAR, desiredAge);
268 return System.currentTimeMillis() >= c.getTime().getTime();
271 public EmailAddress[] getEmails() {
272 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM emails WHERE memid=? AND deleted=0");
274 GigiResultSet rs = ps.executeQuery();
276 int count = rs.getRow();
277 EmailAddress[] data = new EmailAddress[count];
279 for (int i = 0; i < data.length; i++) {
281 throw new Error("Internal sql api violation.");
283 data[i] = EmailAddress.getById(rs.getInt(1));
290 public Domain[] getDomains() {
291 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM domains WHERE memid=? AND deleted IS NULL");
293 GigiResultSet rs = ps.executeQuery();
295 int count = rs.getRow();
296 Domain[] data = new Domain[count];
298 for (int i = 0; i < data.length; i++) {
300 throw new Error("Internal sql api violation.");
302 data[i] = Domain.getById(rs.getInt(1));
309 public Certificate[] getCertificates() {
310 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT serial FROM certs WHERE memid=? AND revoked=0");
312 GigiResultSet rs = ps.executeQuery();
314 int count = rs.getRow();
315 Certificate[] data = new Certificate[count];
317 for (int i = 0; i < data.length; i++) {
319 throw new Error("Internal sql api violation.");
321 data[i] = Certificate.getBySerial(rs.getString(1));
328 public boolean isValidDomain(String domainname) {
329 for (Domain d : getDomains()) {
330 String sfx = d.getSuffix();
331 if (domainname.equals(sfx) || domainname.endsWith("." + sfx)) {
338 public boolean isValidEmail(String email) {
339 for (EmailAddress em : getEmails()) {
340 if (em.getAddress().equals(email)) {
347 public boolean isValidName(String name) {
348 return getName().matches(name);
351 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
352 EmailAddress[] adrs = getEmails();
353 for (int i = 0; i < adrs.length; i++) {
354 if (adrs[i].getAddress().equals(newMail.getAddress())) {
355 if ( !adrs[i].isVerified()) {
356 throw new GigiApiException("Email not verified.");
358 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET email=? WHERE id=?");
359 ps.setString(1, newMail.getAddress());
360 ps.setInt(2, getId());
362 email = newMail.getAddress();
366 throw new GigiApiException("Given address not an address of the user.");
369 public void deleteEmail(EmailAddress mail) throws GigiApiException {
370 if (getEmail().equals(mail.getAddress())) {
371 throw new GigiApiException("Can't delete user's default e-mail.");
373 EmailAddress[] emails = getEmails();
374 for (int i = 0; i < emails.length; i++) {
375 if (emails[i].getId() == mail.getId()) {
376 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE emails SET deleted=? WHERE id=?");
377 ps.setDate(1, new Date(System.currentTimeMillis()));
378 ps.setInt(2, mail.getId());
383 throw new GigiApiException("Email not one of user's email addresses.");
386 public Assurance[] getReceivedAssurances() {
387 if (receivedAssurances == null) {
388 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `to`=? AND deleted=0");
389 query.setInt(1, getId());
390 GigiResultSet res = query.executeQuery();
392 Assurance[] assurances = new Assurance[res.getRow()];
394 for (int i = 0; i < assurances.length; i++) {
396 assurances[i] = new Assurance(res);
398 this.receivedAssurances = assurances;
401 return receivedAssurances;
404 public Assurance[] getMadeAssurances() {
405 if (madeAssurances == null) {
406 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `from`=? AND deleted=0");
407 query.setInt(1, getId());
408 GigiResultSet res = query.executeQuery();
410 Assurance[] assurances = new Assurance[res.getRow()];
412 for (int i = 0; i < assurances.length; i++) {
414 assurances[i] = new Assurance(res);
416 this.madeAssurances = assurances;
419 return madeAssurances;
422 public void invalidateMadeAssurances() {
423 madeAssurances = null;
426 public void invalidateReceivedAssurances() {
427 receivedAssurances = null;
430 public void updateUserData() throws GigiApiException {
431 synchronized (Notary.class) {
432 if (getAssurancePoints() != 0) {
433 throw new GigiApiException("No change after assurance allowed.");
435 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?");
436 update.setString(1, getFname());
437 update.setString(2, getLname());
438 update.setString(3, getMname());
439 update.setString(4, getSuffix());
440 update.setDate(5, getDob());
441 update.setInt(6, getId());
442 update.executeUpdate();
446 public Locale getPreferredLocale() {
450 public void setPreferredLocale(Locale locale) {
451 this.locale = locale;
455 public boolean wantsDirectoryListing() {
456 GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT listme FROM users WHERE id=?");
457 get.setInt(1, getId());
458 GigiResultSet exec = get.executeQuery();
460 return exec.getBoolean("listme");
463 public String getContactInformation() {
464 GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT contactinfo FROM users WHERE id=?");
465 get.setInt(1, getId());
466 GigiResultSet exec = get.executeQuery();
468 return exec.getString("contactinfo");
471 public void setDirectoryListing(boolean on) {
472 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET listme = ? WHERE id = ?");
473 update.setBoolean(1, on);
474 update.setInt(2, getId());
475 update.executeUpdate();
478 public void setContactInformation(String contactInfo) {
479 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET contactinfo = ? WHERE id = ?");
480 update.setString(1, contactInfo);
481 update.setInt(2, getId());
482 update.executeUpdate();
485 public boolean isInGroup(Group g) {
486 return groups.contains(g);
489 public Set<Group> getGroups() {
490 return Collections.unmodifiableSet(groups);
493 public void grantGroup(User granter, Group toGrant) throws GigiApiException {
495 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO user_groups SET user=?, permission=?, grantedby=?");
496 ps.setInt(1, getId());
497 ps.setString(2, toGrant.getDatabaseName());
498 ps.setInt(3, granter.getId());
502 public void revokeGroup(User revoker, Group toRevoke) throws GigiApiException {
503 groups.remove(toRevoke);
504 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE user_groups SET deleted=CURRENT_TIMESTAMP, revokedby=? WHERE deleted is NULL AND permission=? AND user=?");
505 ps.setInt(1, revoker.getId());
506 ps.setString(2, toRevoke.getDatabaseName());
507 ps.setInt(3, getId());
511 private static ObjectCache<User> myCache = new ObjectCache<>();
513 public static synchronized User getById(int id) {
514 User u = myCache.get(id);
516 myCache.put(u = new User(id));