1 package club.wpia.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;
13 import java.util.TreeSet;
15 import club.wpia.gigi.Gigi;
16 import club.wpia.gigi.GigiApiException;
17 import club.wpia.gigi.database.GigiPreparedStatement;
18 import club.wpia.gigi.database.GigiResultSet;
19 import club.wpia.gigi.dbObjects.CATS.CATSType;
20 import club.wpia.gigi.dbObjects.Certificate.RevocationType;
21 import club.wpia.gigi.dbObjects.Country.CountryCodeType;
22 import club.wpia.gigi.dbObjects.Verification.VerificationType;
23 import club.wpia.gigi.email.EmailProvider;
24 import club.wpia.gigi.localisation.Language;
25 import club.wpia.gigi.output.DateSelector;
26 import club.wpia.gigi.pages.PasswordResetPage;
27 import club.wpia.gigi.util.CalendarUtil;
28 import club.wpia.gigi.util.DayDate;
29 import club.wpia.gigi.util.Notary;
30 import club.wpia.gigi.util.PasswordHash;
31 import club.wpia.gigi.util.TimeConditions;
34 * Represents an acting, verifiable user. Synchronizing on user means: no
35 * name-change and no verification.
37 public class User extends CertificateOwner {
39 private static final long serialVersionUID = -7915843843752264176L;
45 private Verification[] receivedVerifications;
47 private Verification[] madeVerifications;
49 private Locale locale;
51 private Set<Group> groups = new HashSet<>();
53 public static final int MINIMUM_AGE = 16;
55 public static final int MAXIMUM_PLAUSIBLE_AGE = 120;
57 public static final int POJAM_AGE = 14;
59 public static final int ADULT_AGE = 18;
61 public static final boolean POJAM_ENABLED = false;
63 public static final int EXPERIENCE_POINTS = 4;
66 * Time in months a verification is considered "recent".
68 public static final int VERIFICATION_MONTHS = TimeConditions.getInstance().getVerificationMonths();
70 private Name preferredName;
72 private Country residenceCountry;
74 protected User(GigiResultSet rs) throws GigiApiException {
75 super(rs.getInt("id"));
77 dob = new DayDate(rs.getDate("dob"));
78 email = rs.getString("email");
79 preferredName = Name.getById(rs.getInt("preferredName"));
81 if (rs.getString("country") != null) {
82 residenceCountry = Country.getCountryByCode(rs.getString("Country"), Country.CountryCodeType.CODE_2_CHARS);
85 String localeStr = rs.getString("language");
86 if (localeStr == null || localeStr.equals("")) {
87 locale = Locale.getDefault();
89 locale = Language.getLocaleFromString(localeStr);
95 public synchronized void refreshGroups() {
96 HashSet<Group> hs = new HashSet<>();
97 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
98 psg.setInt(1, getId());
100 try (GigiResultSet rs2 = psg.executeQuery()) {
102 hs.add(Group.getByString(rs2.getString(1)));
109 public User(String email, String password, DayDate dob, Locale locale, Country residenceCountry, NamePart... preferred) throws GigiApiException {
110 super(validate(email));
114 this.locale = locale;
115 this.preferredName = new Name(this, preferred);
116 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?, `country` = ?")) {
117 query.setString(1, email);
118 query.setString(2, PasswordHash.hash(password));
119 query.setDate(3, dob.toSQLDate());
120 query.setString(4, locale.toString());
121 query.setInt(5, getId());
122 query.setInt(6, preferredName.getId());
123 query.setString(7, residenceCountry == null ? null : residenceCountry.getCode());
127 new EmailAddress(this, email, locale);
130 private static Void validate(String email) {
131 // Avoid storing information that obviously won't get through
132 if ( !EmailProvider.isValidMailAddress(email)) {
133 throw new IllegalArgumentException("Invalid email.");
138 public Name[] getNames() {
139 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
140 gps.setInt(1, getId());
141 return fetchNamesToArray(gps);
145 public Name[] getNonDeprecatedNames() {
146 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL AND `deprecated` IS NULL", true)) {
147 gps.setInt(1, getId());
148 return fetchNamesToArray(gps);
152 private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
153 GigiResultSet rs = gps.executeQuery();
155 Name[] dt = new Name[rs.getRow()];
157 for (int i = 0; rs.next(); i++) {
158 dt[i] = Name.getById(rs.getInt(1));
163 public DayDate getDoB() {
167 public void setDoB(DayDate dob) throws GigiApiException {
168 synchronized (Notary.class) {
169 if (getReceivedVerifications().length != 0) {
170 throw new GigiApiException("No change after verification allowed.");
173 if ( !CalendarUtil.isOfAge(dob, User.MINIMUM_AGE)) {
174 throw new GigiApiException("Entered date of birth is below the restricted age requirements.");
177 if (CalendarUtil.isYearsInFuture(dob.end(), User.MAXIMUM_PLAUSIBLE_AGE)) {
178 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.");
186 protected void setDoBAsSupport(DayDate dob) throws GigiApiException {
187 synchronized (Notary.class) {
194 public String getEmail() {
198 public void changePassword(String oldPass, String newPass) throws GigiApiException {
199 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
200 ps.setInt(1, getId());
201 try (GigiResultSet rs = ps.executeQuery()) {
203 throw new GigiApiException("User not found... very bad.");
205 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
206 throw new GigiApiException("Old password does not match.");
210 setPassword(newPass);
213 private void setPassword(String newPass) throws GigiApiException {
214 Name[] names = getNames();
215 TreeSet<String> nameParts = new TreeSet<>();
216 for (int i = 0; i < names.length; i++) {
217 for (NamePart string : names[i].getParts()) {
218 nameParts.add(string.getValue());
221 GigiApiException gaPassword = Gigi.getPasswordChecker().checkPassword(newPass, nameParts.toArray(new String[nameParts.size()]), getEmail());
222 if (gaPassword != null) {
225 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
226 ps.setString(1, PasswordHash.hash(newPass));
227 ps.setInt(2, getId());
232 public boolean canVerify() {
234 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
238 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
242 if (getVerificationPoints() < 100) {
246 return hasPassedCATS();
250 public boolean hasPassedCATS() {
251 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
252 query.setInt(1, getId());
253 query.setInt(2, CATSType.AGENT_CHALLENGE.getId());
254 try (GigiResultSet rs = query.executeQuery()) {
264 public int getVerificationPoints() {
265 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT SUM(lastpoints) FROM ( SELECT DISTINCT ON (`from`, `method`) `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`, `method`, `when` DESC) as p")) {
266 query.setInt(1, getId());
268 GigiResultSet rs = query.executeQuery();
272 points = rs.getInt(1);
279 public int getExperiencePoints() {
280 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")) {
281 query.setInt(1, getId());
282 query.setEnum(2, VerificationType.FACE_TO_FACE);
284 GigiResultSet rs = query.executeQuery();
288 points = rs.getInt(1) * EXPERIENCE_POINTS;
296 * Gets the maximum allowed points NOW. Note that a verification needs to
297 * re-check PoJam as it has taken place in the past.
299 * @return the maximal points @
301 @SuppressWarnings("unused")
302 public int getMaxVerifyPoints() {
303 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
307 int exp = getExperiencePoints();
310 if (exp >= 5 * EXPERIENCE_POINTS) {
313 if (exp >= 10 * EXPERIENCE_POINTS) {
316 if (exp >= 15 * EXPERIENCE_POINTS) {
319 if (exp >= 20 * EXPERIENCE_POINTS) {
322 if (exp >= 25 * EXPERIENCE_POINTS) {
329 public boolean isValidName(String name) {
330 for (Name n : getNames()) {
331 if (n.matches(name) && n.getVerificationPoints() >= 50) {
338 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
339 for (EmailAddress email : getEmails()) {
340 if (email.getAddress().equals(newMail.getAddress())) {
341 if ( !email.isVerified()) {
342 throw new GigiApiException("Email not verified.");
345 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
346 ps.setString(1, newMail.getAddress());
347 ps.setInt(2, getId());
351 this.email = newMail.getAddress();
356 throw new GigiApiException("Given address not an address of the user.");
359 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
360 if (getEmail().equals(delMail.getAddress())) {
361 throw new GigiApiException("Can't delete user's default e-mail.");
364 deleteEmailCerts(delMail, RevocationType.USER);
367 private void deleteEmailCerts(EmailAddress delMail, RevocationType rt) throws GigiApiException {
368 for (EmailAddress email : getEmails()) {
369 if (email.getId() == delMail.getId()) {
370 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
371 ps.setInt(1, delMail.getId());
374 LinkedList<Job> revokes = new LinkedList<Job>();
375 for (Certificate cert : fetchActiveEmailCertificates(delMail.getAddress())) {
376 revokes.add(cert.revoke(RevocationType.USER));
378 long start = System.currentTimeMillis();
379 for (Job job : revokes) {
380 int toWait = (int) (60000 + start - System.currentTimeMillis());
384 break; // canceled... waited too log
391 throw new GigiApiException("Email not one of user's email addresses.");
395 public Certificate[] fetchActiveEmailCertificates(String email) {
396 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT DISTINCT `certs`.`id` FROM `certs` INNER JOIN `subjectAlternativeNames` ON `subjectAlternativeNames`.`certId` = `certs`.`id` WHERE `contents`=? AND `type`='email' AND `revoked` IS NULL AND `expire` > CURRENT_TIMESTAMP AND `memid`=?", true)) {
397 ps.setString(1, email);
398 ps.setInt(2, getId());
399 GigiResultSet rs = ps.executeQuery();
401 Certificate[] res = new Certificate[rs.getRow()];
405 res[i++] = Certificate.getById(rs.getInt(1));
411 public synchronized Verification[] getReceivedVerifications() {
412 if (receivedVerifications == null) {
413 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")) {
414 query.setInt(1, getId());
416 GigiResultSet res = query.executeQuery();
417 List<Verification> verifications = new LinkedList<Verification>();
420 verifications.add(verificationByRes(res));
423 this.receivedVerifications = verifications.toArray(new Verification[0]);
427 return receivedVerifications;
430 public synchronized Verification[] getMadeVerifications() {
431 if (madeVerifications == null) {
432 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
433 query.setInt(1, getId());
435 try (GigiResultSet res = query.executeQuery()) {
436 List<Verification> verifications = new LinkedList<Verification>();
439 verifications.add(verificationByRes(res));
442 this.madeVerifications = verifications.toArray(new Verification[0]);
447 return madeVerifications;
450 public synchronized void invalidateMadeVerifications() {
451 madeVerifications = null;
454 public synchronized void invalidateReceivedVerifications() {
455 receivedVerifications = null;
458 private void rawUpdateUserData() {
459 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
460 update.setDate(1, getDoB().toSQLDate());
461 update.setInt(2, getId());
462 update.executeUpdate();
466 public Locale getPreferredLocale() {
470 public void setPreferredLocale(Locale locale) {
471 this.locale = locale;
475 public synchronized Name getPreferredName() {
476 return preferredName;
479 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
480 if (preferred.getOwner() != this) {
481 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
483 this.preferredName = preferred;
484 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
485 ps.setInt(1, preferred.getId());
486 ps.setInt(2, getId());
492 public synchronized String getInitials() {
493 return preferredName.toInitialsString();
496 public boolean isInGroup(Group g) {
497 return groups.contains(g);
500 public Set<Group> getGroups() {
501 return Collections.unmodifiableSet(groups);
504 public void grantGroup(User granter, Group toGrant) throws GigiApiException {
505 if (toGrant.isManagedBySupport() && !granter.isInGroup(Group.SUPPORTER)) {
506 throw new GigiApiException("Group may only be managed by supporter");
508 if (toGrant.isManagedBySupport() && granter == this) {
509 throw new GigiApiException("Group may only be managed by supporter that is not oneself");
512 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
513 ps.setInt(1, getId());
514 ps.setEnum(2, toGrant);
515 ps.setInt(3, granter.getId());
520 public void revokeGroup(User revoker, Group toRevoke) throws GigiApiException {
521 if (toRevoke.isManagedBySupport() && !revoker.isInGroup(Group.SUPPORTER)) {
522 throw new GigiApiException("Group may only be managed by supporter");
524 groups.remove(toRevoke);
525 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
526 ps.setInt(1, revoker.getId());
527 ps.setEnum(2, toRevoke);
528 ps.setInt(3, getId());
533 public List<Organisation> getOrganisations() {
534 return getOrganisations(false);
537 public List<Organisation> getOrganisations(boolean isAdmin) {
538 List<Organisation> orgas = new ArrayList<>();
539 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
540 query.setInt(1, getId());
541 try (GigiResultSet res = query.executeQuery()) {
543 orgas.add(Organisation.getById(res.getInt(1)));
551 public static synchronized User getById(int id) {
552 CertificateOwner co = CertificateOwner.getById(id);
553 if (co instanceof User) {
560 public static User getByEmail(String mail) {
561 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
562 ps.setString(1, mail);
563 GigiResultSet rs = ps.executeQuery();
568 return User.getById(rs.getInt(1));
572 public static User[] findByEmail(String mail) {
573 LinkedList<User> results = new LinkedList<User>();
574 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")) {
575 ps.setString(1, mail);
576 GigiResultSet rs = ps.executeQuery();
578 results.add(User.getById(rs.getInt(1)));
580 return results.toArray(new User[results.size()]);
584 public EmailAddress[] getEmails() {
585 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
586 ps.setInt(1, getId());
588 GigiResultSet rs = ps.executeQuery();
589 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
592 data.add(EmailAddress.getById(rs.getInt(1)));
595 return data.toArray(new EmailAddress[0]);
600 public boolean isValidEmail(String email) {
601 for (EmailAddress em : getEmails()) {
602 if (em.getAddress().equals(email)) {
603 return em.isVerified();
610 public String[] getTrainings() {
611 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` DESC")) {
612 prep.setInt(1, getId());
613 GigiResultSet res = prep.executeQuery();
614 List<String> entries = new LinkedList<String>();
617 StringBuilder training = new StringBuilder();
618 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
619 training.append(" (");
620 training.append(res.getString(2));
621 if (res.getString(3).length() > 0) {
622 training.append(" ");
623 training.append(res.getString(3));
625 if (res.getString(4).length() > 0) {
626 training.append(", ");
627 training.append(res.getString(4));
629 training.append(")");
630 entries.add(training.toString());
633 return entries.toArray(new String[0]);
638 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
639 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
640 ps.setInt(1, getId());
641 ps.setInt(2, getId());
642 ps.setString(3, token);
643 ps.setString(4, PasswordHash.hash(privateToken));
645 return ps.lastInsertId();
649 public static User getResetWithToken(int id, String token) {
650 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?::INTEGER")) {
652 ps.setString(2, token);
653 ps.setInt(3, PasswordResetPage.HOUR_MAX);
654 GigiResultSet res = ps.executeQuery();
658 return User.getById(res.getInt(1));
662 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
663 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
665 ps.setInt(2, getId());
666 GigiResultSet rs = ps.executeQuery();
668 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
670 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
671 throw new GigiApiException("Private token does not match.");
673 setPassword(newPassword);
675 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
681 private Verification verificationByRes(GigiResultSet res) {
683 return new Verification(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), res.getTimestamp("expire"));
684 } catch (GigiApiException e) {
689 public boolean isInVerificationLimit() {
690 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' * ?::INTEGER)) AND (`expire` IS NULL OR `expire` > now()) AND `notary`.`deleted` IS NULL;")) {
691 ps.setInt(1, getId());
692 ps.setInt(2, VERIFICATION_MONTHS);
694 GigiResultSet rs = ps.executeQuery();
699 private void writeObject(ObjectOutputStream oos) throws IOException {}
701 private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {}
703 public Country getResidenceCountry() {
704 return residenceCountry;
707 public void setResidenceCountry(Country residenceCountry) {
708 this.residenceCountry = residenceCountry;
709 rawUpdateCountryData();
712 private void rawUpdateCountryData() {
713 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET country=? WHERE id=?")) {
714 update.setString(1, residenceCountry == null ? null : residenceCountry.getCode());
715 update.setInt(2, getId());
716 update.executeUpdate();
720 public boolean hasValidRAChallenge() {
721 return CATS.isInCatsLimit(getId(), CATSType.AGENT_CHALLENGE.getId());
724 public boolean hasValidSupportChallenge() {
725 return CATS.isInCatsLimit(getId(), CATSType.SUPPORT_DP_CHALLENGE_NAME.getId());
728 public boolean hasValidOrgAdminChallenge() {
729 return CATS.isInCatsLimit(getId(), CATSType.ORG_ADMIN_DP_CHALLENGE_NAME.getId());
732 public boolean hasValidOrgAgentChallenge() {
733 return CATS.isInCatsLimit(getId(), CATSType.ORG_AGENT_CHALLENGE.getId());
736 public boolean hasValidTTPAgentChallenge() {
737 return CATS.isInCatsLimit(getId(), CATSType.TTP_AGENT_CHALLENGE.getId());
740 public void writeUserLog(User actor, String type) throws GigiApiException {
741 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `adminLog` SET uid=?, admin=?, type=?")) {
742 prep.setInt(1, actor.getId());
743 prep.setInt(2, getId());
744 prep.setString(3, type);
745 prep.executeUpdate();