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 // Avoid storing information that obviously won't get through
109 if ( !EmailProvider.isValidMailAddress(email)) {
110 throw new IllegalArgumentException("Invalid email.");
115 this.locale = locale;
116 this.preferredName = new Name(this, preferred);
117 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?, `country` = ?")) {
118 query.setString(1, email);
119 query.setString(2, PasswordHash.hash(password));
120 query.setDate(3, dob.toSQLDate());
121 query.setString(4, locale.toString());
122 query.setInt(5, getId());
123 query.setInt(6, preferredName.getId());
124 query.setString(7, residenceCountry == null ? null : residenceCountry.getCode());
128 new EmailAddress(this, email, locale);
131 public Name[] getNames() {
132 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
133 gps.setInt(1, getId());
134 return fetchNamesToArray(gps);
138 public Name[] getNonDeprecatedNames() {
139 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL AND `deprecated` IS NULL", true)) {
140 gps.setInt(1, getId());
141 return fetchNamesToArray(gps);
145 private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
146 GigiResultSet rs = gps.executeQuery();
148 Name[] dt = new Name[rs.getRow()];
150 for (int i = 0; rs.next(); i++) {
151 dt[i] = Name.getById(rs.getInt(1));
156 public DayDate getDoB() {
160 public void setDoB(DayDate dob) throws GigiApiException {
161 synchronized (Notary.class) {
162 if (getReceivedVerifications().length != 0) {
163 throw new GigiApiException("No change after verification allowed.");
166 if ( !CalendarUtil.isOfAge(dob, User.MINIMUM_AGE)) {
167 throw new GigiApiException("Entered date of birth is below the restricted age requirements.");
170 if (CalendarUtil.isYearsInFuture(dob.end(), User.MAXIMUM_PLAUSIBLE_AGE)) {
171 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.");
179 protected void setDoBAsSupport(DayDate dob) throws GigiApiException {
180 synchronized (Notary.class) {
187 public String getEmail() {
191 public void changePassword(String oldPass, String newPass) throws GigiApiException {
192 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
193 ps.setInt(1, getId());
194 try (GigiResultSet rs = ps.executeQuery()) {
196 throw new GigiApiException("User not found... very bad.");
198 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
199 throw new GigiApiException("Old password does not match.");
203 setPassword(newPass);
206 private void setPassword(String newPass) throws GigiApiException {
207 PasswordStrengthChecker.assertStrongPassword(newPass, getNames(), getEmail());
208 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
209 ps.setString(1, PasswordHash.hash(newPass));
210 ps.setInt(2, getId());
215 public boolean canVerify() {
217 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
221 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
225 if (getVerificationPoints() < 100) {
229 return hasPassedCATS();
233 public boolean hasPassedCATS() {
234 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
235 query.setInt(1, getId());
236 query.setInt(2, CATSType.AGENT_CHALLENGE.getId());
237 try (GigiResultSet rs = query.executeQuery()) {
247 public int getVerificationPoints() {
248 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")) {
249 query.setInt(1, getId());
251 GigiResultSet rs = query.executeQuery();
255 points = rs.getInt(1);
262 public int getExperiencePoints() {
263 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")) {
264 query.setInt(1, getId());
265 query.setEnum(2, VerificationType.FACE_TO_FACE);
267 GigiResultSet rs = query.executeQuery();
271 points = rs.getInt(1) * EXPERIENCE_POINTS;
279 * Gets the maximum allowed points NOW. Note that a verification needs to
280 * re-check PoJam as it has taken place in the past.
282 * @return the maximal points @
284 @SuppressWarnings("unused")
285 public int getMaxVerifyPoints() {
286 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
290 int exp = getExperiencePoints();
293 if (exp >= 5 * EXPERIENCE_POINTS) {
296 if (exp >= 10 * EXPERIENCE_POINTS) {
299 if (exp >= 15 * EXPERIENCE_POINTS) {
302 if (exp >= 20 * EXPERIENCE_POINTS) {
305 if (exp >= 25 * EXPERIENCE_POINTS) {
312 public boolean isValidName(String name) {
313 for (Name n : getNames()) {
314 if (n.matches(name) && n.getVerificationPoints() >= 50) {
321 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
322 for (EmailAddress email : getEmails()) {
323 if (email.getAddress().equals(newMail.getAddress())) {
324 if ( !email.isVerified()) {
325 throw new GigiApiException("Email not verified.");
328 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
329 ps.setString(1, newMail.getAddress());
330 ps.setInt(2, getId());
334 this.email = newMail.getAddress();
339 throw new GigiApiException("Given address not an address of the user.");
342 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
343 if (getEmail().equals(delMail.getAddress())) {
344 throw new GigiApiException("Can't delete user's default e-mail.");
347 for (EmailAddress email : getEmails()) {
348 if (email.getId() == delMail.getId()) {
349 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
350 ps.setInt(1, delMail.getId());
356 throw new GigiApiException("Email not one of user's email addresses.");
359 public synchronized Verification[] getReceivedVerifications() {
360 if (receivedVerifications == null) {
361 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")) {
362 query.setInt(1, getId());
364 GigiResultSet res = query.executeQuery();
365 List<Verification> verifications = new LinkedList<Verification>();
368 verifications.add(verificationByRes(res));
371 this.receivedVerifications = verifications.toArray(new Verification[0]);
375 return receivedVerifications;
378 public synchronized Verification[] getMadeVerifications() {
379 if (madeVerifications == null) {
380 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
381 query.setInt(1, getId());
383 try (GigiResultSet res = query.executeQuery()) {
384 List<Verification> verifications = new LinkedList<Verification>();
387 verifications.add(verificationByRes(res));
390 this.madeVerifications = verifications.toArray(new Verification[0]);
395 return madeVerifications;
398 public synchronized void invalidateMadeVerifications() {
399 madeVerifications = null;
402 public synchronized void invalidateReceivedVerifications() {
403 receivedVerifications = null;
406 private void rawUpdateUserData() {
407 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
408 update.setDate(1, getDoB().toSQLDate());
409 update.setInt(2, getId());
410 update.executeUpdate();
414 public Locale getPreferredLocale() {
418 public void setPreferredLocale(Locale locale) {
419 this.locale = locale;
423 public synchronized Name getPreferredName() {
424 return preferredName;
427 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
428 if (preferred.getOwner() != this) {
429 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
431 this.preferredName = preferred;
432 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
433 ps.setInt(1, preferred.getId());
434 ps.setInt(2, getId());
440 public boolean isInGroup(Group g) {
441 return groups.contains(g);
444 public Set<Group> getGroups() {
445 return Collections.unmodifiableSet(groups);
448 public void grantGroup(User granter, Group toGrant) throws GigiApiException {
449 if (toGrant.isManagedBySupport() && !granter.isInGroup(Group.SUPPORTER)) {
450 throw new GigiApiException("Group may only be managed by supporter");
452 if (toGrant.isManagedBySupport() && granter == this) {
453 throw new GigiApiException("Group may only be managed by supporter that is not oneself");
456 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
457 ps.setInt(1, getId());
458 ps.setEnum(2, toGrant);
459 ps.setInt(3, granter.getId());
464 public void revokeGroup(User revoker, Group toRevoke) throws GigiApiException {
465 if (toRevoke.isManagedBySupport() && !revoker.isInGroup(Group.SUPPORTER)) {
466 throw new GigiApiException("Group may only be managed by supporter");
468 groups.remove(toRevoke);
469 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
470 ps.setInt(1, revoker.getId());
471 ps.setEnum(2, toRevoke);
472 ps.setInt(3, getId());
477 public List<Organisation> getOrganisations() {
478 return getOrganisations(false);
481 public List<Organisation> getOrganisations(boolean isAdmin) {
482 List<Organisation> orgas = new ArrayList<>();
483 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
484 query.setInt(1, getId());
485 try (GigiResultSet res = query.executeQuery()) {
487 orgas.add(Organisation.getById(res.getInt(1)));
495 public static synchronized User getById(int id) {
496 CertificateOwner co = CertificateOwner.getById(id);
497 if (co instanceof User) {
504 public static User getByEmail(String mail) {
505 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
506 ps.setString(1, mail);
507 GigiResultSet rs = ps.executeQuery();
512 return User.getById(rs.getInt(1));
516 public static User[] findByEmail(String mail) {
517 LinkedList<User> results = new LinkedList<User>();
518 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")) {
519 ps.setString(1, mail);
520 GigiResultSet rs = ps.executeQuery();
522 results.add(User.getById(rs.getInt(1)));
524 return results.toArray(new User[results.size()]);
528 public EmailAddress[] getEmails() {
529 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
530 ps.setInt(1, getId());
532 GigiResultSet rs = ps.executeQuery();
533 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
536 data.add(EmailAddress.getById(rs.getInt(1)));
539 return data.toArray(new EmailAddress[0]);
544 public boolean isValidEmail(String email) {
545 for (EmailAddress em : getEmails()) {
546 if (em.getAddress().equals(email)) {
547 return em.isVerified();
554 public String[] getTrainings() {
555 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")) {
556 prep.setInt(1, getId());
557 GigiResultSet res = prep.executeQuery();
558 List<String> entries = new LinkedList<String>();
561 StringBuilder training = new StringBuilder();
562 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
563 training.append(" (");
564 training.append(res.getString(2));
565 if (res.getString(3).length() > 0) {
566 training.append(" ");
567 training.append(res.getString(3));
569 if (res.getString(4).length() > 0) {
570 training.append(", ");
571 training.append(res.getString(4));
573 training.append(")");
574 entries.add(training.toString());
577 return entries.toArray(new String[0]);
582 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
583 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
584 ps.setInt(1, getId());
585 ps.setInt(2, getId());
586 ps.setString(3, token);
587 ps.setString(4, PasswordHash.hash(privateToken));
589 return ps.lastInsertId();
593 public static User getResetWithToken(int id, String token) {
594 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")) {
596 ps.setString(2, token);
597 ps.setInt(3, PasswordResetPage.HOUR_MAX);
598 GigiResultSet res = ps.executeQuery();
602 return User.getById(res.getInt(1));
606 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
607 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
609 ps.setInt(2, getId());
610 GigiResultSet rs = ps.executeQuery();
612 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
614 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
615 throw new GigiApiException("Private token does not match.");
617 setPassword(newPassword);
619 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
625 private Verification verificationByRes(GigiResultSet res) {
627 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"));
628 } catch (GigiApiException e) {
633 public boolean isInVerificationLimit() {
634 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;")) {
635 ps.setInt(1, getId());
636 ps.setInt(2, VERIFICATION_MONTHS);
638 GigiResultSet rs = ps.executeQuery();
643 private void writeObject(ObjectOutputStream oos) throws IOException {}
645 private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {}
647 public Country getResidenceCountry() {
648 return residenceCountry;
651 public void setResidenceCountry(Country residenceCountry) {
652 this.residenceCountry = residenceCountry;
653 rawUpdateCountryData();
656 private void rawUpdateCountryData() {
657 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET country=? WHERE id=?")) {
658 update.setString(1, residenceCountry == null ? null : residenceCountry.getCode());
659 update.setInt(2, getId());
660 update.executeUpdate();