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 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);
99 public synchronized void refreshGroups() {
100 HashSet<Group> hs = new HashSet<>();
101 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
102 psg.setInt(1, getId());
104 try (GigiResultSet rs2 = psg.executeQuery()) {
106 hs.add(Group.getByString(rs2.getString(1)));
113 public User(String email, String password, DayDate dob, Locale locale, Country residenceCountry, NamePart... preferred) throws GigiApiException {
116 this.locale = locale;
117 this.preferredName = new Name(this, preferred);
118 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?, `country` = ?")) {
119 query.setString(1, email);
120 query.setString(2, PasswordHash.hash(password));
121 query.setDate(3, dob.toSQLDate());
122 query.setString(4, locale.toString());
123 query.setInt(5, getId());
124 query.setInt(6, preferredName.getId());
125 query.setString(7, residenceCountry == null ? null : residenceCountry.getCode());
128 new EmailAddress(this, email, locale);
131 public Name[] getNames() {
132 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
133 return fetchNamesToArray(gps);
137 public Name[] getNonDeprecatedNames() {
138 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL AND `deprecated` IS NULL", true)) {
139 return fetchNamesToArray(gps);
143 private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
144 gps.setInt(1, getId());
145 GigiResultSet rs = gps.executeQuery();
147 Name[] dt = new Name[rs.getRow()];
149 for (int i = 0; rs.next(); i++) {
150 dt[i] = Name.getById(rs.getInt(1));
155 public DayDate getDoB() {
159 public void setDoB(DayDate dob) throws GigiApiException {
160 synchronized (Notary.class) {
161 if (getReceivedAssurances().length != 0) {
162 throw new GigiApiException("No change after verification allowed.");
165 if ( !CalendarUtil.isOfAge(dob, User.MINIMUM_AGE)) {
166 throw new GigiApiException("Entered date of birth is below the restricted age requirements.");
169 if (CalendarUtil.isOfAge(dob, User.MAXIMUM_PLAUSIBLE_AGE)) {
170 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.");
178 protected void setDoBAsSupport(DayDate dob) throws GigiApiException {
179 synchronized (Notary.class) {
186 public String getEmail() {
190 public void changePassword(String oldPass, String newPass) throws GigiApiException {
191 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
192 ps.setInt(1, getId());
193 try (GigiResultSet rs = ps.executeQuery()) {
195 throw new GigiApiException("User not found... very bad.");
197 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
198 throw new GigiApiException("Old password does not match.");
202 setPassword(newPass);
205 private void setPassword(String newPass) throws GigiApiException {
206 PasswordStrengthChecker.assertStrongPassword(newPass, getNames(), getEmail());
207 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
208 ps.setString(1, PasswordHash.hash(newPass));
209 ps.setInt(2, getId());
214 public boolean canAssure() {
216 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
220 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
224 if (getAssurancePoints() < 100) {
228 return hasPassedCATS();
232 public boolean hasPassedCATS() {
233 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
234 query.setInt(1, getId());
235 query.setInt(2, CATSType.ASSURER_CHALLENGE.getId());
236 try (GigiResultSet rs = query.executeQuery()) {
246 public int getAssurancePoints() {
247 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")) {
248 query.setInt(1, getId());
250 GigiResultSet rs = query.executeQuery();
254 points = rs.getInt(1);
261 public int getExperiencePoints() {
262 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")) {
263 query.setInt(1, getId());
264 query.setString(2, AssuranceType.FACE_TO_FACE.getDescription());
266 GigiResultSet rs = query.executeQuery();
270 points = rs.getInt(1) * EXPERIENCE_POINTS;
278 * Gets the maximum allowed points NOW. Note that an assurance needs to
279 * re-check PoJam as it has taken place in the past.
281 * @return the maximal points @
283 @SuppressWarnings("unused")
284 public int getMaxAssurePoints() {
285 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
289 int exp = getExperiencePoints();
292 if (exp >= 5 * EXPERIENCE_POINTS) {
295 if (exp >= 10 * EXPERIENCE_POINTS) {
298 if (exp >= 15 * EXPERIENCE_POINTS) {
301 if (exp >= 20 * EXPERIENCE_POINTS) {
304 if (exp >= 25 * EXPERIENCE_POINTS) {
311 public boolean isValidName(String name) {
312 for (Name n : getNames()) {
313 if (n.matches(name) && n.getAssurancePoints() >= 50) {
320 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
321 for (EmailAddress email : getEmails()) {
322 if (email.getAddress().equals(newMail.getAddress())) {
323 if ( !email.isVerified()) {
324 throw new GigiApiException("Email not verified.");
327 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
328 ps.setString(1, newMail.getAddress());
329 ps.setInt(2, getId());
333 this.email = newMail.getAddress();
338 throw new GigiApiException("Given address not an address of the user.");
341 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
342 if (getEmail().equals(delMail.getAddress())) {
343 throw new GigiApiException("Can't delete user's default e-mail.");
346 for (EmailAddress email : getEmails()) {
347 if (email.getId() == delMail.getId()) {
348 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
349 ps.setInt(1, delMail.getId());
355 throw new GigiApiException("Email not one of user's email addresses.");
358 public synchronized Assurance[] getReceivedAssurances() {
359 if (receivedAssurances == null) {
360 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")) {
361 query.setInt(1, getId());
363 GigiResultSet res = query.executeQuery();
364 List<Assurance> assurances = new LinkedList<Assurance>();
367 assurances.add(assuranceByRes(res));
370 this.receivedAssurances = assurances.toArray(new Assurance[0]);
374 return receivedAssurances;
377 public synchronized Assurance[] getMadeAssurances() {
378 if (madeAssurances == null) {
379 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
380 query.setInt(1, getId());
382 try (GigiResultSet res = query.executeQuery()) {
383 List<Assurance> assurances = new LinkedList<Assurance>();
386 assurances.add(assuranceByRes(res));
389 this.madeAssurances = assurances.toArray(new Assurance[0]);
394 return madeAssurances;
397 public synchronized void invalidateMadeAssurances() {
398 madeAssurances = null;
401 public synchronized void invalidateReceivedAssurances() {
402 receivedAssurances = null;
405 private void rawUpdateUserData() {
406 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
407 update.setDate(1, getDoB().toSQLDate());
408 update.setInt(2, getId());
409 update.executeUpdate();
413 public Locale getPreferredLocale() {
417 public void setPreferredLocale(Locale locale) {
418 this.locale = locale;
422 public synchronized Name getPreferredName() {
423 return preferredName;
426 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
427 if (preferred.getOwner() != this) {
428 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
430 this.preferredName = preferred;
431 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
432 ps.setInt(1, preferred.getId());
433 ps.setInt(2, getId());
439 public boolean isInGroup(Group g) {
440 return groups.contains(g);
443 public Set<Group> getGroups() {
444 return Collections.unmodifiableSet(groups);
447 public void grantGroup(User granter, Group toGrant) throws GigiApiException {
448 if (toGrant.isManagedBySupport() && !granter.isInGroup(Group.SUPPORTER)) {
449 throw new GigiApiException("Group may only be managed by supporter");
451 if (toGrant.isManagedBySupport() && granter == this) {
452 throw new GigiApiException("Group may only be managed by supporter that is not oneself");
455 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
456 ps.setInt(1, getId());
457 ps.setString(2, toGrant.getDatabaseName());
458 ps.setInt(3, granter.getId());
463 public void revokeGroup(User revoker, Group toRevoke) throws GigiApiException {
464 if (toRevoke.isManagedBySupport() && !revoker.isInGroup(Group.SUPPORTER)) {
465 throw new GigiApiException("Group may only be managed by supporter");
467 groups.remove(toRevoke);
468 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
469 ps.setInt(1, revoker.getId());
470 ps.setString(2, toRevoke.getDatabaseName());
471 ps.setInt(3, getId());
476 public List<Organisation> getOrganisations() {
477 return getOrganisations(false);
480 public List<Organisation> getOrganisations(boolean isAdmin) {
481 List<Organisation> orgas = new ArrayList<>();
482 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
483 query.setInt(1, getId());
484 try (GigiResultSet res = query.executeQuery()) {
486 orgas.add(Organisation.getById(res.getInt(1)));
494 public static synchronized User getById(int id) {
495 CertificateOwner co = CertificateOwner.getById(id);
496 if (co instanceof User) {
503 public static User getByEmail(String mail) {
504 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
505 ps.setString(1, mail);
506 GigiResultSet rs = ps.executeQuery();
511 return User.getById(rs.getInt(1));
515 public static User[] findByEmail(String mail) {
516 LinkedList<User> results = new LinkedList<User>();
517 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")) {
518 ps.setString(1, mail);
519 GigiResultSet rs = ps.executeQuery();
521 results.add(User.getById(rs.getInt(1)));
523 return results.toArray(new User[results.size()]);
527 public EmailAddress[] getEmails() {
528 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
529 ps.setInt(1, getId());
531 GigiResultSet rs = ps.executeQuery();
532 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
535 data.add(EmailAddress.getById(rs.getInt(1)));
538 return data.toArray(new EmailAddress[0]);
543 public boolean isValidEmail(String email) {
544 for (EmailAddress em : getEmails()) {
545 if (em.getAddress().equals(email)) {
546 return em.isVerified();
553 public String[] getTrainings() {
554 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")) {
555 prep.setInt(1, getId());
556 GigiResultSet res = prep.executeQuery();
557 List<String> entries = new LinkedList<String>();
560 StringBuilder training = new StringBuilder();
561 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
562 training.append(" (");
563 training.append(res.getString(2));
564 if (res.getString(3).length() > 0) {
565 training.append(" ");
566 training.append(res.getString(3));
568 if (res.getString(4).length() > 0) {
569 training.append(", ");
570 training.append(res.getString(4));
572 training.append(")");
573 entries.add(training.toString());
576 return entries.toArray(new String[0]);
581 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
582 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
583 ps.setInt(1, getId());
584 ps.setInt(2, getId());
585 ps.setString(3, token);
586 ps.setString(4, PasswordHash.hash(privateToken));
588 return ps.lastInsertId();
592 public static User getResetWithToken(int id, String token) {
593 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
595 ps.setString(2, token);
596 ps.setInt(3, PasswordResetPage.HOUR_MAX);
597 GigiResultSet res = ps.executeQuery();
601 return User.getById(res.getInt(1));
605 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
606 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
608 ps.setInt(2, getId());
609 GigiResultSet rs = ps.executeQuery();
611 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
613 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
614 throw new GigiApiException("Private token does not match.");
616 setPassword(newPassword);
618 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
624 private Assurance assuranceByRes(GigiResultSet res) {
626 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));
627 } catch (GigiApiException e) {
632 public boolean isInVerificationLimit() {
633 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;")) {
634 ps.setInt(1, getId());
635 ps.setInt(2, VERIFICATION_MONTHS);
637 GigiResultSet rs = ps.executeQuery();
642 private void writeObject(ObjectOutputStream oos) throws IOException {}
644 private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {}
646 public Country getResidenceCountry() {
647 return residenceCountry;
650 public void setResidenceCountry(Country residenceCountry) {
651 this.residenceCountry = residenceCountry;
652 rawUpdateCountryData();
655 private void rawUpdateCountryData() {
656 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET country=? WHERE id=?")) {
657 update.setString(1, residenceCountry == null ? null : residenceCountry.getCode());
658 update.setInt(2, getId());
659 update.executeUpdate();