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 POJAM_AGE = 14;
48 public static final int ADULT_AGE = 18;
50 public static final boolean POJAM_ENABLED = false;
52 public static final int EXPERIENCE_POINTS = 2;
55 * Time in months a verification is considered "recent".
57 public static final int VERIFICATION_MONTHS = TimeConditions.getInstance().getVerificationMonths();
59 private Name preferredName;
61 protected User(GigiResultSet rs) {
62 super(rs.getInt("id"));
66 private void updateName(GigiResultSet rs) {
67 dob = new DayDate(rs.getDate("dob"));
68 email = rs.getString("email");
69 preferredName = Name.getById(rs.getInt("preferredName"));
71 String localeStr = rs.getString("language");
72 if (localeStr == null || localeStr.equals("")) {
73 locale = Locale.getDefault();
75 locale = Language.getLocaleFromString(localeStr);
78 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
79 psg.setInt(1, rs.getInt("id"));
81 try (GigiResultSet rs2 = psg.executeQuery()) {
83 groups.add(Group.getByString(rs2.getString(1)));
89 public User(String email, String password, DayDate dob, Locale locale, NamePart... preferred) throws GigiApiException {
93 this.preferredName = new Name(this, preferred);
94 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, `dob`=?, `language`=?, id=?, `preferredName`=?")) {
95 query.setString(1, email);
96 query.setString(2, PasswordHash.hash(password));
97 query.setDate(3, dob.toSQLDate());
98 query.setString(4, locale.toString());
99 query.setInt(5, getId());
100 query.setInt(6, preferredName.getId());
103 new EmailAddress(this, email, locale);
106 public Name[] getNames() {
107 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL", true)) {
108 return fetchNamesToArray(gps);
112 public Name[] getNonDeprecatedNames() {
113 try (GigiPreparedStatement gps = new GigiPreparedStatement("SELECT `id` FROM `names` WHERE `uid`=? AND `deleted` IS NULL AND `deprecated` IS NULL", true)) {
114 return fetchNamesToArray(gps);
118 private Name[] fetchNamesToArray(GigiPreparedStatement gps) {
119 gps.setInt(1, getId());
120 GigiResultSet rs = gps.executeQuery();
122 Name[] dt = new Name[rs.getRow()];
124 for (int i = 0; rs.next(); i++) {
125 dt[i] = Name.getById(rs.getInt(1));
130 public DayDate getDoB() {
134 public void setDoB(DayDate dob) throws GigiApiException {
135 synchronized (Notary.class) {
136 if (getReceivedAssurances().length != 0) {
137 throw new GigiApiException("No change after assurance allowed.");
145 protected void setDoBAsSupport(DayDate dob) throws GigiApiException {
146 synchronized (Notary.class) {
153 public String getEmail() {
157 public void changePassword(String oldPass, String newPass) throws GigiApiException {
158 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
159 ps.setInt(1, getId());
160 try (GigiResultSet rs = ps.executeQuery()) {
162 throw new GigiApiException("User not found... very bad.");
164 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
165 throw new GigiApiException("Old password does not match.");
169 setPassword(newPass);
172 private void setPassword(String newPass) throws GigiApiException {
173 PasswordStrengthChecker.assertStrongPassword(newPass, getNames(), getEmail());
174 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
175 ps.setString(1, PasswordHash.hash(newPass));
176 ps.setInt(2, getId());
181 public boolean canAssure() {
183 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
187 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
191 if (getAssurancePoints() < 100) {
195 return hasPassedCATS();
199 public boolean hasPassedCATS() {
200 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
201 query.setInt(1, getId());
202 query.setInt(2, CATSType.ASSURER_CHALLENGE.getId());
203 try (GigiResultSet rs = query.executeQuery()) {
213 public int getAssurancePoints() {
214 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")) {
215 query.setInt(1, getId());
217 GigiResultSet rs = query.executeQuery();
221 points = rs.getInt(1);
228 public int getExperiencePoints() {
229 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")) {
230 query.setInt(1, getId());
231 query.setString(2, AssuranceType.FACE_TO_FACE.getDescription());
233 GigiResultSet rs = query.executeQuery();
237 points = rs.getInt(1) * EXPERIENCE_POINTS;
245 * Gets the maximum allowed points NOW. Note that an assurance needs to
246 * re-check PoJam as it has taken place in the past.
248 * @return the maximal points @
250 public int getMaxAssurePoints() {
251 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
255 int exp = getExperiencePoints();
258 if (exp >= 5 * EXPERIENCE_POINTS) {
261 if (exp >= 10 * EXPERIENCE_POINTS) {
264 if (exp >= 15 * EXPERIENCE_POINTS) {
267 if (exp >= 20 * EXPERIENCE_POINTS) {
270 if (exp >= 25 * EXPERIENCE_POINTS) {
277 public boolean isValidName(String name) {
278 for (Name n : getNames()) {
279 if (n.matches(name) && n.getAssurancePoints() >= 50) {
286 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
287 for (EmailAddress email : getEmails()) {
288 if (email.getAddress().equals(newMail.getAddress())) {
289 if ( !email.isVerified()) {
290 throw new GigiApiException("Email not verified.");
293 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
294 ps.setString(1, newMail.getAddress());
295 ps.setInt(2, getId());
299 this.email = newMail.getAddress();
304 throw new GigiApiException("Given address not an address of the user.");
307 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
308 if (getEmail().equals(delMail.getAddress())) {
309 throw new GigiApiException("Can't delete user's default e-mail.");
312 for (EmailAddress email : getEmails()) {
313 if (email.getId() == delMail.getId()) {
314 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
315 ps.setInt(1, delMail.getId());
321 throw new GigiApiException("Email not one of user's email addresses.");
324 public synchronized Assurance[] getReceivedAssurances() {
325 if (receivedAssurances == null) {
326 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` INNER JOIN `names` ON `names`.`id` = `notary`.`to` WHERE `names`.`uid`=? AND `notary`.`deleted` IS NULL")) {
327 query.setInt(1, getId());
329 GigiResultSet res = query.executeQuery();
330 List<Assurance> assurances = new LinkedList<Assurance>();
333 assurances.add(assuranceByRes(res));
336 this.receivedAssurances = assurances.toArray(new Assurance[0]);
340 return receivedAssurances;
343 public synchronized Assurance[] getMadeAssurances() {
344 if (madeAssurances == null) {
345 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL")) {
346 query.setInt(1, getId());
348 try (GigiResultSet res = query.executeQuery()) {
349 List<Assurance> assurances = new LinkedList<Assurance>();
352 assurances.add(assuranceByRes(res));
355 this.madeAssurances = assurances.toArray(new Assurance[0]);
360 return madeAssurances;
363 public synchronized void invalidateMadeAssurances() {
364 madeAssurances = null;
367 public synchronized void invalidateReceivedAssurances() {
368 receivedAssurances = null;
371 private void rawUpdateUserData() {
372 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET dob=? WHERE id=?")) {
373 update.setDate(1, getDoB().toSQLDate());
374 update.setInt(2, getId());
375 update.executeUpdate();
379 public Locale getPreferredLocale() {
383 public void setPreferredLocale(Locale locale) {
384 this.locale = locale;
388 public Name getPreferredName() {
389 return preferredName;
392 public synchronized void setPreferredName(Name preferred) throws GigiApiException {
393 if (preferred.getOwner() != this) {
394 throw new GigiApiException("Cannot set a name as preferred one that does not belong to this account.");
396 this.preferredName = preferred;
397 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `users` SET `preferredName`=? WHERE `id`=?")) {
398 ps.setInt(1, preferred.getId());
399 ps.setInt(2, getId());
405 public boolean isInGroup(Group g) {
406 return groups.contains(g);
409 public Set<Group> getGroups() {
410 return Collections.unmodifiableSet(groups);
413 public void grantGroup(User granter, Group toGrant) {
415 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
416 ps.setInt(1, getId());
417 ps.setString(2, toGrant.getDatabaseName());
418 ps.setInt(3, granter.getId());
423 public void revokeGroup(User revoker, Group toRevoke) {
424 groups.remove(toRevoke);
425 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
426 ps.setInt(1, revoker.getId());
427 ps.setString(2, toRevoke.getDatabaseName());
428 ps.setInt(3, getId());
433 public List<Organisation> getOrganisations() {
434 return getOrganisations(false);
437 public List<Organisation> getOrganisations(boolean isAdmin) {
438 List<Organisation> orgas = new ArrayList<>();
439 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
440 query.setInt(1, getId());
441 try (GigiResultSet res = query.executeQuery()) {
443 orgas.add(Organisation.getById(res.getInt(1)));
451 public static synchronized User getById(int id) {
452 CertificateOwner co = CertificateOwner.getById(id);
453 if (co instanceof User) {
460 public static User getByEmail(String mail) {
461 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
462 ps.setString(1, mail);
463 GigiResultSet rs = ps.executeQuery();
468 return User.getById(rs.getInt(1));
472 public static User[] findByEmail(String mail) {
473 LinkedList<User> results = new LinkedList<User>();
474 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")) {
475 ps.setString(1, mail);
476 GigiResultSet rs = ps.executeQuery();
478 results.add(User.getById(rs.getInt(1)));
480 return results.toArray(new User[results.size()]);
484 public EmailAddress[] getEmails() {
485 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
486 ps.setInt(1, getId());
488 GigiResultSet rs = ps.executeQuery();
489 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
492 data.add(EmailAddress.getById(rs.getInt(1)));
495 return data.toArray(new EmailAddress[0]);
500 public boolean isValidEmail(String email) {
501 for (EmailAddress em : getEmails()) {
502 if (em.getAddress().equals(email)) {
503 return em.isVerified();
510 public String[] getTrainings() {
511 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")) {
512 prep.setInt(1, getId());
513 GigiResultSet res = prep.executeQuery();
514 List<String> entries = new LinkedList<String>();
517 StringBuilder training = new StringBuilder();
518 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
519 training.append(" (");
520 training.append(res.getString(2));
521 if (res.getString(3).length() > 0) {
522 training.append(" ");
523 training.append(res.getString(3));
525 if (res.getString(4).length() > 0) {
526 training.append(", ");
527 training.append(res.getString(4));
529 training.append(")");
530 entries.add(training.toString());
533 return entries.toArray(new String[0]);
538 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
539 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
540 ps.setInt(1, getId());
541 ps.setInt(2, getId());
542 ps.setString(3, token);
543 ps.setString(4, PasswordHash.hash(privateToken));
545 return ps.lastInsertId();
549 public static User getResetWithToken(int id, String token) {
550 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
552 ps.setString(2, token);
553 ps.setInt(3, PasswordResetPage.HOUR_MAX);
554 GigiResultSet res = ps.executeQuery();
558 return User.getById(res.getInt(1));
562 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
563 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
565 ps.setInt(2, getId());
566 GigiResultSet rs = ps.executeQuery();
568 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
570 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
571 throw new GigiApiException("Private token does not match.");
573 setPassword(newPassword);
575 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
581 private Assurance assuranceByRes(GigiResultSet res) {
582 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"));
585 public boolean isInVerificationLimit() {
586 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;")) {
587 ps.setInt(1, getId());
588 ps.setInt(2, VERIFICATION_MONTHS);
590 GigiResultSet rs = ps.executeQuery();