1 package org.cacert.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 org.cacert.gigi.GigiApiException;
15 import org.cacert.gigi.database.GigiPreparedStatement;
16 import org.cacert.gigi.database.GigiResultSet;
17 import org.cacert.gigi.dbObjects.Assurance.AssuranceType;
18 import org.cacert.gigi.dbObjects.CATS.CATSType;
19 import org.cacert.gigi.localisation.Language;
20 import org.cacert.gigi.output.DateSelector;
21 import org.cacert.gigi.pages.PasswordResetPage;
22 import org.cacert.gigi.util.CalendarUtil;
23 import org.cacert.gigi.util.DayDate;
24 import org.cacert.gigi.util.Notary;
25 import org.cacert.gigi.util.PasswordHash;
26 import org.cacert.gigi.util.PasswordStrengthChecker;
27 import org.cacert.gigi.util.TimeConditions;
30 * Represents an acting, assurable, user. Synchronizing on user means: no
31 * name-change and no assurance.
33 public class User extends CertificateOwner {
35 private static final long serialVersionUID = -7915843843752264176L;
41 private Assurance[] receivedAssurances;
43 private Assurance[] madeAssurances;
45 private Locale locale;
47 private final Set<Group> groups = new HashSet<>();
49 public static final int MINIMUM_AGE = 16;
51 public static final int MAXIMUM_PLAUSIBLE_AGE = 120;
53 public static final int POJAM_AGE = 14;
55 public static final int ADULT_AGE = 18;
57 public static final boolean POJAM_ENABLED = false;
59 public static final int EXPERIENCE_POINTS = 4;
62 * Time in months a verification is considered "recent".
64 public static final int VERIFICATION_MONTHS = TimeConditions.getInstance().getVerificationMonths();
66 private Name preferredName;
68 protected User(GigiResultSet rs) {
69 super(rs.getInt("id"));
73 private void updateName(GigiResultSet rs) {
74 dob = new DayDate(rs.getDate("dob"));
75 email = rs.getString("email");
76 preferredName = Name.getById(rs.getInt("preferredName"));
78 String localeStr = rs.getString("language");
79 if (localeStr == null || localeStr.equals("")) {
80 locale = Locale.getDefault();
82 locale = Language.getLocaleFromString(localeStr);
85 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
86 psg.setInt(1, rs.getInt("id"));
88 try (GigiResultSet rs2 = psg.executeQuery()) {
90 groups.add(Group.getByString(rs2.getString(1)));
96 public User(String email, String password, DayDate dob, Locale locale, NamePart... preferred) throws GigiApiException {
100 this.preferredName = new Name(this, preferred);
101 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?")) {
102 query.setString(1, email);
103 query.setString(2, PasswordHash.hash(password));
104 query.setDate(3, dob.toSQLDate());
105 query.setString(4, locale.toString());
106 query.setInt(5, getId());
107 query.setInt(6, preferredName.getId());
110 new EmailAddress(this, email, locale);
113 public Name[] getNames() {
114 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
115 return fetchNamesToArray(gps);
119 public Name[] getNonDeprecatedNames() {
120 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL AND `deprecated` IS NULL", true)) {
121 return fetchNamesToArray(gps);
125 private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
126 gps.setInt(1, getId());
127 GigiResultSet rs = gps.executeQuery();
129 Name[] dt = new Name[rs.getRow()];
131 for (int i = 0; rs.next(); i++) {
132 dt[i] = Name.getById(rs.getInt(1));
137 public DayDate getDoB() {
141 public void setDoB(DayDate dob) throws GigiApiException {
142 synchronized (Notary.class) {
143 if (getReceivedAssurances().length != 0) {
144 throw new GigiApiException("No change after verification allowed.");
147 if ( !CalendarUtil.isOfAge(dob, User.MINIMUM_AGE)) {
148 throw new GigiApiException("Entered date of birth is below the restricted age requirements.");
151 if (CalendarUtil.isOfAge(dob, User.MAXIMUM_PLAUSIBLE_AGE)) {
152 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.");
160 protected void setDoBAsSupport(DayDate dob) throws GigiApiException {
161 synchronized (Notary.class) {
168 public String getEmail() {
172 public void changePassword(String oldPass, String newPass) throws GigiApiException {
173 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
174 ps.setInt(1, getId());
175 try (GigiResultSet rs = ps.executeQuery()) {
177 throw new GigiApiException("User not found... very bad.");
179 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
180 throw new GigiApiException("Old password does not match.");
184 setPassword(newPass);
187 private void setPassword(String newPass) throws GigiApiException {
188 PasswordStrengthChecker.assertStrongPassword(newPass, getNames(), getEmail());
189 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
190 ps.setString(1, PasswordHash.hash(newPass));
191 ps.setInt(2, getId());
196 public boolean canAssure() {
198 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
202 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
206 if (getAssurancePoints() < 100) {
210 return hasPassedCATS();
214 public boolean hasPassedCATS() {
215 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
216 query.setInt(1, getId());
217 query.setInt(2, CATSType.ASSURER_CHALLENGE.getId());
218 try (GigiResultSet rs = query.executeQuery()) {
228 public int getAssurancePoints() {
229 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT SUM(lastpoints) FROM ( SELECT DISTINCT ON (`from`) `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`, `when` DESC) as p")) {
230 query.setInt(1, getId());
232 GigiResultSet rs = query.executeQuery();
236 points = rs.getInt(1);
243 public int getExperiencePoints() {
244 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")) {
245 query.setInt(1, getId());
246 query.setString(2, AssuranceType.FACE_TO_FACE.getDescription());
248 GigiResultSet rs = query.executeQuery();
252 points = rs.getInt(1) * EXPERIENCE_POINTS;
260 * Gets the maximum allowed points NOW. Note that an assurance needs to
261 * re-check PoJam as it has taken place in the past.
263 * @return the maximal points @
265 @SuppressWarnings("unused")
266 public int getMaxAssurePoints() {
267 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
271 int exp = getExperiencePoints();
274 if (exp >= 5 * EXPERIENCE_POINTS) {
277 if (exp >= 10 * EXPERIENCE_POINTS) {
280 if (exp >= 15 * EXPERIENCE_POINTS) {
283 if (exp >= 20 * EXPERIENCE_POINTS) {
286 if (exp >= 25 * EXPERIENCE_POINTS) {
293 public boolean isValidName(String name) {
294 for (Name n : getNames()) {
295 if (n.matches(name) && n.getAssurancePoints() >= 50) {
302 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
303 for (EmailAddress email : getEmails()) {
304 if (email.getAddress().equals(newMail.getAddress())) {
305 if ( !email.isVerified()) {
306 throw new GigiApiException("Email not verified.");
309 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
310 ps.setString(1, newMail.getAddress());
311 ps.setInt(2, getId());
315 this.email = newMail.getAddress();
320 throw new GigiApiException("Given address not an address of the user.");
323 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
324 if (getEmail().equals(delMail.getAddress())) {
325 throw new GigiApiException("Can't delete user's default e-mail.");
328 for (EmailAddress email : getEmails()) {
329 if (email.getId() == delMail.getId()) {
330 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
331 ps.setInt(1, delMail.getId());
337 throw new GigiApiException("Email not one of user's email addresses.");
340 public synchronized Assurance[] getReceivedAssurances() {
341 if (receivedAssurances == null) {
342 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")) {
343 query.setInt(1, getId());
345 GigiResultSet res = query.executeQuery();
346 List<Assurance> assurances = new LinkedList<Assurance>();
349 assurances.add(assuranceByRes(res));
352 this.receivedAssurances = assurances.toArray(new Assurance[0]);
356 return receivedAssurances;
359 public synchronized Assurance[] getMadeAssurances() {
360 if (madeAssurances == null) {
361 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
362 query.setInt(1, getId());
364 try (GigiResultSet res = query.executeQuery()) {
365 List<Assurance> assurances = new LinkedList<Assurance>();
368 assurances.add(assuranceByRes(res));
371 this.madeAssurances = assurances.toArray(new Assurance[0]);
376 return madeAssurances;
379 public synchronized void invalidateMadeAssurances() {
380 madeAssurances = null;
383 public synchronized void invalidateReceivedAssurances() {
384 receivedAssurances = null;
387 private void rawUpdateUserData() {
388 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
389 update.setDate(1, getDoB().toSQLDate());
390 update.setInt(2, getId());
391 update.executeUpdate();
395 public Locale getPreferredLocale() {
399 public void setPreferredLocale(Locale locale) {
400 this.locale = locale;
404 public synchronized Name getPreferredName() {
405 return preferredName;
408 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
409 if (preferred.getOwner() != this) {
410 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
412 this.preferredName = preferred;
413 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
414 ps.setInt(1, preferred.getId());
415 ps.setInt(2, getId());
421 public boolean isInGroup(Group g) {
422 return groups.contains(g);
425 public Set<Group> getGroups() {
426 return Collections.unmodifiableSet(groups);
429 public void grantGroup(User granter, Group toGrant) {
431 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
432 ps.setInt(1, getId());
433 ps.setString(2, toGrant.getDatabaseName());
434 ps.setInt(3, granter.getId());
439 public void revokeGroup(User revoker, Group toRevoke) {
440 groups.remove(toRevoke);
441 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
442 ps.setInt(1, revoker.getId());
443 ps.setString(2, toRevoke.getDatabaseName());
444 ps.setInt(3, getId());
449 public List<Organisation> getOrganisations() {
450 return getOrganisations(false);
453 public List<Organisation> getOrganisations(boolean isAdmin) {
454 List<Organisation> orgas = new ArrayList<>();
455 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
456 query.setInt(1, getId());
457 try (GigiResultSet res = query.executeQuery()) {
459 orgas.add(Organisation.getById(res.getInt(1)));
467 public static synchronized User getById(int id) {
468 CertificateOwner co = CertificateOwner.getById(id);
469 if (co instanceof User) {
476 public static User getByEmail(String mail) {
477 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
478 ps.setString(1, mail);
479 GigiResultSet rs = ps.executeQuery();
484 return User.getById(rs.getInt(1));
488 public static User[] findByEmail(String mail) {
489 LinkedList<User> results = new LinkedList<User>();
490 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")) {
491 ps.setString(1, mail);
492 GigiResultSet rs = ps.executeQuery();
494 results.add(User.getById(rs.getInt(1)));
496 return results.toArray(new User[results.size()]);
500 public EmailAddress[] getEmails() {
501 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
502 ps.setInt(1, getId());
504 GigiResultSet rs = ps.executeQuery();
505 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
508 data.add(EmailAddress.getById(rs.getInt(1)));
511 return data.toArray(new EmailAddress[0]);
516 public boolean isValidEmail(String email) {
517 for (EmailAddress em : getEmails()) {
518 if (em.getAddress().equals(email)) {
519 return em.isVerified();
526 public String[] getTrainings() {
527 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")) {
528 prep.setInt(1, getId());
529 GigiResultSet res = prep.executeQuery();
530 List<String> entries = new LinkedList<String>();
533 StringBuilder training = new StringBuilder();
534 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
535 training.append(" (");
536 training.append(res.getString(2));
537 if (res.getString(3).length() > 0) {
538 training.append(" ");
539 training.append(res.getString(3));
541 if (res.getString(4).length() > 0) {
542 training.append(", ");
543 training.append(res.getString(4));
545 training.append(")");
546 entries.add(training.toString());
549 return entries.toArray(new String[0]);
554 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
555 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
556 ps.setInt(1, getId());
557 ps.setInt(2, getId());
558 ps.setString(3, token);
559 ps.setString(4, PasswordHash.hash(privateToken));
561 return ps.lastInsertId();
565 public static User getResetWithToken(int id, String token) {
566 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
568 ps.setString(2, token);
569 ps.setInt(3, PasswordResetPage.HOUR_MAX);
570 GigiResultSet res = ps.executeQuery();
574 return User.getById(res.getInt(1));
578 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
579 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
581 ps.setInt(2, getId());
582 GigiResultSet rs = ps.executeQuery();
584 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
586 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
587 throw new GigiApiException("Private token does not match.");
589 setPassword(newPassword);
591 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
597 private Assurance assuranceByRes(GigiResultSet res) {
598 return new Assurance(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"));
601 public boolean isInVerificationLimit() {
602 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' * ?)) AND (`expire` IS NULL OR `expire` > now()) AND `notary`.`deleted` IS NULL;")) {
603 ps.setInt(1, getId());
604 ps.setInt(2, VERIFICATION_MONTHS);
606 GigiResultSet rs = ps.executeQuery();
611 private void writeObject(ObjectOutputStream oos) throws IOException {}
613 private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {}