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) throws GigiApiException {
72 super(rs.getInt("id"));
74 dob = new DayDate(rs.getDate("dob"));
75 email = rs.getString("email");
76 preferredName = Name.getById(rs.getInt("preferredName"));
78 if (rs.getString("country") != null) {
79 residenceCountry = Country.getCountryByCode(rs.getString("Country"), Country.CountryCodeType.CODE_2_CHARS);
82 String localeStr = rs.getString("language");
83 if (localeStr == null || localeStr.equals("")) {
84 locale = Locale.getDefault();
86 locale = Language.getLocaleFromString(localeStr);
92 public synchronized void refreshGroups() {
93 HashSet<Group> hs = new HashSet<>();
94 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
95 psg.setInt(1, getId());
97 try (GigiResultSet rs2 = psg.executeQuery()) {
99 hs.add(Group.getByString(rs2.getString(1)));
106 public User(String email, String password, DayDate dob, Locale locale, Country residenceCountry, NamePart... preferred) throws GigiApiException {
109 this.locale = locale;
110 this.preferredName = new Name(this, preferred);
111 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?, `country` = ?")) {
112 query.setString(1, email);
113 query.setString(2, PasswordHash.hash(password));
114 query.setDate(3, dob.toSQLDate());
115 query.setString(4, locale.toString());
116 query.setInt(5, getId());
117 query.setInt(6, preferredName.getId());
118 query.setString(7, residenceCountry == null ? null : residenceCountry.getCode());
121 new EmailAddress(this, email, locale);
124 public Name[] getNames() {
125 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
126 gps.setInt(1, getId());
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 gps.setInt(1, getId());
134 return fetchNamesToArray(gps);
138 private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
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.setEnum(2, AssuranceType.FACE_TO_FACE);
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) throws GigiApiException {
442 if (toGrant.isManagedBySupport() && !granter.isInGroup(Group.SUPPORTER)) {
443 throw new GigiApiException("Group may only be managed by supporter");
445 if (toGrant.isManagedBySupport() && granter == this) {
446 throw new GigiApiException("Group may only be managed by supporter that is not oneself");
449 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
450 ps.setInt(1, getId());
451 ps.setEnum(2, toGrant);
452 ps.setInt(3, granter.getId());
457 public void revokeGroup(User revoker, Group toRevoke) throws GigiApiException {
458 if (toRevoke.isManagedBySupport() && !revoker.isInGroup(Group.SUPPORTER)) {
459 throw new GigiApiException("Group may only be managed by supporter");
461 groups.remove(toRevoke);
462 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
463 ps.setInt(1, revoker.getId());
464 ps.setEnum(2, toRevoke);
465 ps.setInt(3, getId());
470 public List<Organisation> getOrganisations() {
471 return getOrganisations(false);
474 public List<Organisation> getOrganisations(boolean isAdmin) {
475 List<Organisation> orgas = new ArrayList<>();
476 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
477 query.setInt(1, getId());
478 try (GigiResultSet res = query.executeQuery()) {
480 orgas.add(Organisation.getById(res.getInt(1)));
488 public static synchronized User getById(int id) {
489 CertificateOwner co = CertificateOwner.getById(id);
490 if (co instanceof User) {
497 public static User getByEmail(String mail) {
498 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
499 ps.setString(1, mail);
500 GigiResultSet rs = ps.executeQuery();
505 return User.getById(rs.getInt(1));
509 public static User[] findByEmail(String mail) {
510 LinkedList<User> results = new LinkedList<User>();
511 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")) {
512 ps.setString(1, mail);
513 GigiResultSet rs = ps.executeQuery();
515 results.add(User.getById(rs.getInt(1)));
517 return results.toArray(new User[results.size()]);
521 public EmailAddress[] getEmails() {
522 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
523 ps.setInt(1, getId());
525 GigiResultSet rs = ps.executeQuery();
526 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
529 data.add(EmailAddress.getById(rs.getInt(1)));
532 return data.toArray(new EmailAddress[0]);
537 public boolean isValidEmail(String email) {
538 for (EmailAddress em : getEmails()) {
539 if (em.getAddress().equals(email)) {
540 return em.isVerified();
547 public String[] getTrainings() {
548 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")) {
549 prep.setInt(1, getId());
550 GigiResultSet res = prep.executeQuery();
551 List<String> entries = new LinkedList<String>();
554 StringBuilder training = new StringBuilder();
555 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
556 training.append(" (");
557 training.append(res.getString(2));
558 if (res.getString(3).length() > 0) {
559 training.append(" ");
560 training.append(res.getString(3));
562 if (res.getString(4).length() > 0) {
563 training.append(", ");
564 training.append(res.getString(4));
566 training.append(")");
567 entries.add(training.toString());
570 return entries.toArray(new String[0]);
575 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
576 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
577 ps.setInt(1, getId());
578 ps.setInt(2, getId());
579 ps.setString(3, token);
580 ps.setString(4, PasswordHash.hash(privateToken));
582 return ps.lastInsertId();
586 public static User getResetWithToken(int id, String token) {
587 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
589 ps.setString(2, token);
590 ps.setInt(3, PasswordResetPage.HOUR_MAX);
591 GigiResultSet res = ps.executeQuery();
595 return User.getById(res.getInt(1));
599 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
600 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
602 ps.setInt(2, getId());
603 GigiResultSet rs = ps.executeQuery();
605 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
607 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
608 throw new GigiApiException("Private token does not match.");
610 setPassword(newPassword);
612 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
618 private Assurance assuranceByRes(GigiResultSet res) {
620 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));
621 } catch (GigiApiException e) {
626 public boolean isInVerificationLimit() {
627 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;")) {
628 ps.setInt(1, getId());
629 ps.setInt(2, VERIFICATION_MONTHS);
631 GigiResultSet rs = ps.executeQuery();
636 private void writeObject(ObjectOutputStream oos) throws IOException {}
638 private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {}
640 public Country getResidenceCountry() {
641 return residenceCountry;
644 public void setResidenceCountry(Country residenceCountry) {
645 this.residenceCountry = residenceCountry;
646 rawUpdateCountryData();
649 private void rawUpdateCountryData() {
650 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET country=? WHERE id=?")) {
651 update.setString(1, residenceCountry == null ? null : residenceCountry.getCode());
652 update.setInt(2, getId());
653 update.executeUpdate();