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.dbObjects.CountryCode.CountryCodeType;
20 import org.cacert.gigi.localisation.Language;
21 import org.cacert.gigi.output.DateSelector;
22 import org.cacert.gigi.pages.PasswordResetPage;
23 import org.cacert.gigi.util.CalendarUtil;
24 import org.cacert.gigi.util.DayDate;
25 import org.cacert.gigi.util.Notary;
26 import org.cacert.gigi.util.PasswordHash;
27 import org.cacert.gigi.util.PasswordStrengthChecker;
28 import org.cacert.gigi.util.TimeConditions;
31 * Represents an acting, assurable, user. Synchronizing on user means: no
32 * name-change and no assurance.
34 public class User extends CertificateOwner {
36 private static final long serialVersionUID = -7915843843752264176L;
42 private Assurance[] receivedAssurances;
44 private Assurance[] madeAssurances;
46 private Locale locale;
48 private final Set<Group> groups = new HashSet<>();
50 public static final int MINIMUM_AGE = 16;
52 public static final int MAXIMUM_PLAUSIBLE_AGE = 120;
54 public static final int POJAM_AGE = 14;
56 public static final int ADULT_AGE = 18;
58 public static final boolean POJAM_ENABLED = false;
60 public static final int EXPERIENCE_POINTS = 4;
63 * Time in months a verification is considered "recent".
65 public static final int VERIFICATION_MONTHS = TimeConditions.getInstance().getVerificationMonths();
67 private Name preferredName;
69 protected User(GigiResultSet rs) {
70 super(rs.getInt("id"));
74 private void updateName(GigiResultSet rs) {
75 dob = new DayDate(rs.getDate("dob"));
76 email = rs.getString("email");
77 preferredName = Name.getById(rs.getInt("preferredName"));
79 String localeStr = rs.getString("language");
80 if (localeStr == null || localeStr.equals("")) {
81 locale = Locale.getDefault();
83 locale = Language.getLocaleFromString(localeStr);
86 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
87 psg.setInt(1, rs.getInt("id"));
89 try (GigiResultSet rs2 = psg.executeQuery()) {
91 groups.add(Group.getByString(rs2.getString(1)));
97 public User(String email, String password, DayDate dob, Locale locale, NamePart... preferred) throws GigiApiException {
100 this.locale = locale;
101 this.preferredName = new Name(this, preferred);
102 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?")) {
103 query.setString(1, email);
104 query.setString(2, PasswordHash.hash(password));
105 query.setDate(3, dob.toSQLDate());
106 query.setString(4, locale.toString());
107 query.setInt(5, getId());
108 query.setInt(6, preferredName.getId());
111 new EmailAddress(this, email, locale);
114 public Name[] getNames() {
115 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
116 return fetchNamesToArray(gps);
120 public Name[] getNonDeprecatedNames() {
121 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL AND `deprecated` IS NULL", true)) {
122 return fetchNamesToArray(gps);
126 private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
127 gps.setInt(1, getId());
128 GigiResultSet rs = gps.executeQuery();
130 Name[] dt = new Name[rs.getRow()];
132 for (int i = 0; rs.next(); i++) {
133 dt[i] = Name.getById(rs.getInt(1));
138 public DayDate getDoB() {
142 public void setDoB(DayDate dob) throws GigiApiException {
143 synchronized (Notary.class) {
144 if (getReceivedAssurances().length != 0) {
145 throw new GigiApiException("No change after verification allowed.");
148 if ( !CalendarUtil.isOfAge(dob, User.MINIMUM_AGE)) {
149 throw new GigiApiException("Entered date of birth is below the restricted age requirements.");
152 if (CalendarUtil.isOfAge(dob, User.MAXIMUM_PLAUSIBLE_AGE)) {
153 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.");
161 protected void setDoBAsSupport(DayDate dob) throws GigiApiException {
162 synchronized (Notary.class) {
169 public String getEmail() {
173 public void changePassword(String oldPass, String newPass) throws GigiApiException {
174 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
175 ps.setInt(1, getId());
176 try (GigiResultSet rs = ps.executeQuery()) {
178 throw new GigiApiException("User not found... very bad.");
180 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
181 throw new GigiApiException("Old password does not match.");
185 setPassword(newPass);
188 private void setPassword(String newPass) throws GigiApiException {
189 PasswordStrengthChecker.assertStrongPassword(newPass, getNames(), getEmail());
190 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
191 ps.setString(1, PasswordHash.hash(newPass));
192 ps.setInt(2, getId());
197 public boolean canAssure() {
199 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
203 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
207 if (getAssurancePoints() < 100) {
211 return hasPassedCATS();
215 public boolean hasPassedCATS() {
216 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
217 query.setInt(1, getId());
218 query.setInt(2, CATSType.ASSURER_CHALLENGE.getId());
219 try (GigiResultSet rs = query.executeQuery()) {
229 public int getAssurancePoints() {
230 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")) {
231 query.setInt(1, getId());
233 GigiResultSet rs = query.executeQuery();
237 points = rs.getInt(1);
244 public int getExperiencePoints() {
245 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")) {
246 query.setInt(1, getId());
247 query.setString(2, AssuranceType.FACE_TO_FACE.getDescription());
249 GigiResultSet rs = query.executeQuery();
253 points = rs.getInt(1) * EXPERIENCE_POINTS;
261 * Gets the maximum allowed points NOW. Note that an assurance needs to
262 * re-check PoJam as it has taken place in the past.
264 * @return the maximal points @
266 @SuppressWarnings("unused")
267 public int getMaxAssurePoints() {
268 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
272 int exp = getExperiencePoints();
275 if (exp >= 5 * EXPERIENCE_POINTS) {
278 if (exp >= 10 * EXPERIENCE_POINTS) {
281 if (exp >= 15 * EXPERIENCE_POINTS) {
284 if (exp >= 20 * EXPERIENCE_POINTS) {
287 if (exp >= 25 * EXPERIENCE_POINTS) {
294 public boolean isValidName(String name) {
295 for (Name n : getNames()) {
296 if (n.matches(name) && n.getAssurancePoints() >= 50) {
303 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
304 for (EmailAddress email : getEmails()) {
305 if (email.getAddress().equals(newMail.getAddress())) {
306 if ( !email.isVerified()) {
307 throw new GigiApiException("Email not verified.");
310 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
311 ps.setString(1, newMail.getAddress());
312 ps.setInt(2, getId());
316 this.email = newMail.getAddress();
321 throw new GigiApiException("Given address not an address of the user.");
324 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
325 if (getEmail().equals(delMail.getAddress())) {
326 throw new GigiApiException("Can't delete user's default e-mail.");
329 for (EmailAddress email : getEmails()) {
330 if (email.getId() == delMail.getId()) {
331 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
332 ps.setInt(1, delMail.getId());
338 throw new GigiApiException("Email not one of user's email addresses.");
341 public synchronized Assurance[] getReceivedAssurances() {
342 if (receivedAssurances == null) {
343 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")) {
344 query.setInt(1, getId());
346 GigiResultSet res = query.executeQuery();
347 List<Assurance> assurances = new LinkedList<Assurance>();
350 assurances.add(assuranceByRes(res));
353 this.receivedAssurances = assurances.toArray(new Assurance[0]);
357 return receivedAssurances;
360 public synchronized Assurance[] getMadeAssurances() {
361 if (madeAssurances == null) {
362 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
363 query.setInt(1, getId());
365 try (GigiResultSet res = query.executeQuery()) {
366 List<Assurance> assurances = new LinkedList<Assurance>();
369 assurances.add(assuranceByRes(res));
372 this.madeAssurances = assurances.toArray(new Assurance[0]);
377 return madeAssurances;
380 public synchronized void invalidateMadeAssurances() {
381 madeAssurances = null;
384 public synchronized void invalidateReceivedAssurances() {
385 receivedAssurances = null;
388 private void rawUpdateUserData() {
389 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
390 update.setDate(1, getDoB().toSQLDate());
391 update.setInt(2, getId());
392 update.executeUpdate();
396 public Locale getPreferredLocale() {
400 public void setPreferredLocale(Locale locale) {
401 this.locale = locale;
405 public synchronized Name getPreferredName() {
406 return preferredName;
409 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
410 if (preferred.getOwner() != this) {
411 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
413 this.preferredName = preferred;
414 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
415 ps.setInt(1, preferred.getId());
416 ps.setInt(2, getId());
422 public boolean isInGroup(Group g) {
423 return groups.contains(g);
426 public Set<Group> getGroups() {
427 return Collections.unmodifiableSet(groups);
430 public void grantGroup(User granter, Group toGrant) {
432 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
433 ps.setInt(1, getId());
434 ps.setString(2, toGrant.getDatabaseName());
435 ps.setInt(3, granter.getId());
440 public void revokeGroup(User revoker, Group toRevoke) {
441 groups.remove(toRevoke);
442 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
443 ps.setInt(1, revoker.getId());
444 ps.setString(2, toRevoke.getDatabaseName());
445 ps.setInt(3, getId());
450 public List<Organisation> getOrganisations() {
451 return getOrganisations(false);
454 public List<Organisation> getOrganisations(boolean isAdmin) {
455 List<Organisation> orgas = new ArrayList<>();
456 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
457 query.setInt(1, getId());
458 try (GigiResultSet res = query.executeQuery()) {
460 orgas.add(Organisation.getById(res.getInt(1)));
468 public static synchronized User getById(int id) {
469 CertificateOwner co = CertificateOwner.getById(id);
470 if (co instanceof User) {
477 public static User getByEmail(String mail) {
478 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
479 ps.setString(1, mail);
480 GigiResultSet rs = ps.executeQuery();
485 return User.getById(rs.getInt(1));
489 public static User[] findByEmail(String mail) {
490 LinkedList<User> results = new LinkedList<User>();
491 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")) {
492 ps.setString(1, mail);
493 GigiResultSet rs = ps.executeQuery();
495 results.add(User.getById(rs.getInt(1)));
497 return results.toArray(new User[results.size()]);
501 public EmailAddress[] getEmails() {
502 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
503 ps.setInt(1, getId());
505 GigiResultSet rs = ps.executeQuery();
506 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
509 data.add(EmailAddress.getById(rs.getInt(1)));
512 return data.toArray(new EmailAddress[0]);
517 public boolean isValidEmail(String email) {
518 for (EmailAddress em : getEmails()) {
519 if (em.getAddress().equals(email)) {
520 return em.isVerified();
527 public String[] getTrainings() {
528 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")) {
529 prep.setInt(1, getId());
530 GigiResultSet res = prep.executeQuery();
531 List<String> entries = new LinkedList<String>();
534 StringBuilder training = new StringBuilder();
535 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
536 training.append(" (");
537 training.append(res.getString(2));
538 if (res.getString(3).length() > 0) {
539 training.append(" ");
540 training.append(res.getString(3));
542 if (res.getString(4).length() > 0) {
543 training.append(", ");
544 training.append(res.getString(4));
546 training.append(")");
547 entries.add(training.toString());
550 return entries.toArray(new String[0]);
555 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
556 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
557 ps.setInt(1, getId());
558 ps.setInt(2, getId());
559 ps.setString(3, token);
560 ps.setString(4, PasswordHash.hash(privateToken));
562 return ps.lastInsertId();
566 public static User getResetWithToken(int id, String token) {
567 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
569 ps.setString(2, token);
570 ps.setInt(3, PasswordResetPage.HOUR_MAX);
571 GigiResultSet res = ps.executeQuery();
575 return User.getById(res.getInt(1));
579 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
580 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
582 ps.setInt(2, getId());
583 GigiResultSet rs = ps.executeQuery();
585 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
587 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
588 throw new GigiApiException("Private token does not match.");
590 setPassword(newPassword);
592 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
598 private Assurance assuranceByRes(GigiResultSet res) {
600 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"), res.getString("country") == null ? null : CountryCode.getCountryCode(res.getString("country"), CountryCodeType.CODE_2_CHARS));
601 } catch (GigiApiException e) {
606 public boolean isInVerificationLimit() {
607 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;")) {
608 ps.setInt(1, getId());
609 ps.setInt(2, VERIFICATION_MONTHS);
611 GigiResultSet rs = ps.executeQuery();
616 private void writeObject(ObjectOutputStream oos) throws IOException {}
618 private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {}