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;
14 import club.wpia.gigi.GigiApiException;
15 import club.wpia.gigi.database.GigiPreparedStatement;
16 import club.wpia.gigi.database.GigiResultSet;
17 import club.wpia.gigi.dbObjects.CATS.CATSType;
18 import club.wpia.gigi.dbObjects.Country.CountryCodeType;
19 import club.wpia.gigi.dbObjects.Verification.VerificationType;
20 import club.wpia.gigi.email.EmailProvider;
21 import club.wpia.gigi.localisation.Language;
22 import club.wpia.gigi.output.DateSelector;
23 import club.wpia.gigi.pages.PasswordResetPage;
24 import club.wpia.gigi.util.CalendarUtil;
25 import club.wpia.gigi.util.DayDate;
26 import club.wpia.gigi.util.Notary;
27 import club.wpia.gigi.util.PasswordHash;
28 import club.wpia.gigi.util.PasswordStrengthChecker;
29 import club.wpia.gigi.util.TimeConditions;
32 * Represents an acting, verifiable user. Synchronizing on user means: no
33 * name-change and no verification.
35 public class User extends CertificateOwner {
37 private static final long serialVersionUID = -7915843843752264176L;
43 private Verification[] receivedVerifications;
45 private Verification[] madeVerifications;
47 private Locale locale;
49 private Set<Group> groups = new HashSet<>();
51 public static final int MINIMUM_AGE = 16;
53 public static final int MAXIMUM_PLAUSIBLE_AGE = 120;
55 public static final int POJAM_AGE = 14;
57 public static final int ADULT_AGE = 18;
59 public static final boolean POJAM_ENABLED = false;
61 public static final int EXPERIENCE_POINTS = 4;
64 * Time in months a verification is considered "recent".
66 public static final int VERIFICATION_MONTHS = TimeConditions.getInstance().getVerificationMonths();
68 private Name preferredName;
70 private Country residenceCountry;
72 protected User(GigiResultSet rs) throws GigiApiException {
73 super(rs.getInt("id"));
75 dob = new DayDate(rs.getDate("dob"));
76 email = rs.getString("email");
77 preferredName = Name.getById(rs.getInt("preferredName"));
79 if (rs.getString("country") != null) {
80 residenceCountry = Country.getCountryByCode(rs.getString("Country"), Country.CountryCodeType.CODE_2_CHARS);
83 String localeStr = rs.getString("language");
84 if (localeStr == null || localeStr.equals("")) {
85 locale = Locale.getDefault();
87 locale = Language.getLocaleFromString(localeStr);
93 public synchronized void refreshGroups() {
94 HashSet<Group> hs = new HashSet<>();
95 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
96 psg.setInt(1, getId());
98 try (GigiResultSet rs2 = psg.executeQuery()) {
100 hs.add(Group.getByString(rs2.getString(1)));
107 public User(String email, String password, DayDate dob, Locale locale, Country residenceCountry, NamePart... preferred) throws GigiApiException {
108 super(validate(email));
112 this.locale = locale;
113 this.preferredName = new Name(this, preferred);
114 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?, `country` = ?")) {
115 query.setString(1, email);
116 query.setString(2, PasswordHash.hash(password));
117 query.setDate(3, dob.toSQLDate());
118 query.setString(4, locale.toString());
119 query.setInt(5, getId());
120 query.setInt(6, preferredName.getId());
121 query.setString(7, residenceCountry == null ? null : residenceCountry.getCode());
125 new EmailAddress(this, email, locale);
128 private static Void validate(String email) {
129 // Avoid storing information that obviously won't get through
130 if ( !EmailProvider.isValidMailAddress(email)) {
131 throw new IllegalArgumentException("Invalid email.");
136 public Name[] getNames() {
137 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
138 gps.setInt(1, getId());
139 return fetchNamesToArray(gps);
143 public Name[] getNonDeprecatedNames() {
144 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL AND `deprecated` IS NULL", true)) {
145 gps.setInt(1, getId());
146 return fetchNamesToArray(gps);
150 private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
151 GigiResultSet rs = gps.executeQuery();
153 Name[] dt = new Name[rs.getRow()];
155 for (int i = 0; rs.next(); i++) {
156 dt[i] = Name.getById(rs.getInt(1));
161 public DayDate getDoB() {
165 public void setDoB(DayDate dob) throws GigiApiException {
166 synchronized (Notary.class) {
167 if (getReceivedVerifications().length != 0) {
168 throw new GigiApiException("No change after verification allowed.");
171 if ( !CalendarUtil.isOfAge(dob, User.MINIMUM_AGE)) {
172 throw new GigiApiException("Entered date of birth is below the restricted age requirements.");
175 if (CalendarUtil.isYearsInFuture(dob.end(), User.MAXIMUM_PLAUSIBLE_AGE)) {
176 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.");
184 protected void setDoBAsSupport(DayDate dob) throws GigiApiException {
185 synchronized (Notary.class) {
192 public String getEmail() {
196 public void changePassword(String oldPass, String newPass) throws GigiApiException {
197 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
198 ps.setInt(1, getId());
199 try (GigiResultSet rs = ps.executeQuery()) {
201 throw new GigiApiException("User not found... very bad.");
203 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
204 throw new GigiApiException("Old password does not match.");
208 setPassword(newPass);
211 private void setPassword(String newPass) throws GigiApiException {
212 PasswordStrengthChecker.assertStrongPassword(newPass, getNames(), getEmail());
213 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
214 ps.setString(1, PasswordHash.hash(newPass));
215 ps.setInt(2, getId());
220 public boolean canVerify() {
222 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
226 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
230 if (getVerificationPoints() < 100) {
234 return hasPassedCATS();
238 public boolean hasPassedCATS() {
239 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
240 query.setInt(1, getId());
241 query.setInt(2, CATSType.AGENT_CHALLENGE.getId());
242 try (GigiResultSet rs = query.executeQuery()) {
252 public int getVerificationPoints() {
253 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")) {
254 query.setInt(1, getId());
256 GigiResultSet rs = query.executeQuery();
260 points = rs.getInt(1);
267 public int getExperiencePoints() {
268 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")) {
269 query.setInt(1, getId());
270 query.setEnum(2, VerificationType.FACE_TO_FACE);
272 GigiResultSet rs = query.executeQuery();
276 points = rs.getInt(1) * EXPERIENCE_POINTS;
284 * Gets the maximum allowed points NOW. Note that a verification needs to
285 * re-check PoJam as it has taken place in the past.
287 * @return the maximal points @
289 @SuppressWarnings("unused")
290 public int getMaxVerifyPoints() {
291 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
295 int exp = getExperiencePoints();
298 if (exp >= 5 * EXPERIENCE_POINTS) {
301 if (exp >= 10 * EXPERIENCE_POINTS) {
304 if (exp >= 15 * EXPERIENCE_POINTS) {
307 if (exp >= 20 * EXPERIENCE_POINTS) {
310 if (exp >= 25 * EXPERIENCE_POINTS) {
317 public boolean isValidName(String name) {
318 for (Name n : getNames()) {
319 if (n.matches(name) && n.getVerificationPoints() >= 50) {
326 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
327 for (EmailAddress email : getEmails()) {
328 if (email.getAddress().equals(newMail.getAddress())) {
329 if ( !email.isVerified()) {
330 throw new GigiApiException("Email not verified.");
333 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
334 ps.setString(1, newMail.getAddress());
335 ps.setInt(2, getId());
339 this.email = newMail.getAddress();
344 throw new GigiApiException("Given address not an address of the user.");
347 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
348 if (getEmail().equals(delMail.getAddress())) {
349 throw new GigiApiException("Can't delete user's default e-mail.");
352 for (EmailAddress email : getEmails()) {
353 if (email.getId() == delMail.getId()) {
354 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
355 ps.setInt(1, delMail.getId());
361 throw new GigiApiException("Email not one of user's email addresses.");
364 public synchronized Verification[] getReceivedVerifications() {
365 if (receivedVerifications == null) {
366 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")) {
367 query.setInt(1, getId());
369 GigiResultSet res = query.executeQuery();
370 List<Verification> verifications = new LinkedList<Verification>();
373 verifications.add(verificationByRes(res));
376 this.receivedVerifications = verifications.toArray(new Verification[0]);
380 return receivedVerifications;
383 public synchronized Verification[] getMadeVerifications() {
384 if (madeVerifications == null) {
385 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
386 query.setInt(1, getId());
388 try (GigiResultSet res = query.executeQuery()) {
389 List<Verification> verifications = new LinkedList<Verification>();
392 verifications.add(verificationByRes(res));
395 this.madeVerifications = verifications.toArray(new Verification[0]);
400 return madeVerifications;
403 public synchronized void invalidateMadeVerifications() {
404 madeVerifications = null;
407 public synchronized void invalidateReceivedVerifications() {
408 receivedVerifications = null;
411 private void rawUpdateUserData() {
412 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
413 update.setDate(1, getDoB().toSQLDate());
414 update.setInt(2, getId());
415 update.executeUpdate();
419 public Locale getPreferredLocale() {
423 public void setPreferredLocale(Locale locale) {
424 this.locale = locale;
428 public synchronized Name getPreferredName() {
429 return preferredName;
432 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
433 if (preferred.getOwner() != this) {
434 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
436 this.preferredName = preferred;
437 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
438 ps.setInt(1, preferred.getId());
439 ps.setInt(2, getId());
445 public boolean isInGroup(Group g) {
446 return groups.contains(g);
449 public Set<Group> getGroups() {
450 return Collections.unmodifiableSet(groups);
453 public void grantGroup(User granter, Group toGrant) throws GigiApiException {
454 if (toGrant.isManagedBySupport() && !granter.isInGroup(Group.SUPPORTER)) {
455 throw new GigiApiException("Group may only be managed by supporter");
457 if (toGrant.isManagedBySupport() && granter == this) {
458 throw new GigiApiException("Group may only be managed by supporter that is not oneself");
461 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
462 ps.setInt(1, getId());
463 ps.setEnum(2, toGrant);
464 ps.setInt(3, granter.getId());
469 public void revokeGroup(User revoker, Group toRevoke) throws GigiApiException {
470 if (toRevoke.isManagedBySupport() && !revoker.isInGroup(Group.SUPPORTER)) {
471 throw new GigiApiException("Group may only be managed by supporter");
473 groups.remove(toRevoke);
474 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
475 ps.setInt(1, revoker.getId());
476 ps.setEnum(2, toRevoke);
477 ps.setInt(3, getId());
482 public List<Organisation> getOrganisations() {
483 return getOrganisations(false);
486 public List<Organisation> getOrganisations(boolean isAdmin) {
487 List<Organisation> orgas = new ArrayList<>();
488 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
489 query.setInt(1, getId());
490 try (GigiResultSet res = query.executeQuery()) {
492 orgas.add(Organisation.getById(res.getInt(1)));
500 public static synchronized User getById(int id) {
501 CertificateOwner co = CertificateOwner.getById(id);
502 if (co instanceof User) {
509 public static User getByEmail(String mail) {
510 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
511 ps.setString(1, mail);
512 GigiResultSet rs = ps.executeQuery();
517 return User.getById(rs.getInt(1));
521 public static User[] findByEmail(String mail) {
522 LinkedList<User> results = new LinkedList<User>();
523 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")) {
524 ps.setString(1, mail);
525 GigiResultSet rs = ps.executeQuery();
527 results.add(User.getById(rs.getInt(1)));
529 return results.toArray(new User[results.size()]);
533 public EmailAddress[] getEmails() {
534 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
535 ps.setInt(1, getId());
537 GigiResultSet rs = ps.executeQuery();
538 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
541 data.add(EmailAddress.getById(rs.getInt(1)));
544 return data.toArray(new EmailAddress[0]);
549 public boolean isValidEmail(String email) {
550 for (EmailAddress em : getEmails()) {
551 if (em.getAddress().equals(email)) {
552 return em.isVerified();
559 public String[] getTrainings() {
560 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")) {
561 prep.setInt(1, getId());
562 GigiResultSet res = prep.executeQuery();
563 List<String> entries = new LinkedList<String>();
566 StringBuilder training = new StringBuilder();
567 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
568 training.append(" (");
569 training.append(res.getString(2));
570 if (res.getString(3).length() > 0) {
571 training.append(" ");
572 training.append(res.getString(3));
574 if (res.getString(4).length() > 0) {
575 training.append(", ");
576 training.append(res.getString(4));
578 training.append(")");
579 entries.add(training.toString());
582 return entries.toArray(new String[0]);
587 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
588 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
589 ps.setInt(1, getId());
590 ps.setInt(2, getId());
591 ps.setString(3, token);
592 ps.setString(4, PasswordHash.hash(privateToken));
594 return ps.lastInsertId();
598 public static User getResetWithToken(int id, String token) {
599 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")) {
601 ps.setString(2, token);
602 ps.setInt(3, PasswordResetPage.HOUR_MAX);
603 GigiResultSet res = ps.executeQuery();
607 return User.getById(res.getInt(1));
611 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
612 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
614 ps.setInt(2, getId());
615 GigiResultSet rs = ps.executeQuery();
617 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
619 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
620 throw new GigiApiException("Private token does not match.");
622 setPassword(newPassword);
624 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
630 private Verification verificationByRes(GigiResultSet res) {
632 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"));
633 } catch (GigiApiException e) {
638 public boolean isInVerificationLimit() {
639 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;")) {
640 ps.setInt(1, getId());
641 ps.setInt(2, VERIFICATION_MONTHS);
643 GigiResultSet rs = ps.executeQuery();
648 private void writeObject(ObjectOutputStream oos) throws IOException {}
650 private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {}
652 public Country getResidenceCountry() {
653 return residenceCountry;
656 public void setResidenceCountry(Country residenceCountry) {
657 this.residenceCountry = residenceCountry;
658 rawUpdateCountryData();
661 private void rawUpdateCountryData() {
662 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET country=? WHERE id=?")) {
663 update.setString(1, residenceCountry == null ? null : residenceCountry.getCode());
664 update.setInt(2, getId());
665 update.executeUpdate();