1 package org.cacert.gigi.dbObjects;
4 import java.sql.PreparedStatement;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7 import java.util.Calendar;
8 import java.util.Collections;
9 import java.util.HashSet;
10 import java.util.Locale;
13 import org.cacert.gigi.GigiApiException;
14 import org.cacert.gigi.database.DatabaseConnection;
15 import org.cacert.gigi.localisation.Language;
16 import org.cacert.gigi.util.Notary;
17 import org.cacert.gigi.util.PasswordHash;
18 import org.cacert.gigi.util.PasswordStrengthChecker;
20 public class User implements IdCachable {
24 private Name name = new Name(null, null, null, null);
30 private Assurance[] receivedAssurances, madeAssurances;
32 private Locale locale;
34 private Set<Group> groups = new HashSet<>();
36 private User(int id) {
41 private void updateName(int id) {
43 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `fname`, `lname`,`mname`, `suffix`, `dob`, `email`, `language` FROM `users` WHERE id=?");
45 ResultSet rs = ps.executeQuery();
47 name = new Name(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4));
49 email = rs.getString(6);
50 String localeStr = rs.getString(7);
51 if (localeStr == null || localeStr.equals("")) {
52 locale = Locale.getDefault();
54 locale = Language.getLocaleFromString(localeStr);
58 PreparedStatement psg = DatabaseConnection.getInstance().prepare("SELECT permission FROM user_groups WHERE user=? AND deleted is NULL");
60 ResultSet rs2 = psg.executeQuery();
62 groups.add(Group.getByString(rs2.getString(1)));
65 } catch (SQLException e) {
76 public String getFname() {
80 public String getLname() {
84 public String getMname() {
88 public Name getName() {
92 public void setMname(String mname) {
93 this.name.mname = mname;
96 public String getSuffix() {
100 public void setSuffix(String suffix) {
101 this.name.suffix = suffix;
104 public Date getDob() {
108 public void setDob(Date dob) {
112 public String getEmail() {
116 public void setEmail(String email) {
120 public void setId(int id) {
124 public void setFname(String fname) {
125 this.name.fname = fname;
128 public void setLname(String lname) {
129 this.name.lname = lname;
132 public void insert(String password) throws SQLException {
134 throw new Error("refusing to insert");
136 PreparedStatement query = DatabaseConnection.getInstance().prepare("insert into `users` set `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `created`=NOW(), locked=0, `language`=?");
137 query.setString(1, email);
138 query.setString(2, PasswordHash.hash(password));
139 query.setString(3, name.fname);
140 query.setString(4, name.mname);
141 query.setString(5, name.lname);
142 query.setString(6, name.suffix);
143 query.setDate(7, new java.sql.Date(dob.getTime()));
144 query.setString(8, locale.toString());
145 synchronized (User.class) {
147 id = DatabaseConnection.lastInsertId(query);
152 public void changePassword(String oldPass, String newPass) throws GigiApiException {
154 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `password` FROM users WHERE id=?");
156 ResultSet rs = ps.executeQuery();
158 throw new GigiApiException("User not found... very bad.");
160 if ( !PasswordHash.verifyHash(oldPass, rs.getString(1))) {
161 throw new GigiApiException("Old password does not match.");
164 PasswordStrengthChecker.assertStrongPassword(newPass, this);
165 ps = DatabaseConnection.getInstance().prepare("UPDATE users SET `password`=? WHERE id=?");
166 ps.setString(1, PasswordHash.hash(newPass));
168 if (ps.executeUpdate() != 1) {
169 throw new GigiApiException("Password update failed.");
171 } catch (SQLException e) {
172 throw new GigiApiException(e);
176 public boolean canAssure() throws SQLException {
177 if ( !isOfAge(14)) { // PoJAM
180 if (getAssurancePoints() < 100) {
184 return hasPassedCATS();
188 public boolean hasPassedCATS() throws SQLException {
189 PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `cats_passed` where `user_id`=?");
191 ResultSet rs = query.executeQuery();
199 public int getAssurancePoints() throws SQLException {
200 PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT sum(points) FROM `notary` where `to`=? AND `deleted`=0");
202 ResultSet rs = query.executeQuery();
205 points = rs.getInt(1);
211 public int getExperiencePoints() throws SQLException {
212 PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0");
214 ResultSet rs = query.executeQuery();
217 points = rs.getInt(1) * 2;
224 public boolean equals(Object obj) {
225 if ( !(obj instanceof User)) {
229 return name.equals(s.name) && email.equals(s.email) && dob.toString().equals(s.dob.toString()); // This
238 * Gets the maximum allowed points NOW. Note that an assurance needs to
239 * re-check PoJam as it has taken place in the past.
241 * @return the maximal points
242 * @throws SQLException
244 public int getMaxAssurePoints() throws SQLException {
249 int exp = getExperiencePoints();
270 public boolean isOfAge(int desiredAge) {
271 Calendar c = Calendar.getInstance();
273 int year = c.get(Calendar.YEAR);
274 int month = c.get(Calendar.MONTH);
275 int day = c.get(Calendar.DAY_OF_MONTH);
276 c.set(year, month, day);
277 c.add(Calendar.YEAR, desiredAge);
278 return System.currentTimeMillis() >= c.getTime().getTime();
281 public EmailAddress[] getEmails() {
283 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM emails WHERE memid=? AND deleted=0");
285 ResultSet rs = ps.executeQuery();
287 int count = rs.getRow();
288 EmailAddress[] data = new EmailAddress[count];
290 for (int i = 0; i < data.length; i++) {
292 throw new Error("Internal sql api violation.");
294 data[i] = EmailAddress.getById(rs.getInt(1));
298 } catch (SQLException e) {
305 public Domain[] getDomains() {
307 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM domains WHERE memid=? AND deleted IS NULL");
309 ResultSet rs = ps.executeQuery();
311 int count = rs.getRow();
312 Domain[] data = new Domain[count];
314 for (int i = 0; i < data.length; i++) {
316 throw new Error("Internal sql api violation.");
318 data[i] = Domain.getById(rs.getInt(1));
322 } catch (SQLException e) {
329 public Certificate[] getCertificates() {
331 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT serial FROM certs WHERE memid=? AND revoked=0");
333 ResultSet rs = ps.executeQuery();
335 int count = rs.getRow();
336 Certificate[] data = new Certificate[count];
338 for (int i = 0; i < data.length; i++) {
340 throw new Error("Internal sql api violation.");
342 data[i] = Certificate.getBySerial(rs.getString(1));
346 } catch (SQLException e) {
353 public boolean isValidDomain(String domainname) {
354 for (Domain d : getDomains()) {
355 String sfx = d.getSuffix();
356 if (domainname.equals(sfx) || domainname.endsWith("." + sfx)) {
363 public boolean isValidEmail(String email) {
364 for (EmailAddress em : getEmails()) {
365 if (em.getAddress().equals(email)) {
372 public boolean isValidName(String name) {
373 return getName().matches(name);
376 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
378 EmailAddress[] adrs = getEmails();
379 for (int i = 0; i < adrs.length; i++) {
380 if (adrs[i].getAddress().equals(newMail.getAddress())) {
381 if ( !adrs[i].isVerified()) {
382 throw new GigiApiException("Email not verified.");
384 PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET email=? WHERE id=?");
385 ps.setString(1, newMail.getAddress());
386 ps.setInt(2, getId());
388 email = newMail.getAddress();
392 throw new GigiApiException("Given address not an address of the user.");
393 } catch (SQLException e) {
394 throw new GigiApiException(e);
398 public void deleteEmail(EmailAddress mail) throws GigiApiException {
399 if (getEmail().equals(mail.getAddress())) {
400 throw new GigiApiException("Can't delete user's default e-mail.");
402 EmailAddress[] emails = getEmails();
403 for (int i = 0; i < emails.length; i++) {
404 if (emails[i].getId() == mail.getId()) {
406 PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE emails SET deleted=? WHERE id=?");
407 ps.setDate(1, new Date(System.currentTimeMillis()));
408 ps.setInt(2, mail.getId());
410 } catch (SQLException e) {
412 throw new GigiApiException(e);
417 throw new GigiApiException("Email not one of user's email addresses.");
420 public Assurance[] getReceivedAssurances() throws SQLException {
421 if (receivedAssurances == null) {
422 PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `to`=? AND deleted=0");
423 query.setInt(1, getId());
424 ResultSet res = query.executeQuery();
426 Assurance[] assurances = new Assurance[res.getRow()];
428 for (int i = 0; i < assurances.length; i++) {
430 assurances[i] = new Assurance(res);
432 this.receivedAssurances = assurances;
435 return receivedAssurances;
438 public Assurance[] getMadeAssurances() throws SQLException {
439 if (madeAssurances == null) {
440 PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `from`=? AND deleted=0");
441 query.setInt(1, getId());
442 ResultSet res = query.executeQuery();
444 Assurance[] assurances = new Assurance[res.getRow()];
446 for (int i = 0; i < assurances.length; i++) {
448 assurances[i] = new Assurance(res);
450 this.madeAssurances = assurances;
453 return madeAssurances;
456 public void invalidateMadeAssurances() {
457 madeAssurances = null;
460 public void invalidateReceivedAssurances() {
461 receivedAssurances = null;
464 public void updateUserData() throws SQLException, GigiApiException {
465 synchronized (Notary.class) {
466 if (getAssurancePoints() != 0) {
467 throw new GigiApiException("No change after assurance allowed.");
469 PreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?");
470 update.setString(1, getFname());
471 update.setString(2, getLname());
472 update.setString(3, getMname());
473 update.setString(4, getSuffix());
474 update.setDate(5, getDob());
475 update.setInt(6, getId());
476 update.executeUpdate();
480 public Locale getPreferredLocale() {
484 public void setPreferredLocale(Locale locale) {
485 this.locale = locale;
489 public boolean wantsDirectoryListing() throws SQLException {
490 PreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT listme FROM users WHERE id=?");
491 get.setInt(1, getId());
492 ResultSet exec = get.executeQuery();
494 return exec.getBoolean("listme");
497 public String getContactInformation() throws SQLException {
498 PreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT contactinfo FROM users WHERE id=?");
499 get.setInt(1, getId());
500 ResultSet exec = get.executeQuery();
502 return exec.getString("contactinfo");
505 public void setDirectoryListing(boolean on) throws SQLException {
506 PreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET listme = ? WHERE id = ?");
507 update.setBoolean(1, on);
508 update.setInt(2, getId());
509 update.executeUpdate();
512 public void setContactInformation(String contactInfo) throws SQLException {
513 PreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET contactinfo = ? WHERE id = ?");
514 update.setString(1, contactInfo);
515 update.setInt(2, getId());
516 update.executeUpdate();
519 public boolean isInGroup(Group g) {
520 return groups.contains(g);
523 public Set<Group> getGroups() {
524 return Collections.unmodifiableSet(groups);
527 public void grantGroup(User granter, Group toGrant) throws GigiApiException {
530 PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO user_groups SET user=?, permission=?, grantedby=?");
531 ps.setInt(1, getId());
532 ps.setString(2, toGrant.getDatabaseName());
533 ps.setInt(3, granter.getId());
535 } catch (SQLException e) {
536 throw new GigiApiException(e);
540 public void revokeGroup(User revoker, Group toRevoke) throws GigiApiException {
541 groups.remove(toRevoke);
543 PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE user_groups SET deleted=CURRENT_TIMESTAMP, revokedby=? WHERE deleted is NULL AND permission=? AND user=?");
544 ps.setInt(1, revoker.getId());
545 ps.setString(2, toRevoke.getDatabaseName());
546 ps.setInt(3, getId());
548 } catch (SQLException e) {
549 throw new GigiApiException(e);
553 private static ObjectCache<User> myCache = new ObjectCache<>();
555 public static synchronized User getById(int id) {
556 User u = myCache.get(id);
558 myCache.put(u = new User(id));