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;
52 * Time in months a verification is considered "recent".
54 public static final int VERIFICATION_MONTHS = 39;
56 private Name preferredName;
58 protected User(GigiResultSet rs) {
59 super(rs.getInt("id"));
63 private void updateName(GigiResultSet rs) {
64 dob = new DayDate(rs.getDate("dob"));
65 email = rs.getString("email");
66 preferredName = Name.getById(rs.getInt("preferredName"));
68 String localeStr = rs.getString("language");
69 if (localeStr == null || localeStr.equals("")) {
70 locale = Locale.getDefault();
72 locale = Language.getLocaleFromString(localeStr);
75 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
76 psg.setInt(1, rs.getInt("id"));
78 try (GigiResultSet rs2 = psg.executeQuery()) {
80 groups.add(Group.getByString(rs2.getString(1)));
86 public User(String email, String password, DayDate dob, Locale locale, NamePart... preferred) throws GigiApiException {
90 this.preferredName = new Name(this, preferred);
91 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?")) {
92 query.setString(1, email);
93 query.setString(2, PasswordHash.hash(password));
94 query.setDate(3, dob.toSQLDate());
95 query.setString(4, locale.toString());
96 query.setInt(5, getId());
97 query.setInt(6, preferredName.getId());
100 new EmailAddress(this, email, locale);
103 public Name[] getNames() {
104 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
105 return fetchNamesToArray(gps);
109 public Name[] getNonDeprecatedNames() {
110 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL AND `deprecated` IS NULL", true)) {
111 return fetchNamesToArray(gps);
115 private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
116 gps.setInt(1, getId());
117 GigiResultSet rs = gps.executeQuery();
119 Name[] dt = new Name[rs.getRow()];
121 for (int i = 0; rs.next(); i++) {
122 dt[i] = Name.getById(rs.getInt(1));
127 public DayDate getDoB() {
131 public void setDoB(DayDate dob) throws GigiApiException {
132 synchronized (Notary.class) {
133 if (getReceivedAssurances().length != 0) {
134 throw new GigiApiException("No change after assurance allowed.");
142 protected void setDoBAsSupport(DayDate dob) throws GigiApiException {
143 synchronized (Notary.class) {
150 public String getEmail() {
154 public void changePassword(String oldPass, String newPass) throws GigiApiException {
155 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
156 ps.setInt(1, getId());
157 try (GigiResultSet rs = ps.executeQuery()) {
159 throw new GigiApiException("User not found... very bad.");
161 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
162 throw new GigiApiException("Old password does not match.");
166 setPassword(newPass);
169 private void setPassword(String newPass) throws GigiApiException {
170 PasswordStrengthChecker.assertStrongPassword(newPass, getNames(), getEmail());
171 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
172 ps.setString(1, PasswordHash.hash(newPass));
173 ps.setInt(2, getId());
178 public boolean canAssure() {
180 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
184 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
188 if (getAssurancePoints() < 100) {
192 return hasPassedCATS();
196 public boolean hasPassedCATS() {
197 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
198 query.setInt(1, getId());
199 query.setInt(2, CATSType.ASSURER_CHALLENGE.getId());
200 try (GigiResultSet rs = query.executeQuery()) {
210 public int getAssurancePoints() {
211 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")) {
212 query.setInt(1, getId());
214 GigiResultSet rs = query.executeQuery();
218 points = rs.getInt(1);
225 public int getExperiencePoints() {
226 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")) {
227 query.setInt(1, getId());
228 query.setString(2, AssuranceType.FACE_TO_FACE.getDescription());
230 GigiResultSet rs = query.executeQuery();
234 points = rs.getInt(1) * 2;
242 * Gets the maximum allowed points NOW. Note that an assurance needs to
243 * re-check PoJam as it has taken place in the past.
245 * @return the maximal points @
247 public int getMaxAssurePoints() {
248 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
252 int exp = getExperiencePoints();
274 public boolean isValidName(String name) {
275 for (Name n : getNames()) {
276 if (n.matches(name) && n.getAssurancePoints() >= 50) {
283 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
284 for (EmailAddress email : getEmails()) {
285 if (email.getAddress().equals(newMail.getAddress())) {
286 if ( !email.isVerified()) {
287 throw new GigiApiException("Email not verified.");
290 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
291 ps.setString(1, newMail.getAddress());
292 ps.setInt(2, getId());
296 this.email = newMail.getAddress();
301 throw new GigiApiException("Given address not an address of the user.");
304 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
305 if (getEmail().equals(delMail.getAddress())) {
306 throw new GigiApiException("Can't delete user's default e-mail.");
309 for (EmailAddress email : getEmails()) {
310 if (email.getId() == delMail.getId()) {
311 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
312 ps.setInt(1, delMail.getId());
318 throw new GigiApiException("Email not one of user's email addresses.");
321 public synchronized Assurance[] getReceivedAssurances() {
322 if (receivedAssurances == null) {
323 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` INNER JOIN `names` ON `names`.`id` = `notary`.`to` WHERE `names`.`uid`=? AND `notary`.`deleted` IS NULL")) {
324 query.setInt(1, getId());
326 GigiResultSet res = query.executeQuery();
327 List<Assurance> assurances = new LinkedList<Assurance>();
330 assurances.add(assuranceByRes(res));
333 this.receivedAssurances = assurances.toArray(new Assurance[0]);
337 return receivedAssurances;
340 public synchronized Assurance[] getMadeAssurances() {
341 if (madeAssurances == null) {
342 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL")) {
343 query.setInt(1, getId());
345 try (GigiResultSet res = query.executeQuery()) {
346 List<Assurance> assurances = new LinkedList<Assurance>();
349 assurances.add(assuranceByRes(res));
352 this.madeAssurances = assurances.toArray(new Assurance[0]);
357 return madeAssurances;
360 public synchronized void invalidateMadeAssurances() {
361 madeAssurances = null;
364 public synchronized void invalidateReceivedAssurances() {
365 receivedAssurances = null;
368 private void rawUpdateUserData() {
369 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
370 update.setDate(1, getDoB().toSQLDate());
371 update.setInt(2, getId());
372 update.executeUpdate();
376 public Locale getPreferredLocale() {
380 public void setPreferredLocale(Locale locale) {
381 this.locale = locale;
385 public Name getPreferredName() {
386 return preferredName;
389 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
390 if (preferred.getOwner() != this) {
391 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
393 this.preferredName = preferred;
394 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
395 ps.setInt(1, preferred.getId());
396 ps.setInt(2, getId());
402 public boolean isInGroup(Group g) {
403 return groups.contains(g);
406 public Set<Group> getGroups() {
407 return Collections.unmodifiableSet(groups);
410 public void grantGroup(User granter, Group toGrant) {
412 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
413 ps.setInt(1, getId());
414 ps.setString(2, toGrant.getDatabaseName());
415 ps.setInt(3, granter.getId());
420 public void revokeGroup(User revoker, Group toRevoke) {
421 groups.remove(toRevoke);
422 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
423 ps.setInt(1, revoker.getId());
424 ps.setString(2, toRevoke.getDatabaseName());
425 ps.setInt(3, getId());
430 public List<Organisation> getOrganisations() {
431 return getOrganisations(false);
434 public List<Organisation> getOrganisations(boolean isAdmin) {
435 List<Organisation> orgas = new ArrayList<>();
436 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
437 query.setInt(1, getId());
438 try (GigiResultSet res = query.executeQuery()) {
440 orgas.add(Organisation.getById(res.getInt(1)));
448 public static synchronized User getById(int id) {
449 CertificateOwner co = CertificateOwner.getById(id);
450 if (co instanceof User) {
457 public static User getByEmail(String mail) {
458 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
459 ps.setString(1, mail);
460 GigiResultSet rs = ps.executeQuery();
465 return User.getById(rs.getInt(1));
469 public static User[] findByEmail(String mail) {
470 LinkedList<User> results = new LinkedList<User>();
471 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")) {
472 ps.setString(1, mail);
473 GigiResultSet rs = ps.executeQuery();
475 results.add(User.getById(rs.getInt(1)));
477 return results.toArray(new User[results.size()]);
481 public EmailAddress[] getEmails() {
482 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
483 ps.setInt(1, getId());
485 GigiResultSet rs = ps.executeQuery();
486 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
489 data.add(EmailAddress.getById(rs.getInt(1)));
492 return data.toArray(new EmailAddress[0]);
497 public boolean isValidEmail(String email) {
498 for (EmailAddress em : getEmails()) {
499 if (em.getAddress().equals(email)) {
500 return em.isVerified();
507 public String[] getTrainings() {
508 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")) {
509 prep.setInt(1, getId());
510 GigiResultSet res = prep.executeQuery();
511 List<String> entries = new LinkedList<String>();
514 StringBuilder training = new StringBuilder();
515 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
516 training.append(" (");
517 training.append(res.getString(2));
518 if (res.getString(3).length() > 0) {
519 training.append(" ");
520 training.append(res.getString(3));
522 if (res.getString(4).length() > 0) {
523 training.append(", ");
524 training.append(res.getString(4));
526 training.append(")");
527 entries.add(training.toString());
530 return entries.toArray(new String[0]);
535 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
536 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
537 ps.setInt(1, getId());
538 ps.setInt(2, getId());
539 ps.setString(3, token);
540 ps.setString(4, PasswordHash.hash(privateToken));
542 return ps.lastInsertId();
546 public static User getResetWithToken(int id, String token) {
547 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
549 ps.setString(2, token);
550 ps.setInt(3, PasswordResetPage.HOUR_MAX);
551 GigiResultSet res = ps.executeQuery();
555 return User.getById(res.getInt(1));
559 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
560 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
562 ps.setInt(2, getId());
563 GigiResultSet rs = ps.executeQuery();
565 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
567 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
568 throw new GigiApiException("Private token does not match.");
570 setPassword(newPassword);
572 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
578 private Assurance assuranceByRes(GigiResultSet res) {
579 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"));
582 public boolean isInVerificationLimit() {
583 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;")) {
584 ps.setInt(1, getId());
585 ps.setInt(2, VERIFICATION_MONTHS);
587 GigiResultSet rs = ps.executeQuery();