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 verification 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 @SuppressWarnings("unused")
261 public int getMaxAssurePoints() {
262 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
266 int exp = getExperiencePoints();
269 if (exp >= 5 * EXPERIENCE_POINTS) {
272 if (exp >= 10 * EXPERIENCE_POINTS) {
275 if (exp >= 15 * EXPERIENCE_POINTS) {
278 if (exp >= 20 * EXPERIENCE_POINTS) {
281 if (exp >= 25 * EXPERIENCE_POINTS) {
288 public boolean isValidName(String name) {
289 for (Name n : getNames()) {
290 if (n.matches(name) && n.getAssurancePoints() >= 50) {
297 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
298 for (EmailAddress email : getEmails()) {
299 if (email.getAddress().equals(newMail.getAddress())) {
300 if ( !email.isVerified()) {
301 throw new GigiApiException("Email not verified.");
304 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
305 ps.setString(1, newMail.getAddress());
306 ps.setInt(2, getId());
310 this.email = newMail.getAddress();
315 throw new GigiApiException("Given address not an address of the user.");
318 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
319 if (getEmail().equals(delMail.getAddress())) {
320 throw new GigiApiException("Can't delete user's default e-mail.");
323 for (EmailAddress email : getEmails()) {
324 if (email.getId() == delMail.getId()) {
325 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
326 ps.setInt(1, delMail.getId());
332 throw new GigiApiException("Email not one of user's email addresses.");
335 public synchronized Assurance[] getReceivedAssurances() {
336 if (receivedAssurances == null) {
337 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")) {
338 query.setInt(1, getId());
340 GigiResultSet res = query.executeQuery();
341 List<Assurance> assurances = new LinkedList<Assurance>();
344 assurances.add(assuranceByRes(res));
347 this.receivedAssurances = assurances.toArray(new Assurance[0]);
351 return receivedAssurances;
354 public synchronized Assurance[] getMadeAssurances() {
355 if (madeAssurances == null) {
356 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL ORDER BY `when` DESC")) {
357 query.setInt(1, getId());
359 try (GigiResultSet res = query.executeQuery()) {
360 List<Assurance> assurances = new LinkedList<Assurance>();
363 assurances.add(assuranceByRes(res));
366 this.madeAssurances = assurances.toArray(new Assurance[0]);
371 return madeAssurances;
374 public synchronized void invalidateMadeAssurances() {
375 madeAssurances = null;
378 public synchronized void invalidateReceivedAssurances() {
379 receivedAssurances = null;
382 private void rawUpdateUserData() {
383 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
384 update.setDate(1, getDoB().toSQLDate());
385 update.setInt(2, getId());
386 update.executeUpdate();
390 public Locale getPreferredLocale() {
394 public void setPreferredLocale(Locale locale) {
395 this.locale = locale;
399 public synchronized Name getPreferredName() {
400 return preferredName;
403 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
404 if (preferred.getOwner() != this) {
405 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
407 this.preferredName = preferred;
408 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
409 ps.setInt(1, preferred.getId());
410 ps.setInt(2, getId());
416 public boolean isInGroup(Group g) {
417 return groups.contains(g);
420 public Set<Group> getGroups() {
421 return Collections.unmodifiableSet(groups);
424 public void grantGroup(User granter, Group toGrant) {
426 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
427 ps.setInt(1, getId());
428 ps.setString(2, toGrant.getDatabaseName());
429 ps.setInt(3, granter.getId());
434 public void revokeGroup(User revoker, Group toRevoke) {
435 groups.remove(toRevoke);
436 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
437 ps.setInt(1, revoker.getId());
438 ps.setString(2, toRevoke.getDatabaseName());
439 ps.setInt(3, getId());
444 public List<Organisation> getOrganisations() {
445 return getOrganisations(false);
448 public List<Organisation> getOrganisations(boolean isAdmin) {
449 List<Organisation> orgas = new ArrayList<>();
450 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
451 query.setInt(1, getId());
452 try (GigiResultSet res = query.executeQuery()) {
454 orgas.add(Organisation.getById(res.getInt(1)));
462 public static synchronized User getById(int id) {
463 CertificateOwner co = CertificateOwner.getById(id);
464 if (co instanceof User) {
471 public static User getByEmail(String mail) {
472 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
473 ps.setString(1, mail);
474 GigiResultSet rs = ps.executeQuery();
479 return User.getById(rs.getInt(1));
483 public static User[] findByEmail(String mail) {
484 LinkedList<User> results = new LinkedList<User>();
485 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")) {
486 ps.setString(1, mail);
487 GigiResultSet rs = ps.executeQuery();
489 results.add(User.getById(rs.getInt(1)));
491 return results.toArray(new User[results.size()]);
495 public EmailAddress[] getEmails() {
496 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
497 ps.setInt(1, getId());
499 GigiResultSet rs = ps.executeQuery();
500 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
503 data.add(EmailAddress.getById(rs.getInt(1)));
506 return data.toArray(new EmailAddress[0]);
511 public boolean isValidEmail(String email) {
512 for (EmailAddress em : getEmails()) {
513 if (em.getAddress().equals(email)) {
514 return em.isVerified();
521 public String[] getTrainings() {
522 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")) {
523 prep.setInt(1, getId());
524 GigiResultSet res = prep.executeQuery();
525 List<String> entries = new LinkedList<String>();
528 StringBuilder training = new StringBuilder();
529 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
530 training.append(" (");
531 training.append(res.getString(2));
532 if (res.getString(3).length() > 0) {
533 training.append(" ");
534 training.append(res.getString(3));
536 if (res.getString(4).length() > 0) {
537 training.append(", ");
538 training.append(res.getString(4));
540 training.append(")");
541 entries.add(training.toString());
544 return entries.toArray(new String[0]);
549 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
550 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
551 ps.setInt(1, getId());
552 ps.setInt(2, getId());
553 ps.setString(3, token);
554 ps.setString(4, PasswordHash.hash(privateToken));
556 return ps.lastInsertId();
560 public static User getResetWithToken(int id, String token) {
561 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
563 ps.setString(2, token);
564 ps.setInt(3, PasswordResetPage.HOUR_MAX);
565 GigiResultSet res = ps.executeQuery();
569 return User.getById(res.getInt(1));
573 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
574 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
576 ps.setInt(2, getId());
577 GigiResultSet rs = ps.executeQuery();
579 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
581 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
582 throw new GigiApiException("Private token does not match.");
584 setPassword(newPassword);
586 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
592 private Assurance assuranceByRes(GigiResultSet res) {
593 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"));
596 public boolean isInVerificationLimit() {
597 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;")) {
598 ps.setInt(1, getId());
599 ps.setInt(2, VERIFICATION_MONTHS);
601 GigiResultSet rs = ps.executeQuery();