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 setFname(String fname) {
116 this.name.fname = fname;
119 public void setLname(String lname) {
120 this.name.lname = lname;
123 public void insert(String password) {
125 throw new Error("refusing to insert");
127 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("insert into `users` set `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `created`=NOW(), locked=0, `language`=?");
128 query.setString(1, email);
129 query.setString(2, PasswordHash.hash(password));
130 query.setString(3, name.fname);
131 query.setString(4, name.mname);
132 query.setString(5, name.lname);
133 query.setString(6, name.suffix);
134 query.setDate(7, new java.sql.Date(dob.getTime()));
135 query.setString(8, locale.toString());
136 synchronized (User.class) {
138 id = query.lastInsertId();
143 public void changePassword(String oldPass, String newPass) throws GigiApiException {
144 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `password` FROM users WHERE id=?");
146 GigiResultSet rs = ps.executeQuery();
148 throw new GigiApiException("User not found... very bad.");
150 if ( !PasswordHash.verifyHash(oldPass, rs.getString(1))) {
151 throw new GigiApiException("Old password does not match.");
154 PasswordStrengthChecker.assertStrongPassword(newPass, this);
155 ps = DatabaseConnection.getInstance().prepare("UPDATE users SET `password`=? WHERE id=?");
156 ps.setString(1, PasswordHash.hash(newPass));
158 if (ps.executeUpdate() != 1) {
159 throw new GigiApiException("Password update failed.");
163 public boolean canAssure() {
164 if ( !isOfAge(14)) { // PoJAM
167 if (getAssurancePoints() < 100) {
171 return hasPassedCATS();
175 public boolean hasPassedCATS() {
176 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `cats_passed` where `user_id`=?");
178 GigiResultSet rs = query.executeQuery();
186 public int getAssurancePoints() {
187 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT sum(points) FROM `notary` where `to`=? AND `deleted`=0");
189 GigiResultSet rs = query.executeQuery();
192 points = rs.getInt(1);
198 public int getExperiencePoints() {
199 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0");
201 GigiResultSet rs = query.executeQuery();
204 points = rs.getInt(1) * 2;
211 public boolean equals(Object obj) {
212 if ( !(obj instanceof User)) {
216 return name.equals(s.name) && email.equals(s.email) && dob.toString().equals(s.dob.toString()); // This
225 * Gets the maximum allowed points NOW. Note that an assurance needs to
226 * re-check PoJam as it has taken place in the past.
228 * @return the maximal points @
230 public int getMaxAssurePoints() {
235 int exp = getExperiencePoints();
256 public boolean isOfAge(int desiredAge) {
257 Calendar c = Calendar.getInstance();
259 int year = c.get(Calendar.YEAR);
260 int month = c.get(Calendar.MONTH);
261 int day = c.get(Calendar.DAY_OF_MONTH);
262 c.set(year, month, day);
263 c.add(Calendar.YEAR, desiredAge);
264 return System.currentTimeMillis() >= c.getTime().getTime();
267 public EmailAddress[] getEmails() {
268 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM emails WHERE memid=? AND deleted=0");
270 GigiResultSet rs = ps.executeQuery();
272 int count = rs.getRow();
273 EmailAddress[] data = new EmailAddress[count];
275 for (int i = 0; i < data.length; i++) {
277 throw new Error("Internal sql api violation.");
279 data[i] = EmailAddress.getById(rs.getInt(1));
286 public Domain[] getDomains() {
287 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM domains WHERE memid=? AND deleted IS NULL");
289 GigiResultSet rs = ps.executeQuery();
291 int count = rs.getRow();
292 Domain[] data = new Domain[count];
294 for (int i = 0; i < data.length; i++) {
296 throw new Error("Internal sql api violation.");
298 data[i] = Domain.getById(rs.getInt(1));
305 public Certificate[] getCertificates() {
306 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT serial FROM certs WHERE memid=? AND revoked=0");
308 GigiResultSet rs = ps.executeQuery();
310 int count = rs.getRow();
311 Certificate[] data = new Certificate[count];
313 for (int i = 0; i < data.length; i++) {
315 throw new Error("Internal sql api violation.");
317 data[i] = Certificate.getBySerial(rs.getString(1));
324 public boolean isValidDomain(String domainname) {
325 for (Domain d : getDomains()) {
326 String sfx = d.getSuffix();
327 if (domainname.equals(sfx) || domainname.endsWith("." + sfx)) {
334 public boolean isValidEmail(String email) {
335 for (EmailAddress em : getEmails()) {
336 if (em.getAddress().equals(email)) {
343 public boolean isValidName(String name) {
344 return getName().matches(name);
347 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
348 EmailAddress[] adrs = getEmails();
349 for (int i = 0; i < adrs.length; i++) {
350 if (adrs[i].getAddress().equals(newMail.getAddress())) {
351 if ( !adrs[i].isVerified()) {
352 throw new GigiApiException("Email not verified.");
354 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET email=? WHERE id=?");
355 ps.setString(1, newMail.getAddress());
356 ps.setInt(2, getId());
358 email = newMail.getAddress();
362 throw new GigiApiException("Given address not an address of the user.");
365 public void deleteEmail(EmailAddress mail) throws GigiApiException {
366 if (getEmail().equals(mail.getAddress())) {
367 throw new GigiApiException("Can't delete user's default e-mail.");
369 EmailAddress[] emails = getEmails();
370 for (int i = 0; i < emails.length; i++) {
371 if (emails[i].getId() == mail.getId()) {
372 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE emails SET deleted=? WHERE id=?");
373 ps.setDate(1, new Date(System.currentTimeMillis()));
374 ps.setInt(2, mail.getId());
379 throw new GigiApiException("Email not one of user's email addresses.");
382 public Assurance[] getReceivedAssurances() {
383 if (receivedAssurances == null) {
384 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `to`=? AND deleted=0");
385 query.setInt(1, getId());
386 GigiResultSet res = query.executeQuery();
388 Assurance[] assurances = new Assurance[res.getRow()];
390 for (int i = 0; i < assurances.length; i++) {
392 assurances[i] = new Assurance(res);
394 this.receivedAssurances = assurances;
397 return receivedAssurances;
400 public Assurance[] getMadeAssurances() {
401 if (madeAssurances == null) {
402 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `from`=? AND deleted=0");
403 query.setInt(1, getId());
404 GigiResultSet res = query.executeQuery();
406 Assurance[] assurances = new Assurance[res.getRow()];
408 for (int i = 0; i < assurances.length; i++) {
410 assurances[i] = new Assurance(res);
412 this.madeAssurances = assurances;
415 return madeAssurances;
418 public void invalidateMadeAssurances() {
419 madeAssurances = null;
422 public void invalidateReceivedAssurances() {
423 receivedAssurances = null;
426 public void updateUserData() throws GigiApiException {
427 synchronized (Notary.class) {
428 if (getAssurancePoints() != 0) {
429 throw new GigiApiException("No change after assurance allowed.");
431 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?");
432 update.setString(1, getFname());
433 update.setString(2, getLname());
434 update.setString(3, getMname());
435 update.setString(4, getSuffix());
436 update.setDate(5, getDob());
437 update.setInt(6, getId());
438 update.executeUpdate();
442 public Locale getPreferredLocale() {
446 public void setPreferredLocale(Locale locale) {
447 this.locale = locale;
451 public boolean wantsDirectoryListing() {
452 GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT listme FROM users WHERE id=?");
453 get.setInt(1, getId());
454 GigiResultSet exec = get.executeQuery();
456 return exec.getBoolean("listme");
459 public String getContactInformation() {
460 GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT contactinfo FROM users WHERE id=?");
461 get.setInt(1, getId());
462 GigiResultSet exec = get.executeQuery();
464 return exec.getString("contactinfo");
467 public void setDirectoryListing(boolean on) {
468 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET listme = ? WHERE id = ?");
469 update.setBoolean(1, on);
470 update.setInt(2, getId());
471 update.executeUpdate();
474 public void setContactInformation(String contactInfo) {
475 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET contactinfo = ? WHERE id = ?");
476 update.setString(1, contactInfo);
477 update.setInt(2, getId());
478 update.executeUpdate();
481 public boolean isInGroup(Group g) {
482 return groups.contains(g);
485 public Set<Group> getGroups() {
486 return Collections.unmodifiableSet(groups);
489 public void grantGroup(User granter, Group toGrant) throws GigiApiException {
491 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO user_groups SET user=?, permission=?, grantedby=?");
492 ps.setInt(1, getId());
493 ps.setString(2, toGrant.getDatabaseName());
494 ps.setInt(3, granter.getId());
498 public void revokeGroup(User revoker, Group toRevoke) throws GigiApiException {
499 groups.remove(toRevoke);
500 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE user_groups SET deleted=CURRENT_TIMESTAMP, revokedby=? WHERE deleted is NULL AND permission=? AND user=?");
501 ps.setInt(1, revoker.getId());
502 ps.setString(2, toRevoke.getDatabaseName());
503 ps.setInt(3, getId());
507 private static ObjectCache<User> myCache = new ObjectCache<>();
509 public static synchronized User getById(int id) {
510 User u = myCache.get(id);
512 myCache.put(u = new User(id));