1 package org.cacert.gigi.dbObjects;
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.HashSet;
6 import java.util.LinkedList;
8 import java.util.Locale;
11 import org.cacert.gigi.GigiApiException;
12 import org.cacert.gigi.database.GigiPreparedStatement;
13 import org.cacert.gigi.database.GigiResultSet;
14 import org.cacert.gigi.dbObjects.Assurance.AssuranceType;
15 import org.cacert.gigi.dbObjects.CATS.CATSType;
16 import org.cacert.gigi.localisation.Language;
17 import org.cacert.gigi.output.DateSelector;
18 import org.cacert.gigi.pages.PasswordResetPage;
19 import org.cacert.gigi.util.CalendarUtil;
20 import org.cacert.gigi.util.DayDate;
21 import org.cacert.gigi.util.Notary;
22 import org.cacert.gigi.util.PasswordHash;
23 import org.cacert.gigi.util.PasswordStrengthChecker;
24 import org.cacert.gigi.util.TimeConditions;
27 * Represents an acting, assurable, user. Synchronizing on user means: no
28 * name-change and no assurance.
30 public class User extends CertificateOwner {
36 private Assurance[] receivedAssurances;
38 private Assurance[] madeAssurances;
40 private Locale locale;
42 private final Set<Group> groups = new HashSet<>();
44 public static final int MINIMUM_AGE = 16;
46 public static final int MAXIMUM_PLAUSIBLE_AGE = 120;
48 public static final int POJAM_AGE = 14;
50 public static final int ADULT_AGE = 18;
52 public static final boolean POJAM_ENABLED = false;
54 public static final int EXPERIENCE_POINTS = 4;
57 * Time in months a verification is considered "recent".
59 public static final int VERIFICATION_MONTHS = TimeConditions.getInstance().getVerificationMonths();
61 private Name preferredName;
63 protected User(GigiResultSet rs) {
64 super(rs.getInt("id"));
68 private void updateName(GigiResultSet rs) {
69 dob = new DayDate(rs.getDate("dob"));
70 email = rs.getString("email");
71 preferredName = Name.getById(rs.getInt("preferredName"));
73 String localeStr = rs.getString("language");
74 if (localeStr == null || localeStr.equals("")) {
75 locale = Locale.getDefault();
77 locale = Language.getLocaleFromString(localeStr);
80 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
81 psg.setInt(1, rs.getInt("id"));
83 try (GigiResultSet rs2 = psg.executeQuery()) {
85 groups.add(Group.getByString(rs2.getString(1)));
91 public User(String email, String password, DayDate dob, Locale locale, NamePart... preferred) throws GigiApiException {
95 this.preferredName = new Name(this, preferred);
96 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?")) {
97 query.setString(1, email);
98 query.setString(2, PasswordHash.hash(password));
99 query.setDate(3, dob.toSQLDate());
100 query.setString(4, locale.toString());
101 query.setInt(5, getId());
102 query.setInt(6, preferredName.getId());
105 new EmailAddress(this, email, locale);
108 public Name[] getNames() {
109 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
110 return fetchNamesToArray(gps);
114 public Name[] getNonDeprecatedNames() {
115 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL AND `deprecated` IS NULL", true)) {
116 return fetchNamesToArray(gps);
120 private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
121 gps.setInt(1, getId());
122 GigiResultSet rs = gps.executeQuery();
124 Name[] dt = new Name[rs.getRow()];
126 for (int i = 0; rs.next(); i++) {
127 dt[i] = Name.getById(rs.getInt(1));
132 public DayDate getDoB() {
136 public void setDoB(DayDate dob) throws GigiApiException {
137 synchronized (Notary.class) {
138 if (getReceivedAssurances().length != 0) {
139 throw new GigiApiException("No change after assurance allowed.");
142 if ( !CalendarUtil.isOfAge(dob, User.MINIMUM_AGE)) {
143 throw new GigiApiException("Entered date of birth is below the restricted age requirements.");
146 if (CalendarUtil.isOfAge(dob, User.MAXIMUM_PLAUSIBLE_AGE)) {
147 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.");
155 protected void setDoBAsSupport(DayDate dob) throws GigiApiException {
156 synchronized (Notary.class) {
163 public String getEmail() {
167 public void changePassword(String oldPass, String newPass) throws GigiApiException {
168 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
169 ps.setInt(1, getId());
170 try (GigiResultSet rs = ps.executeQuery()) {
172 throw new GigiApiException("User not found... very bad.");
174 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
175 throw new GigiApiException("Old password does not match.");
179 setPassword(newPass);
182 private void setPassword(String newPass) throws GigiApiException {
183 PasswordStrengthChecker.assertStrongPassword(newPass, getNames(), getEmail());
184 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
185 ps.setString(1, PasswordHash.hash(newPass));
186 ps.setInt(2, getId());
191 public boolean canAssure() {
193 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
197 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
201 if (getAssurancePoints() < 100) {
205 return hasPassedCATS();
209 public boolean hasPassedCATS() {
210 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
211 query.setInt(1, getId());
212 query.setInt(2, CATSType.ASSURER_CHALLENGE.getId());
213 try (GigiResultSet rs = query.executeQuery()) {
223 public int getAssurancePoints() {
224 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")) {
225 query.setInt(1, getId());
227 GigiResultSet rs = query.executeQuery();
231 points = rs.getInt(1);
238 public int getExperiencePoints() {
239 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")) {
240 query.setInt(1, getId());
241 query.setString(2, AssuranceType.FACE_TO_FACE.getDescription());
243 GigiResultSet rs = query.executeQuery();
247 points = rs.getInt(1) * EXPERIENCE_POINTS;
255 * Gets the maximum allowed points NOW. Note that an assurance needs to
256 * re-check PoJam as it has taken place in the past.
258 * @return the maximal points @
260 public int getMaxAssurePoints() {
261 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
265 int exp = getExperiencePoints();
268 if (exp >= 5 * EXPERIENCE_POINTS) {
271 if (exp >= 10 * EXPERIENCE_POINTS) {
274 if (exp >= 15 * EXPERIENCE_POINTS) {
277 if (exp >= 20 * EXPERIENCE_POINTS) {
280 if (exp >= 25 * EXPERIENCE_POINTS) {
287 public boolean isValidName(String name) {
288 for (Name n : getNames()) {
289 if (n.matches(name) && n.getAssurancePoints() >= 50) {
296 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
297 for (EmailAddress email : getEmails()) {
298 if (email.getAddress().equals(newMail.getAddress())) {
299 if ( !email.isVerified()) {
300 throw new GigiApiException("Email not verified.");
303 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
304 ps.setString(1, newMail.getAddress());
305 ps.setInt(2, getId());
309 this.email = newMail.getAddress();
314 throw new GigiApiException("Given address not an address of the user.");
317 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
318 if (getEmail().equals(delMail.getAddress())) {
319 throw new GigiApiException("Can't delete user's default e-mail.");
322 for (EmailAddress email : getEmails()) {
323 if (email.getId() == delMail.getId()) {
324 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
325 ps.setInt(1, delMail.getId());
331 throw new GigiApiException("Email not one of user's email addresses.");
334 public synchronized Assurance[] getReceivedAssurances() {
335 if (receivedAssurances == null) {
336 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")) {
337 query.setInt(1, getId());
339 GigiResultSet res = query.executeQuery();
340 List<Assurance> assurances = new LinkedList<Assurance>();
343 assurances.add(assuranceByRes(res));
346 this.receivedAssurances = assurances.toArray(new Assurance[0]);
350 return receivedAssurances;
353 public synchronized Assurance[] getMadeAssurances() {
354 if (madeAssurances == null) {
355 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
356 query.setInt(1, getId());
358 try (GigiResultSet res = query.executeQuery()) {
359 List<Assurance> assurances = new LinkedList<Assurance>();
362 assurances.add(assuranceByRes(res));
365 this.madeAssurances = assurances.toArray(new Assurance[0]);
370 return madeAssurances;
373 public synchronized void invalidateMadeAssurances() {
374 madeAssurances = null;
377 public synchronized void invalidateReceivedAssurances() {
378 receivedAssurances = null;
381 private void rawUpdateUserData() {
382 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
383 update.setDate(1, getDoB().toSQLDate());
384 update.setInt(2, getId());
385 update.executeUpdate();
389 public Locale getPreferredLocale() {
393 public void setPreferredLocale(Locale locale) {
394 this.locale = locale;
398 public Name getPreferredName() {
399 return preferredName;
402 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
403 if (preferred.getOwner() != this) {
404 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
406 this.preferredName = preferred;
407 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
408 ps.setInt(1, preferred.getId());
409 ps.setInt(2, getId());
415 public boolean isInGroup(Group g) {
416 return groups.contains(g);
419 public Set<Group> getGroups() {
420 return Collections.unmodifiableSet(groups);
423 public void grantGroup(User granter, Group toGrant) {
425 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
426 ps.setInt(1, getId());
427 ps.setString(2, toGrant.getDatabaseName());
428 ps.setInt(3, granter.getId());
433 public void revokeGroup(User revoker, Group toRevoke) {
434 groups.remove(toRevoke);
435 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
436 ps.setInt(1, revoker.getId());
437 ps.setString(2, toRevoke.getDatabaseName());
438 ps.setInt(3, getId());
443 public List<Organisation> getOrganisations() {
444 return getOrganisations(false);
447 public List<Organisation> getOrganisations(boolean isAdmin) {
448 List<Organisation> orgas = new ArrayList<>();
449 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
450 query.setInt(1, getId());
451 try (GigiResultSet res = query.executeQuery()) {
453 orgas.add(Organisation.getById(res.getInt(1)));
461 public static synchronized User getById(int id) {
462 CertificateOwner co = CertificateOwner.getById(id);
463 if (co instanceof User) {
470 public static User getByEmail(String mail) {
471 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
472 ps.setString(1, mail);
473 GigiResultSet rs = ps.executeQuery();
478 return User.getById(rs.getInt(1));
482 public static User[] findByEmail(String mail) {
483 LinkedList<User> results = new LinkedList<User>();
484 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")) {
485 ps.setString(1, mail);
486 GigiResultSet rs = ps.executeQuery();
488 results.add(User.getById(rs.getInt(1)));
490 return results.toArray(new User[results.size()]);
494 public EmailAddress[] getEmails() {
495 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
496 ps.setInt(1, getId());
498 GigiResultSet rs = ps.executeQuery();
499 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
502 data.add(EmailAddress.getById(rs.getInt(1)));
505 return data.toArray(new EmailAddress[0]);
510 public boolean isValidEmail(String email) {
511 for (EmailAddress em : getEmails()) {
512 if (em.getAddress().equals(email)) {
513 return em.isVerified();
520 public String[] getTrainings() {
521 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")) {
522 prep.setInt(1, getId());
523 GigiResultSet res = prep.executeQuery();
524 List<String> entries = new LinkedList<String>();
527 StringBuilder training = new StringBuilder();
528 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
529 training.append(" (");
530 training.append(res.getString(2));
531 if (res.getString(3).length() > 0) {
532 training.append(" ");
533 training.append(res.getString(3));
535 if (res.getString(4).length() > 0) {
536 training.append(", ");
537 training.append(res.getString(4));
539 training.append(")");
540 entries.add(training.toString());
543 return entries.toArray(new String[0]);
548 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
549 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
550 ps.setInt(1, getId());
551 ps.setInt(2, getId());
552 ps.setString(3, token);
553 ps.setString(4, PasswordHash.hash(privateToken));
555 return ps.lastInsertId();
559 public static User getResetWithToken(int id, String token) {
560 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
562 ps.setString(2, token);
563 ps.setInt(3, PasswordResetPage.HOUR_MAX);
564 GigiResultSet res = ps.executeQuery();
568 return User.getById(res.getInt(1));
572 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
573 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
575 ps.setInt(2, getId());
576 GigiResultSet rs = ps.executeQuery();
578 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
580 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
581 throw new GigiApiException("Private token does not match.");
583 setPassword(newPassword);
585 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
591 private Assurance assuranceByRes(GigiResultSet res) {
592 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"));
595 public boolean isInVerificationLimit() {
596 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;")) {
597 ps.setInt(1, getId());
598 ps.setInt(2, VERIFICATION_MONTHS);
600 GigiResultSet rs = ps.executeQuery();