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 if ( !Contract.hasSignedContract(this, Contract.ContractType.RA_AGENT_CONTRACT)) {
249 return hasPassedCATS();
253 public boolean hasPassedCATS() {
254 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
255 query.setInt(1, getId());
256 query.setInt(2, CATSType.AGENT_CHALLENGE.getId());
257 try (GigiResultSet rs = query.executeQuery()) {
267 public int getVerificationPoints() {
268 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")) {
269 query.setInt(1, getId());
271 GigiResultSet rs = query.executeQuery();
275 points = rs.getInt(1);
282 public int getExperiencePoints() {
283 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")) {
284 query.setInt(1, getId());
285 query.setEnum(2, VerificationType.FACE_TO_FACE);
287 GigiResultSet rs = query.executeQuery();
291 points = rs.getInt(1) * EXPERIENCE_POINTS;
299 * Gets the maximum allowed points NOW. Note that a verification needs to
300 * re-check PoJam as it has taken place in the past.
302 * @return the maximal points @
304 @SuppressWarnings("unused")
305 public int getMaxVerifyPoints() {
306 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
310 int exp = getExperiencePoints();
313 if (exp >= 5 * EXPERIENCE_POINTS) {
316 if (exp >= 10 * EXPERIENCE_POINTS) {
319 if (exp >= 15 * EXPERIENCE_POINTS) {
322 if (exp >= 20 * EXPERIENCE_POINTS) {
325 if (exp >= 25 * EXPERIENCE_POINTS) {
332 public boolean isValidName(String name) {
333 for (Name n : getNames()) {
334 if (n.matches(name) && n.getVerificationPoints() >= 50) {
341 public boolean isValidNameVerification(String name) {
342 for (Name n : getNames()) {
343 if (n.matches(name) && n.isValidVerification()) {
350 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
351 for (EmailAddress email : getEmails()) {
352 if (email.getAddress().equals(newMail.getAddress())) {
353 if ( !email.isVerified()) {
354 throw new GigiApiException("Email not verified.");
357 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
358 ps.setString(1, newMail.getAddress());
359 ps.setInt(2, getId());
363 this.email = newMail.getAddress();
368 throw new GigiApiException("Given address not an address of the user.");
371 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
372 if (getEmail().equals(delMail.getAddress())) {
373 throw new GigiApiException("Can't delete user's default e-mail.");
376 for (EmailAddress email : getEmails()) {
377 if (email.getId() == delMail.getId()) {
378 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
379 ps.setInt(1, delMail.getId());
385 throw new GigiApiException("Email not one of user's email addresses.");
388 public synchronized Verification[] getReceivedVerifications() {
389 if (receivedVerifications == null) {
390 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")) {
391 query.setInt(1, getId());
393 GigiResultSet res = query.executeQuery();
394 List<Verification> verifications = new LinkedList<Verification>();
397 verifications.add(verificationByRes(res));
400 this.receivedVerifications = verifications.toArray(new Verification[0]);
404 return receivedVerifications;
407 public synchronized Verification[] getMadeVerifications() {
408 if (madeVerifications == null) {
409 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
410 query.setInt(1, getId());
412 try (GigiResultSet res = query.executeQuery()) {
413 List<Verification> verifications = new LinkedList<Verification>();
416 verifications.add(verificationByRes(res));
419 this.madeVerifications = verifications.toArray(new Verification[0]);
424 return madeVerifications;
427 public synchronized void invalidateMadeVerifications() {
428 madeVerifications = null;
431 public synchronized void invalidateReceivedVerifications() {
432 receivedVerifications = null;
435 private void rawUpdateUserData() {
436 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
437 update.setDate(1, getDoB().toSQLDate());
438 update.setInt(2, getId());
439 update.executeUpdate();
443 public Locale getPreferredLocale() {
447 public void setPreferredLocale(Locale locale) {
448 this.locale = locale;
452 public synchronized Name getPreferredName() {
453 return preferredName;
456 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
457 if (preferred.getOwner() != this) {
458 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
460 this.preferredName = preferred;
461 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
462 ps.setInt(1, preferred.getId());
463 ps.setInt(2, getId());
469 public synchronized String getInitials() {
470 return preferredName.toInitialsString();
473 public boolean isInGroup(Group g) {
474 return groups.contains(g);
477 public Set<Group> getGroups() {
478 return Collections.unmodifiableSet(groups);
481 public void grantGroup(User granter, Group toGrant) throws GigiApiException {
482 if (toGrant.isManagedBySupport() && !granter.isInGroup(Group.SUPPORTER)) {
483 throw new GigiApiException("Group may only be managed by supporter");
485 if (toGrant.isManagedBySupport() && granter == this) {
486 throw new GigiApiException("Group may only be managed by supporter that is not oneself");
489 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
490 ps.setInt(1, getId());
491 ps.setEnum(2, toGrant);
492 ps.setInt(3, granter.getId());
497 public void revokeGroup(User revoker, Group toRevoke) throws GigiApiException {
498 if (toRevoke.isManagedBySupport() && !revoker.isInGroup(Group.SUPPORTER)) {
499 throw new GigiApiException("Group may only be managed by supporter");
501 groups.remove(toRevoke);
502 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
503 ps.setInt(1, revoker.getId());
504 ps.setEnum(2, toRevoke);
505 ps.setInt(3, getId());
510 public List<Organisation> getOrganisations() {
511 return getOrganisations(false);
514 public List<Organisation> getOrganisations(boolean isAdmin) {
515 List<Organisation> orgas = new ArrayList<>();
516 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
517 query.setInt(1, getId());
518 try (GigiResultSet res = query.executeQuery()) {
520 orgas.add(Organisation.getById(res.getInt(1)));
528 public static synchronized User getById(int id) {
529 CertificateOwner co = CertificateOwner.getById(id);
530 if (co instanceof User) {
537 public static User getByEmail(String mail) {
538 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
539 ps.setString(1, mail);
540 GigiResultSet rs = ps.executeQuery();
545 return User.getById(rs.getInt(1));
549 public static User[] findByEmail(String mail) {
550 LinkedList<User> results = new LinkedList<User>();
551 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")) {
552 ps.setString(1, mail);
553 GigiResultSet rs = ps.executeQuery();
555 results.add(User.getById(rs.getInt(1)));
557 return results.toArray(new User[results.size()]);
561 public EmailAddress[] getEmails() {
562 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
563 ps.setInt(1, getId());
565 GigiResultSet rs = ps.executeQuery();
566 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
569 data.add(EmailAddress.getById(rs.getInt(1)));
572 return data.toArray(new EmailAddress[0]);
577 public boolean isValidEmail(String email) {
578 for (EmailAddress em : getEmails()) {
579 if (em.getAddress().equals(email)) {
580 return em.isVerified();
587 public String[] getTrainings() {
588 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")) {
589 prep.setInt(1, getId());
590 GigiResultSet res = prep.executeQuery();
591 List<String> entries = new LinkedList<String>();
594 StringBuilder training = new StringBuilder();
595 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
596 training.append(" (");
597 training.append(res.getString(2));
598 if (res.getString(3).length() > 0) {
599 training.append(" ");
600 training.append(res.getString(3));
602 if (res.getString(4).length() > 0) {
603 training.append(", ");
604 training.append(res.getString(4));
606 training.append(")");
607 entries.add(training.toString());
610 return entries.toArray(new String[0]);
615 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
616 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
617 ps.setInt(1, getId());
618 ps.setInt(2, getId());
619 ps.setString(3, token);
620 ps.setString(4, PasswordHash.hash(privateToken));
622 return ps.lastInsertId();
626 public static User getResetWithToken(int id, String token) {
627 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")) {
629 ps.setString(2, token);
630 ps.setInt(3, PasswordResetPage.HOUR_MAX);
631 GigiResultSet res = ps.executeQuery();
635 return User.getById(res.getInt(1));
639 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
640 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
642 ps.setInt(2, getId());
643 GigiResultSet rs = ps.executeQuery();
645 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
647 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
648 throw new GigiApiException("Private token does not match.");
650 setPassword(newPassword);
652 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
658 private Verification verificationByRes(GigiResultSet res) {
660 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"));
661 } catch (GigiApiException e) {
666 public boolean isInVerificationLimit() {
667 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;")) {
668 ps.setInt(1, getId());
669 ps.setInt(2, VERIFICATION_MONTHS);
671 GigiResultSet rs = ps.executeQuery();
676 private void writeObject(ObjectOutputStream oos) throws IOException {}
678 private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {}
680 public Country getResidenceCountry() {
681 return residenceCountry;
684 public void setResidenceCountry(Country residenceCountry) {
685 this.residenceCountry = residenceCountry;
686 rawUpdateCountryData();
689 private void rawUpdateCountryData() {
690 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET country=? WHERE id=?")) {
691 update.setString(1, residenceCountry == null ? null : residenceCountry.getCode());
692 update.setInt(2, getId());
693 update.executeUpdate();
697 public boolean hasValidRAChallenge() {
698 return CATS.isInCatsLimit(getId(), CATSType.AGENT_CHALLENGE.getId());
701 public boolean hasValidSupportChallenge() {
702 return CATS.isInCatsLimit(getId(), CATSType.SUPPORT_DP_CHALLENGE_NAME.getId());
705 public boolean hasValidOrgAdminChallenge() {
706 return CATS.isInCatsLimit(getId(), CATSType.ORG_ADMIN_DP_CHALLENGE_NAME.getId());
709 public boolean hasValidOrgAgentChallenge() {
710 return CATS.isInCatsLimit(getId(), CATSType.ORG_AGENT_CHALLENGE.getId());
713 public boolean hasValidTTPAgentChallenge() {
714 return CATS.isInCatsLimit(getId(), CATSType.TTP_AGENT_CHALLENGE.getId());
717 public void writeUserLog(User actor, String type) throws GigiApiException {
718 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `adminLog` SET uid=?, admin=?, type=?")) {
719 prep.setInt(1, actor.getId());
720 prep.setInt(2, getId());
721 prep.setString(3, type);
722 prep.executeUpdate();