1 package org.cacert.gigi.dbObjects;
3 import java.io.IOException;
4 import java.io.ObjectInputStream;
5 import java.io.ObjectOutputStream;
6 import java.util.ArrayList;
7 import java.util.Collections;
8 import java.util.HashSet;
9 import java.util.LinkedList;
10 import java.util.List;
11 import java.util.Locale;
14 import org.cacert.gigi.GigiApiException;
15 import org.cacert.gigi.database.GigiPreparedStatement;
16 import org.cacert.gigi.database.GigiResultSet;
17 import org.cacert.gigi.dbObjects.Assurance.AssuranceType;
18 import org.cacert.gigi.dbObjects.CATS.CATSType;
19 import org.cacert.gigi.dbObjects.Country.CountryCodeType;
20 import org.cacert.gigi.localisation.Language;
21 import org.cacert.gigi.output.DateSelector;
22 import org.cacert.gigi.pages.PasswordResetPage;
23 import org.cacert.gigi.util.CalendarUtil;
24 import org.cacert.gigi.util.DayDate;
25 import org.cacert.gigi.util.Notary;
26 import org.cacert.gigi.util.PasswordHash;
27 import org.cacert.gigi.util.PasswordStrengthChecker;
28 import org.cacert.gigi.util.TimeConditions;
31 * Represents an acting, assurable, user. Synchronizing on user means: no
32 * name-change and no assurance.
34 public class User extends CertificateOwner {
36 private static final long serialVersionUID = -7915843843752264176L;
42 private Assurance[] receivedAssurances;
44 private Assurance[] madeAssurances;
46 private Locale locale;
48 private final Set<Group> groups = new HashSet<>();
50 public static final int MINIMUM_AGE = 16;
52 public static final int MAXIMUM_PLAUSIBLE_AGE = 120;
54 public static final int POJAM_AGE = 14;
56 public static final int ADULT_AGE = 18;
58 public static final boolean POJAM_ENABLED = false;
60 public static final int EXPERIENCE_POINTS = 4;
63 * Time in months a verification is considered "recent".
65 public static final int VERIFICATION_MONTHS = TimeConditions.getInstance().getVerificationMonths();
67 private Name preferredName;
69 private Country residenceCountry;
71 protected User(GigiResultSet rs) {
72 super(rs.getInt("id"));
76 private void updateName(GigiResultSet rs) {
77 dob = new DayDate(rs.getDate("dob"));
78 email = rs.getString("email");
79 preferredName = Name.getById(rs.getInt("preferredName"));
82 if (rs.getString("Country") != null) {
83 residenceCountry = Country.getCountryByCode(rs.getString("Country"), Country.CountryCodeType.CODE_2_CHARS);
85 } catch (GigiApiException e) {
89 String localeStr = rs.getString("language");
90 if (localeStr == null || localeStr.equals("")) {
91 locale = Locale.getDefault();
93 locale = Language.getLocaleFromString(localeStr);
96 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
97 psg.setInt(1, rs.getInt("id"));
99 try (GigiResultSet rs2 = psg.executeQuery()) {
101 groups.add(Group.getByString(rs2.getString(1)));
107 public User(String email, String password, DayDate dob, Locale locale, Country residenceCountry, NamePart... preferred) throws GigiApiException {
110 this.locale = locale;
111 this.preferredName = new Name(this, preferred);
112 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?, `country` = ?")) {
113 query.setString(1, email);
114 query.setString(2, PasswordHash.hash(password));
115 query.setDate(3, dob.toSQLDate());
116 query.setString(4, locale.toString());
117 query.setInt(5, getId());
118 query.setInt(6, preferredName.getId());
119 query.setString(7, residenceCountry == null ? null : residenceCountry.getCode());
122 new EmailAddress(this, email, locale);
125 public Name[] getNames() {
126 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
127 return fetchNamesToArray(gps);
131 public Name[] getNonDeprecatedNames() {
132 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL AND `deprecated` IS NULL", true)) {
133 return fetchNamesToArray(gps);
137 private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
138 gps.setInt(1, getId());
139 GigiResultSet rs = gps.executeQuery();
141 Name[] dt = new Name[rs.getRow()];
143 for (int i = 0; rs.next(); i++) {
144 dt[i] = Name.getById(rs.getInt(1));
149 public DayDate getDoB() {
153 public void setDoB(DayDate dob) throws GigiApiException {
154 synchronized (Notary.class) {
155 if (getReceivedAssurances().length != 0) {
156 throw new GigiApiException("No change after verification allowed.");
159 if ( !CalendarUtil.isOfAge(dob, User.MINIMUM_AGE)) {
160 throw new GigiApiException("Entered date of birth is below the restricted age requirements.");
163 if (CalendarUtil.isOfAge(dob, User.MAXIMUM_PLAUSIBLE_AGE)) {
164 throw new GigiApiException("Entered date of birth exceeds the maximum age set in our policies. Please check your DoB is correct and contact support if the issue persists.");
172 protected void setDoBAsSupport(DayDate dob) throws GigiApiException {
173 synchronized (Notary.class) {
180 public String getEmail() {
184 public void changePassword(String oldPass, String newPass) throws GigiApiException {
185 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
186 ps.setInt(1, getId());
187 try (GigiResultSet rs = ps.executeQuery()) {
189 throw new GigiApiException("User not found... very bad.");
191 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
192 throw new GigiApiException("Old password does not match.");
196 setPassword(newPass);
199 private void setPassword(String newPass) throws GigiApiException {
200 PasswordStrengthChecker.assertStrongPassword(newPass, getNames(), getEmail());
201 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
202 ps.setString(1, PasswordHash.hash(newPass));
203 ps.setInt(2, getId());
208 public boolean canAssure() {
210 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
214 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
218 if (getAssurancePoints() < 100) {
222 return hasPassedCATS();
226 public boolean hasPassedCATS() {
227 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
228 query.setInt(1, getId());
229 query.setInt(2, CATSType.ASSURER_CHALLENGE.getId());
230 try (GigiResultSet rs = query.executeQuery()) {
240 public int getAssurancePoints() {
241 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT SUM(lastpoints) FROM ( SELECT DISTINCT ON (`from`) `from`, `points` as lastpoints FROM `notary` INNER JOIN `names` ON `names`.`id`=`to` WHERE `notary`.`deleted` is NULL AND (`expire` IS NULL OR `expire` > CURRENT_TIMESTAMP) AND `names`.`uid` = ? ORDER BY `from`, `when` DESC) as p")) {
242 query.setInt(1, getId());
244 GigiResultSet rs = query.executeQuery();
248 points = rs.getInt(1);
255 public int getExperiencePoints() {
256 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT count(*) FROM ( SELECT `names`.`uid` FROM `notary` INNER JOIN `names` ON `names`.`id` = `to` WHERE `from`=? AND `notary`.`deleted` IS NULL AND `method` = ? ::`notaryType` GROUP BY `names`.`uid`) as p")) {
257 query.setInt(1, getId());
258 query.setString(2, AssuranceType.FACE_TO_FACE.getDescription());
260 GigiResultSet rs = query.executeQuery();
264 points = rs.getInt(1) * EXPERIENCE_POINTS;
272 * Gets the maximum allowed points NOW. Note that an assurance needs to
273 * re-check PoJam as it has taken place in the past.
275 * @return the maximal points @
277 @SuppressWarnings("unused")
278 public int getMaxAssurePoints() {
279 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
283 int exp = getExperiencePoints();
286 if (exp >= 5 * EXPERIENCE_POINTS) {
289 if (exp >= 10 * EXPERIENCE_POINTS) {
292 if (exp >= 15 * EXPERIENCE_POINTS) {
295 if (exp >= 20 * EXPERIENCE_POINTS) {
298 if (exp >= 25 * EXPERIENCE_POINTS) {
305 public boolean isValidName(String name) {
306 for (Name n : getNames()) {
307 if (n.matches(name) && n.getAssurancePoints() >= 50) {
314 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
315 for (EmailAddress email : getEmails()) {
316 if (email.getAddress().equals(newMail.getAddress())) {
317 if ( !email.isVerified()) {
318 throw new GigiApiException("Email not verified.");
321 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
322 ps.setString(1, newMail.getAddress());
323 ps.setInt(2, getId());
327 this.email = newMail.getAddress();
332 throw new GigiApiException("Given address not an address of the user.");
335 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
336 if (getEmail().equals(delMail.getAddress())) {
337 throw new GigiApiException("Can't delete user's default e-mail.");
340 for (EmailAddress email : getEmails()) {
341 if (email.getId() == delMail.getId()) {
342 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
343 ps.setInt(1, delMail.getId());
349 throw new GigiApiException("Email not one of user's email addresses.");
352 public synchronized Assurance[] getReceivedAssurances() {
353 if (receivedAssurances == null) {
354 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` INNER JOIN `names` ON `names`.`id` = `notary`.`to` WHERE `names`.`uid`=? AND `notary`.`deleted` IS NULL ORDER BY `when` DESC")) {
355 query.setInt(1, getId());
357 GigiResultSet res = query.executeQuery();
358 List<Assurance> assurances = new LinkedList<Assurance>();
361 assurances.add(assuranceByRes(res));
364 this.receivedAssurances = assurances.toArray(new Assurance[0]);
368 return receivedAssurances;
371 public synchronized Assurance[] getMadeAssurances() {
372 if (madeAssurances == null) {
373 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
374 query.setInt(1, getId());
376 try (GigiResultSet res = query.executeQuery()) {
377 List<Assurance> assurances = new LinkedList<Assurance>();
380 assurances.add(assuranceByRes(res));
383 this.madeAssurances = assurances.toArray(new Assurance[0]);
388 return madeAssurances;
391 public synchronized void invalidateMadeAssurances() {
392 madeAssurances = null;
395 public synchronized void invalidateReceivedAssurances() {
396 receivedAssurances = null;
399 private void rawUpdateUserData() {
400 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
401 update.setDate(1, getDoB().toSQLDate());
402 update.setInt(2, getId());
403 update.executeUpdate();
407 public Locale getPreferredLocale() {
411 public void setPreferredLocale(Locale locale) {
412 this.locale = locale;
416 public synchronized Name getPreferredName() {
417 return preferredName;
420 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
421 if (preferred.getOwner() != this) {
422 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
424 this.preferredName = preferred;
425 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
426 ps.setInt(1, preferred.getId());
427 ps.setInt(2, getId());
433 public boolean isInGroup(Group g) {
434 return groups.contains(g);
437 public Set<Group> getGroups() {
438 return Collections.unmodifiableSet(groups);
441 public void grantGroup(User granter, Group toGrant) {
443 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
444 ps.setInt(1, getId());
445 ps.setString(2, toGrant.getDatabaseName());
446 ps.setInt(3, granter.getId());
451 public void revokeGroup(User revoker, Group toRevoke) {
452 groups.remove(toRevoke);
453 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
454 ps.setInt(1, revoker.getId());
455 ps.setString(2, toRevoke.getDatabaseName());
456 ps.setInt(3, getId());
461 public List<Organisation> getOrganisations() {
462 return getOrganisations(false);
465 public List<Organisation> getOrganisations(boolean isAdmin) {
466 List<Organisation> orgas = new ArrayList<>();
467 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
468 query.setInt(1, getId());
469 try (GigiResultSet res = query.executeQuery()) {
471 orgas.add(Organisation.getById(res.getInt(1)));
479 public static synchronized User getById(int id) {
480 CertificateOwner co = CertificateOwner.getById(id);
481 if (co instanceof User) {
488 public static User getByEmail(String mail) {
489 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
490 ps.setString(1, mail);
491 GigiResultSet rs = ps.executeQuery();
496 return User.getById(rs.getInt(1));
500 public static User[] findByEmail(String mail) {
501 LinkedList<User> results = new LinkedList<User>();
502 try (GigiPreparedStatement ps = new GigiPreparedStatement("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` LIMIT 100")) {
503 ps.setString(1, mail);
504 GigiResultSet rs = ps.executeQuery();
506 results.add(User.getById(rs.getInt(1)));
508 return results.toArray(new User[results.size()]);
512 public EmailAddress[] getEmails() {
513 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
514 ps.setInt(1, getId());
516 GigiResultSet rs = ps.executeQuery();
517 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
520 data.add(EmailAddress.getById(rs.getInt(1)));
523 return data.toArray(new EmailAddress[0]);
528 public boolean isValidEmail(String email) {
529 for (EmailAddress em : getEmails()) {
530 if (em.getAddress().equals(email)) {
531 return em.isVerified();
538 public String[] getTrainings() {
539 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `pass_date`, `type_text`, `language`, `version` FROM `cats_passed` LEFT JOIN `cats_type` ON `cats_type`.`id`=`cats_passed`.`variant_id` WHERE `user_id`=? ORDER BY `pass_date` ASC")) {
540 prep.setInt(1, getId());
541 GigiResultSet res = prep.executeQuery();
542 List<String> entries = new LinkedList<String>();
545 StringBuilder training = new StringBuilder();
546 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
547 training.append(" (");
548 training.append(res.getString(2));
549 if (res.getString(3).length() > 0) {
550 training.append(" ");
551 training.append(res.getString(3));
553 if (res.getString(4).length() > 0) {
554 training.append(", ");
555 training.append(res.getString(4));
557 training.append(")");
558 entries.add(training.toString());
561 return entries.toArray(new String[0]);
566 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
567 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
568 ps.setInt(1, getId());
569 ps.setInt(2, getId());
570 ps.setString(3, token);
571 ps.setString(4, PasswordHash.hash(privateToken));
573 return ps.lastInsertId();
577 public static User getResetWithToken(int id, String token) {
578 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
580 ps.setString(2, token);
581 ps.setInt(3, PasswordResetPage.HOUR_MAX);
582 GigiResultSet res = ps.executeQuery();
586 return User.getById(res.getInt(1));
590 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
591 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
593 ps.setInt(2, getId());
594 GigiResultSet rs = ps.executeQuery();
596 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
598 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
599 throw new GigiApiException("Private token does not match.");
601 setPassword(newPassword);
603 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
609 private Assurance assuranceByRes(GigiResultSet res) {
611 return new Assurance(res.getInt("id"), User.getById(res.getInt("from")), Name.getById(res.getInt("to")), res.getString("location"), res.getString("method"), res.getInt("points"), res.getString("date"), res.getString("country") == null ? null : Country.getCountryByCode(res.getString("country"), CountryCodeType.CODE_2_CHARS));
612 } catch (GigiApiException e) {
617 public boolean isInVerificationLimit() {
618 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT 1 FROM `notary` INNER JOIN `names` ON `names`.`id`=`to` WHERE `names`.`uid` = ? AND `when` > (now() - (interval '1 month' * ?)) AND (`expire` IS NULL OR `expire` > now()) AND `notary`.`deleted` IS NULL;")) {
619 ps.setInt(1, getId());
620 ps.setInt(2, VERIFICATION_MONTHS);
622 GigiResultSet rs = ps.executeQuery();
627 private void writeObject(ObjectOutputStream oos) throws IOException {}
629 private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {}
631 public Country getResidenceCountry() {
632 return residenceCountry;
635 public void setResidenceCountry(Country residenceCountry) {
636 this.residenceCountry = residenceCountry;
637 rawUpdateCountryData();
640 private void rawUpdateCountryData() {
641 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET country=? WHERE id=?")) {
642 update.setString(1, residenceCountry == null ? null : residenceCountry.getCode());
643 update.setInt(2, getId());
644 update.executeUpdate();