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;
26 * Represents an acting, assurable, user. Synchronizing on user means: no
27 * name-change and no assurance.
29 public class User extends CertificateOwner {
35 private Assurance[] receivedAssurances;
37 private Assurance[] madeAssurances;
39 private Locale locale;
41 private final Set<Group> groups = new HashSet<>();
43 public static final int MINIMUM_AGE = 16;
45 public static final int POJAM_AGE = 14;
47 public static final int ADULT_AGE = 18;
49 public static final boolean POJAM_ENABLED = false;
51 public static final int EXPERIENCE_POINTS = 2;
54 * Time in months a verification is considered "recent".
56 public static final int VERIFICATION_MONTHS = 39;
58 private Name preferredName;
60 protected User(GigiResultSet rs) {
61 super(rs.getInt("id"));
65 private void updateName(GigiResultSet rs) {
66 dob = new DayDate(rs.getDate("dob"));
67 email = rs.getString("email");
68 preferredName = Name.getById(rs.getInt("preferredName"));
70 String localeStr = rs.getString("language");
71 if (localeStr == null || localeStr.equals("")) {
72 locale = Locale.getDefault();
74 locale = Language.getLocaleFromString(localeStr);
77 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
78 psg.setInt(1, rs.getInt("id"));
80 try (GigiResultSet rs2 = psg.executeQuery()) {
82 groups.add(Group.getByString(rs2.getString(1)));
88 public User(String email, String password, DayDate dob, Locale locale, NamePart... preferred) throws GigiApiException {
92 this.preferredName = new Name(this, preferred);
93 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?")) {
94 query.setString(1, email);
95 query.setString(2, PasswordHash.hash(password));
96 query.setDate(3, dob.toSQLDate());
97 query.setString(4, locale.toString());
98 query.setInt(5, getId());
99 query.setInt(6, preferredName.getId());
102 new EmailAddress(this, email, locale);
105 public Name[] getNames() {
106 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
107 return fetchNamesToArray(gps);
111 public Name[] getNonDeprecatedNames() {
112 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL AND `deprecated` IS NULL", true)) {
113 return fetchNamesToArray(gps);
117 private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
118 gps.setInt(1, getId());
119 GigiResultSet rs = gps.executeQuery();
121 Name[] dt = new Name[rs.getRow()];
123 for (int i = 0; rs.next(); i++) {
124 dt[i] = Name.getById(rs.getInt(1));
129 public DayDate getDoB() {
133 public void setDoB(DayDate dob) throws GigiApiException {
134 synchronized (Notary.class) {
135 if (getReceivedAssurances().length != 0) {
136 throw new GigiApiException("No change after assurance allowed.");
144 protected void setDoBAsSupport(DayDate dob) throws GigiApiException {
145 synchronized (Notary.class) {
152 public String getEmail() {
156 public void changePassword(String oldPass, String newPass) throws GigiApiException {
157 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
158 ps.setInt(1, getId());
159 try (GigiResultSet rs = ps.executeQuery()) {
161 throw new GigiApiException("User not found... very bad.");
163 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
164 throw new GigiApiException("Old password does not match.");
168 setPassword(newPass);
171 private void setPassword(String newPass) throws GigiApiException {
172 PasswordStrengthChecker.assertStrongPassword(newPass, getNames(), getEmail());
173 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
174 ps.setString(1, PasswordHash.hash(newPass));
175 ps.setInt(2, getId());
180 public boolean canAssure() {
182 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
186 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
190 if (getAssurancePoints() < 100) {
194 return hasPassedCATS();
198 public boolean hasPassedCATS() {
199 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
200 query.setInt(1, getId());
201 query.setInt(2, CATSType.ASSURER_CHALLENGE.getId());
202 try (GigiResultSet rs = query.executeQuery()) {
212 public int getAssurancePoints() {
213 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")) {
214 query.setInt(1, getId());
216 GigiResultSet rs = query.executeQuery();
220 points = rs.getInt(1);
227 public int getExperiencePoints() {
228 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")) {
229 query.setInt(1, getId());
230 query.setString(2, AssuranceType.FACE_TO_FACE.getDescription());
232 GigiResultSet rs = query.executeQuery();
236 points = rs.getInt(1) * EXPERIENCE_POINTS;
244 * Gets the maximum allowed points NOW. Note that an assurance needs to
245 * re-check PoJam as it has taken place in the past.
247 * @return the maximal points @
249 public int getMaxAssurePoints() {
250 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
254 int exp = getExperiencePoints();
257 if (exp >= 5 * EXPERIENCE_POINTS) {
260 if (exp >= 10 * EXPERIENCE_POINTS) {
263 if (exp >= 15 * EXPERIENCE_POINTS) {
266 if (exp >= 20 * EXPERIENCE_POINTS) {
269 if (exp >= 25 * EXPERIENCE_POINTS) {
276 public boolean isValidName(String name) {
277 for (Name n : getNames()) {
278 if (n.matches(name) && n.getAssurancePoints() >= 50) {
285 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
286 for (EmailAddress email : getEmails()) {
287 if (email.getAddress().equals(newMail.getAddress())) {
288 if ( !email.isVerified()) {
289 throw new GigiApiException("Email not verified.");
292 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
293 ps.setString(1, newMail.getAddress());
294 ps.setInt(2, getId());
298 this.email = newMail.getAddress();
303 throw new GigiApiException("Given address not an address of the user.");
306 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
307 if (getEmail().equals(delMail.getAddress())) {
308 throw new GigiApiException("Can't delete user's default e-mail.");
311 for (EmailAddress email : getEmails()) {
312 if (email.getId() == delMail.getId()) {
313 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
314 ps.setInt(1, delMail.getId());
320 throw new GigiApiException("Email not one of user's email addresses.");
323 public synchronized Assurance[] getReceivedAssurances() {
324 if (receivedAssurances == null) {
325 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` INNER JOIN `names` ON `names`.`id` = `notary`.`to` WHERE `names`.`uid`=? AND `notary`.`deleted` IS NULL")) {
326 query.setInt(1, getId());
328 GigiResultSet res = query.executeQuery();
329 List<Assurance> assurances = new LinkedList<Assurance>();
332 assurances.add(assuranceByRes(res));
335 this.receivedAssurances = assurances.toArray(new Assurance[0]);
339 return receivedAssurances;
342 public synchronized Assurance[] getMadeAssurances() {
343 if (madeAssurances == null) {
344 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL")) {
345 query.setInt(1, getId());
347 try (GigiResultSet res = query.executeQuery()) {
348 List<Assurance> assurances = new LinkedList<Assurance>();
351 assurances.add(assuranceByRes(res));
354 this.madeAssurances = assurances.toArray(new Assurance[0]);
359 return madeAssurances;
362 public synchronized void invalidateMadeAssurances() {
363 madeAssurances = null;
366 public synchronized void invalidateReceivedAssurances() {
367 receivedAssurances = null;
370 private void rawUpdateUserData() {
371 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
372 update.setDate(1, getDoB().toSQLDate());
373 update.setInt(2, getId());
374 update.executeUpdate();
378 public Locale getPreferredLocale() {
382 public void setPreferredLocale(Locale locale) {
383 this.locale = locale;
387 public Name getPreferredName() {
388 return preferredName;
391 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
392 if (preferred.getOwner() != this) {
393 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
395 this.preferredName = preferred;
396 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
397 ps.setInt(1, preferred.getId());
398 ps.setInt(2, getId());
404 public boolean isInGroup(Group g) {
405 return groups.contains(g);
408 public Set<Group> getGroups() {
409 return Collections.unmodifiableSet(groups);
412 public void grantGroup(User granter, Group toGrant) {
414 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
415 ps.setInt(1, getId());
416 ps.setString(2, toGrant.getDatabaseName());
417 ps.setInt(3, granter.getId());
422 public void revokeGroup(User revoker, Group toRevoke) {
423 groups.remove(toRevoke);
424 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
425 ps.setInt(1, revoker.getId());
426 ps.setString(2, toRevoke.getDatabaseName());
427 ps.setInt(3, getId());
432 public List<Organisation> getOrganisations() {
433 return getOrganisations(false);
436 public List<Organisation> getOrganisations(boolean isAdmin) {
437 List<Organisation> orgas = new ArrayList<>();
438 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
439 query.setInt(1, getId());
440 try (GigiResultSet res = query.executeQuery()) {
442 orgas.add(Organisation.getById(res.getInt(1)));
450 public static synchronized User getById(int id) {
451 CertificateOwner co = CertificateOwner.getById(id);
452 if (co instanceof User) {
459 public static User getByEmail(String mail) {
460 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
461 ps.setString(1, mail);
462 GigiResultSet rs = ps.executeQuery();
467 return User.getById(rs.getInt(1));
471 public static User[] findByEmail(String mail) {
472 LinkedList<User> results = new LinkedList<User>();
473 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")) {
474 ps.setString(1, mail);
475 GigiResultSet rs = ps.executeQuery();
477 results.add(User.getById(rs.getInt(1)));
479 return results.toArray(new User[results.size()]);
483 public EmailAddress[] getEmails() {
484 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
485 ps.setInt(1, getId());
487 GigiResultSet rs = ps.executeQuery();
488 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
491 data.add(EmailAddress.getById(rs.getInt(1)));
494 return data.toArray(new EmailAddress[0]);
499 public boolean isValidEmail(String email) {
500 for (EmailAddress em : getEmails()) {
501 if (em.getAddress().equals(email)) {
502 return em.isVerified();
509 public String[] getTrainings() {
510 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")) {
511 prep.setInt(1, getId());
512 GigiResultSet res = prep.executeQuery();
513 List<String> entries = new LinkedList<String>();
516 StringBuilder training = new StringBuilder();
517 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
518 training.append(" (");
519 training.append(res.getString(2));
520 if (res.getString(3).length() > 0) {
521 training.append(" ");
522 training.append(res.getString(3));
524 if (res.getString(4).length() > 0) {
525 training.append(", ");
526 training.append(res.getString(4));
528 training.append(")");
529 entries.add(training.toString());
532 return entries.toArray(new String[0]);
537 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
538 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
539 ps.setInt(1, getId());
540 ps.setInt(2, getId());
541 ps.setString(3, token);
542 ps.setString(4, PasswordHash.hash(privateToken));
544 return ps.lastInsertId();
548 public static User getResetWithToken(int id, String token) {
549 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
551 ps.setString(2, token);
552 ps.setInt(3, PasswordResetPage.HOUR_MAX);
553 GigiResultSet res = ps.executeQuery();
557 return User.getById(res.getInt(1));
561 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
562 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
564 ps.setInt(2, getId());
565 GigiResultSet rs = ps.executeQuery();
567 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
569 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
570 throw new GigiApiException("Private token does not match.");
572 setPassword(newPassword);
574 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
580 private Assurance assuranceByRes(GigiResultSet res) {
581 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"));
584 public boolean isInVerificationLimit() {
585 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;")) {
586 ps.setInt(1, getId());
587 ps.setInt(2, VERIFICATION_MONTHS);
589 GigiResultSet rs = ps.executeQuery();