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.Country.CountryCodeType;
21 import club.wpia.gigi.dbObjects.Verification.VerificationType;
22 import club.wpia.gigi.email.EmailProvider;
23 import club.wpia.gigi.localisation.Language;
24 import club.wpia.gigi.output.DateSelector;
25 import club.wpia.gigi.pages.PasswordResetPage;
26 import club.wpia.gigi.util.CalendarUtil;
27 import club.wpia.gigi.util.DayDate;
28 import club.wpia.gigi.util.Notary;
29 import club.wpia.gigi.util.PasswordHash;
30 import club.wpia.gigi.util.TimeConditions;
33 * Represents an acting, verifiable user. Synchronizing on user means: no
34 * name-change and no verification.
36 public class User extends CertificateOwner {
38 private static final long serialVersionUID = -7915843843752264176L;
44 private Verification[] receivedVerifications;
46 private Verification[] madeVerifications;
48 private Locale locale;
50 private Set<Group> groups = new HashSet<>();
52 public static final int MINIMUM_AGE = 16;
54 public static final int MAXIMUM_PLAUSIBLE_AGE = 120;
56 public static final int POJAM_AGE = 14;
58 public static final int ADULT_AGE = 18;
60 public static final boolean POJAM_ENABLED = false;
62 public static final int EXPERIENCE_POINTS = 4;
65 * Time in months a verification is considered "recent".
67 public static final int VERIFICATION_MONTHS = TimeConditions.getInstance().getVerificationMonths();
69 private Name preferredName;
71 private Country residenceCountry;
73 protected User(GigiResultSet rs) throws GigiApiException {
74 super(rs.getInt("id"));
76 dob = new DayDate(rs.getDate("dob"));
77 email = rs.getString("email");
78 preferredName = Name.getById(rs.getInt("preferredName"));
80 if (rs.getString("country") != null) {
81 residenceCountry = Country.getCountryByCode(rs.getString("Country"), Country.CountryCodeType.CODE_2_CHARS);
84 String localeStr = rs.getString("language");
85 if (localeStr == null || localeStr.equals("")) {
86 locale = Locale.getDefault();
88 locale = Language.getLocaleFromString(localeStr);
94 public synchronized void refreshGroups() {
95 HashSet<Group> hs = new HashSet<>();
96 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
97 psg.setInt(1, getId());
99 try (GigiResultSet rs2 = psg.executeQuery()) {
101 hs.add(Group.getByString(rs2.getString(1)));
108 public User(String email, String password, DayDate dob, Locale locale, Country residenceCountry, NamePart... preferred) throws GigiApiException {
109 super(validate(email));
113 this.locale = locale;
114 this.preferredName = new Name(this, preferred);
115 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?, `country` = ?")) {
116 query.setString(1, email);
117 query.setString(2, PasswordHash.hash(password));
118 query.setDate(3, dob.toSQLDate());
119 query.setString(4, locale.toString());
120 query.setInt(5, getId());
121 query.setInt(6, preferredName.getId());
122 query.setString(7, residenceCountry == null ? null : residenceCountry.getCode());
126 new EmailAddress(this, email, locale);
129 private static Void validate(String email) {
130 // Avoid storing information that obviously won't get through
131 if ( !EmailProvider.isValidMailAddress(email)) {
132 throw new IllegalArgumentException("Invalid email.");
137 public Name[] getNames() {
138 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
139 gps.setInt(1, getId());
140 return fetchNamesToArray(gps);
144 public Name[] getNonDeprecatedNames() {
145 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL AND `deprecated` IS NULL", true)) {
146 gps.setInt(1, getId());
147 return fetchNamesToArray(gps);
151 private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
152 GigiResultSet rs = gps.executeQuery();
154 Name[] dt = new Name[rs.getRow()];
156 for (int i = 0; rs.next(); i++) {
157 dt[i] = Name.getById(rs.getInt(1));
162 public DayDate getDoB() {
166 public void setDoB(DayDate dob) throws GigiApiException {
167 synchronized (Notary.class) {
168 if (getReceivedVerifications().length != 0) {
169 throw new GigiApiException("No change after verification allowed.");
172 if ( !CalendarUtil.isOfAge(dob, User.MINIMUM_AGE)) {
173 throw new GigiApiException("Entered date of birth is below the restricted age requirements.");
176 if (CalendarUtil.isYearsInFuture(dob.end(), User.MAXIMUM_PLAUSIBLE_AGE)) {
177 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.");
185 protected void setDoBAsSupport(DayDate dob) throws GigiApiException {
186 synchronized (Notary.class) {
193 public String getEmail() {
197 public void changePassword(String oldPass, String newPass) throws GigiApiException {
198 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
199 ps.setInt(1, getId());
200 try (GigiResultSet rs = ps.executeQuery()) {
202 throw new GigiApiException("User not found... very bad.");
204 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
205 throw new GigiApiException("Old password does not match.");
209 setPassword(newPass);
212 public void setPassword(String newPass) throws GigiApiException {
213 Name[] names = getNames();
214 TreeSet<String> nameParts = new TreeSet<>();
215 for (int i = 0; i < names.length; i++) {
216 for (NamePart string : names[i].getParts()) {
217 nameParts.add(string.getValue());
220 GigiApiException gaPassword = Gigi.getPasswordChecker().checkPassword(newPass, nameParts.toArray(new String[nameParts.size()]), getEmail());
221 if (gaPassword != null) {
224 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
225 ps.setString(1, PasswordHash.hash(newPass));
226 ps.setInt(2, getId());
231 public boolean canVerify() {
233 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
237 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
241 if (getVerificationPoints() < 100) {
245 return hasPassedCATS();
249 public boolean hasPassedCATS() {
250 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
251 query.setInt(1, getId());
252 query.setInt(2, CATSType.AGENT_CHALLENGE.getId());
253 try (GigiResultSet rs = query.executeQuery()) {
263 public int getVerificationPoints() {
264 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")) {
265 query.setInt(1, getId());
267 GigiResultSet rs = query.executeQuery();
271 points = rs.getInt(1);
278 public int getExperiencePoints() {
279 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")) {
280 query.setInt(1, getId());
281 query.setEnum(2, VerificationType.FACE_TO_FACE);
283 GigiResultSet rs = query.executeQuery();
287 points = rs.getInt(1) * EXPERIENCE_POINTS;
295 * Gets the maximum allowed points NOW. Note that a verification needs to
296 * re-check PoJam as it has taken place in the past.
298 * @return the maximal points @
300 @SuppressWarnings("unused")
301 public int getMaxVerifyPoints() {
302 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
306 int exp = getExperiencePoints();
309 if (exp >= 5 * EXPERIENCE_POINTS) {
312 if (exp >= 10 * EXPERIENCE_POINTS) {
315 if (exp >= 15 * EXPERIENCE_POINTS) {
318 if (exp >= 20 * EXPERIENCE_POINTS) {
321 if (exp >= 25 * EXPERIENCE_POINTS) {
328 public boolean isValidName(String name) {
329 for (Name n : getNames()) {
330 if (n.matches(name) && n.getVerificationPoints() >= 50) {
337 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
338 for (EmailAddress email : getEmails()) {
339 if (email.getAddress().equals(newMail.getAddress())) {
340 if ( !email.isVerified()) {
341 throw new GigiApiException("Email not verified.");
344 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
345 ps.setString(1, newMail.getAddress());
346 ps.setInt(2, getId());
350 this.email = newMail.getAddress();
355 throw new GigiApiException("Given address not an address of the user.");
358 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
359 if (getEmail().equals(delMail.getAddress())) {
360 throw new GigiApiException("Can't delete user's default e-mail.");
363 for (EmailAddress email : getEmails()) {
364 if (email.getId() == delMail.getId()) {
365 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
366 ps.setInt(1, delMail.getId());
372 throw new GigiApiException("Email not one of user's email addresses.");
375 public synchronized Verification[] getReceivedVerifications() {
376 if (receivedVerifications == null) {
377 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")) {
378 query.setInt(1, getId());
380 GigiResultSet res = query.executeQuery();
381 List<Verification> verifications = new LinkedList<Verification>();
384 verifications.add(verificationByRes(res));
387 this.receivedVerifications = verifications.toArray(new Verification[0]);
391 return receivedVerifications;
394 public synchronized Verification[] getMadeVerifications() {
395 if (madeVerifications == null) {
396 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
397 query.setInt(1, getId());
399 try (GigiResultSet res = query.executeQuery()) {
400 List<Verification> verifications = new LinkedList<Verification>();
403 verifications.add(verificationByRes(res));
406 this.madeVerifications = verifications.toArray(new Verification[0]);
411 return madeVerifications;
414 public synchronized void invalidateMadeVerifications() {
415 madeVerifications = null;
418 public synchronized void invalidateReceivedVerifications() {
419 receivedVerifications = null;
422 private void rawUpdateUserData() {
423 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
424 update.setDate(1, getDoB().toSQLDate());
425 update.setInt(2, getId());
426 update.executeUpdate();
430 public Locale getPreferredLocale() {
434 public void setPreferredLocale(Locale locale) {
435 this.locale = locale;
439 public synchronized Name getPreferredName() {
440 return preferredName;
443 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
444 if (preferred.getOwner() != this) {
445 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
447 this.preferredName = preferred;
448 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
449 ps.setInt(1, preferred.getId());
450 ps.setInt(2, getId());
456 public synchronized String getInitials() {
457 return preferredName.toInitialsString();
460 public boolean isInGroup(Group g) {
461 return groups.contains(g);
464 public Set<Group> getGroups() {
465 return Collections.unmodifiableSet(groups);
468 public void grantGroup(User granter, Group toGrant) throws GigiApiException {
469 if (toGrant.isManagedBySupport() && !granter.isInGroup(Group.SUPPORTER)) {
470 throw new GigiApiException("Group may only be managed by supporter");
472 if (toGrant.isManagedBySupport() && granter == this) {
473 throw new GigiApiException("Group may only be managed by supporter that is not oneself");
476 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
477 ps.setInt(1, getId());
478 ps.setEnum(2, toGrant);
479 ps.setInt(3, granter.getId());
484 public void revokeGroup(User revoker, Group toRevoke) throws GigiApiException {
485 if (toRevoke.isManagedBySupport() && !revoker.isInGroup(Group.SUPPORTER)) {
486 throw new GigiApiException("Group may only be managed by supporter");
488 groups.remove(toRevoke);
489 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
490 ps.setInt(1, revoker.getId());
491 ps.setEnum(2, toRevoke);
492 ps.setInt(3, getId());
497 public List<Organisation> getOrganisations() {
498 return getOrganisations(false);
501 public List<Organisation> getOrganisations(boolean isAdmin) {
502 List<Organisation> orgas = new ArrayList<>();
503 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
504 query.setInt(1, getId());
505 try (GigiResultSet res = query.executeQuery()) {
507 orgas.add(Organisation.getById(res.getInt(1)));
515 public static synchronized User getById(int id) {
516 CertificateOwner co = CertificateOwner.getById(id);
517 if (co instanceof User) {
524 public static User getByEmail(String mail) {
525 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
526 ps.setString(1, mail);
527 GigiResultSet rs = ps.executeQuery();
532 return User.getById(rs.getInt(1));
536 public static User[] findByEmail(String mail) {
537 LinkedList<User> results = new LinkedList<User>();
538 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")) {
539 ps.setString(1, mail);
540 GigiResultSet rs = ps.executeQuery();
542 results.add(User.getById(rs.getInt(1)));
544 return results.toArray(new User[results.size()]);
548 public EmailAddress[] getEmails() {
549 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
550 ps.setInt(1, getId());
552 GigiResultSet rs = ps.executeQuery();
553 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
556 data.add(EmailAddress.getById(rs.getInt(1)));
559 return data.toArray(new EmailAddress[0]);
564 public boolean isValidEmail(String email) {
565 for (EmailAddress em : getEmails()) {
566 if (em.getAddress().equals(email)) {
567 return em.isVerified();
574 public String[] getTrainings() {
575 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")) {
576 prep.setInt(1, getId());
577 GigiResultSet res = prep.executeQuery();
578 List<String> entries = new LinkedList<String>();
581 StringBuilder training = new StringBuilder();
582 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
583 training.append(" (");
584 training.append(res.getString(2));
585 if (res.getString(3).length() > 0) {
586 training.append(" ");
587 training.append(res.getString(3));
589 if (res.getString(4).length() > 0) {
590 training.append(", ");
591 training.append(res.getString(4));
593 training.append(")");
594 entries.add(training.toString());
597 return entries.toArray(new String[0]);
602 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
603 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
604 ps.setInt(1, getId());
605 ps.setInt(2, getId());
606 ps.setString(3, token);
607 ps.setString(4, PasswordHash.hash(privateToken));
609 return ps.lastInsertId();
613 public static User getResetWithToken(int id, String token) {
614 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")) {
616 ps.setString(2, token);
617 ps.setInt(3, PasswordResetPage.HOUR_MAX);
618 GigiResultSet res = ps.executeQuery();
622 return User.getById(res.getInt(1));
626 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
627 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
629 ps.setInt(2, getId());
630 GigiResultSet rs = ps.executeQuery();
632 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
634 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
635 throw new GigiApiException("Private token does not match.");
637 setPassword(newPassword);
639 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
645 private Verification verificationByRes(GigiResultSet res) {
647 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"));
648 } catch (GigiApiException e) {
653 public boolean isInVerificationLimit() {
654 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;")) {
655 ps.setInt(1, getId());
656 ps.setInt(2, VERIFICATION_MONTHS);
658 GigiResultSet rs = ps.executeQuery();
663 private void writeObject(ObjectOutputStream oos) throws IOException {}
665 private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {}
667 public Country getResidenceCountry() {
668 return residenceCountry;
671 public void setResidenceCountry(Country residenceCountry) {
672 this.residenceCountry = residenceCountry;
673 rawUpdateCountryData();
676 private void rawUpdateCountryData() {
677 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET country=? WHERE id=?")) {
678 update.setString(1, residenceCountry == null ? null : residenceCountry.getCode());
679 update.setInt(2, getId());
680 update.executeUpdate();
684 public boolean hasValidRAChallenge() {
685 return CATS.isInCatsLimit(getId(), CATSType.AGENT_CHALLENGE.getId());
688 public boolean hasValidSupportChallenge() {
689 return CATS.isInCatsLimit(getId(), CATSType.SUPPORT_DP_CHALLENGE_NAME.getId());
692 public boolean hasValidOrgAdminChallenge() {
693 return CATS.isInCatsLimit(getId(), CATSType.ORG_ADMIN_DP_CHALLENGE_NAME.getId());
696 public boolean hasValidOrgAgentChallenge() {
697 return CATS.isInCatsLimit(getId(), CATSType.ORG_AGENT_CHALLENGE.getId());
700 public boolean hasValidTTPAgentChallenge() {
701 return CATS.isInCatsLimit(getId(), CATSType.TTP_AGENT_CHALLENGE.getId());
704 public void writeUserLog(User actor, String type) throws GigiApiException {
705 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `adminLog` SET uid=?, admin=?, type=?")) {
706 prep.setInt(1, actor.getId());
707 prep.setInt(2, getId());
708 prep.setString(3, type);
709 prep.executeUpdate();