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 {
31 private Name name = new Name(null, null, null, null);
37 private Assurance[] receivedAssurances;
39 private Assurance[] madeAssurances;
41 private Locale locale;
43 private final Set<Group> groups = new HashSet<>();
45 public static final int MINIMUM_AGE = 16;
47 public static final int POJAM_AGE = 14;
49 public static final int ADULT_AGE = 18;
51 public static final boolean POJAM_ENABLED = false;
54 * Time in months a verification is considered "recent".
56 public static final int VERIFICATION_MONTHS = 39;
58 protected User(GigiResultSet rs) {
59 super(rs.getInt("id"));
63 private void updateName(GigiResultSet rs) {
64 name = new Name(rs.getString("fname"), rs.getString("lname"), rs.getString("mname"), rs.getString("suffix"));
65 dob = new DayDate(rs.getDate("dob"));
66 email = rs.getString("email");
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, Name name, DayDate dob, Locale locale) throws GigiApiException {
91 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `language`=?, id=?")) {
92 query.setString(1, email);
93 query.setString(2, PasswordHash.hash(password));
94 query.setString(3, name.getFname());
95 query.setString(4, name.getMname());
96 query.setString(5, name.getLname());
97 query.setString(6, name.getSuffix());
98 query.setDate(7, dob.toSQLDate());
99 query.setString(8, locale.toString());
100 query.setInt(9, getId());
103 new EmailAddress(this, email, locale);
106 public Name getName() {
110 public DayDate getDoB() {
114 public void setDoB(DayDate dob) {
118 public String getEmail() {
122 public void changePassword(String oldPass, String newPass) throws GigiApiException {
123 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
124 ps.setInt(1, getId());
125 try (GigiResultSet rs = ps.executeQuery()) {
127 throw new GigiApiException("User not found... very bad.");
129 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
130 throw new GigiApiException("Old password does not match.");
134 setPassword(newPass);
137 private void setPassword(String newPass) throws GigiApiException {
138 PasswordStrengthChecker.assertStrongPassword(newPass, getName(), getEmail());
139 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
140 ps.setString(1, PasswordHash.hash(newPass));
141 ps.setInt(2, getId());
146 public void setName(Name name) {
150 public boolean canAssure() {
152 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
156 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
160 if (getAssurancePoints() < 100) {
164 return hasPassedCATS();
168 public boolean hasPassedCATS() {
169 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
170 query.setInt(1, getId());
171 query.setInt(2, CATSType.ASSURER_CHALLENGE.getId());
172 try (GigiResultSet rs = query.executeQuery()) {
182 public int getAssurancePoints() {
183 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT SUM(lastpoints) FROM ( SELECT DISTINCT ON (`from`) `from`, `to`, `points` as lastpoints, `method` FROM `notary` WHERE `deleted` is NULL AND (`expire` IS NULL OR `expire` > CURRENT_TIMESTAMP) AND `to` = ? ORDER BY `from`, `when` DESC) as p")) {
184 query.setInt(1, getId());
186 GigiResultSet rs = query.executeQuery();
190 points = rs.getInt(1);
197 public int getExperiencePoints() {
198 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT count(*) FROM ( SELECT `to` FROM `notary` WHERE `from`=? AND `deleted` IS NULL AND `method` = ? ::`notaryType` GROUP BY `to`) as p")) {
199 query.setInt(1, getId());
200 query.setString(2, AssuranceType.FACE_TO_FACE.getDescription());
202 GigiResultSet rs = query.executeQuery();
206 points = rs.getInt(1) * 2;
214 * Gets the maximum allowed points NOW. Note that an assurance needs to
215 * re-check PoJam as it has taken place in the past.
217 * @return the maximal points @
219 public int getMaxAssurePoints() {
220 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
224 int exp = getExperiencePoints();
246 public boolean isValidName(String name) {
247 return getName().matches(name);
250 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
251 for (EmailAddress email : getEmails()) {
252 if (email.getAddress().equals(newMail.getAddress())) {
253 if ( !email.isVerified()) {
254 throw new GigiApiException("Email not verified.");
257 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
258 ps.setString(1, newMail.getAddress());
259 ps.setInt(2, getId());
263 this.email = newMail.getAddress();
268 throw new GigiApiException("Given address not an address of the user.");
271 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
272 if (getEmail().equals(delMail.getAddress())) {
273 throw new GigiApiException("Can't delete user's default e-mail.");
276 for (EmailAddress email : getEmails()) {
277 if (email.getId() == delMail.getId()) {
278 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
279 ps.setInt(1, delMail.getId());
285 throw new GigiApiException("Email not one of user's email addresses.");
288 public synchronized Assurance[] getReceivedAssurances() {
289 if (receivedAssurances == null) {
290 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` WHERE `to`=? AND `deleted` IS NULL")) {
291 query.setInt(1, getId());
293 GigiResultSet res = query.executeQuery();
294 List<Assurance> assurances = new LinkedList<Assurance>();
297 assurances.add(assuranceByRes(res));
300 this.receivedAssurances = assurances.toArray(new Assurance[0]);
304 return receivedAssurances;
307 public synchronized Assurance[] getMadeAssurances() {
308 if (madeAssurances == null) {
309 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL")) {
310 query.setInt(1, getId());
312 try (GigiResultSet res = query.executeQuery()) {
313 List<Assurance> assurances = new LinkedList<Assurance>();
316 assurances.add(assuranceByRes(res));
319 this.madeAssurances = assurances.toArray(new Assurance[0]);
324 return madeAssurances;
327 public synchronized void invalidateMadeAssurances() {
328 madeAssurances = null;
331 public synchronized void invalidateReceivedAssurances() {
332 receivedAssurances = null;
335 public void updateUserData() throws GigiApiException {
336 synchronized (Notary.class) {
337 if (getReceivedAssurances().length != 0) {
338 throw new GigiApiException("No change after assurance allowed.");
344 protected void rawUpdateUserData() {
345 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?")) {
346 update.setString(1, name.getFname());
347 update.setString(2, name.getLname());
348 update.setString(3, name.getMname());
349 update.setString(4, name.getSuffix());
350 update.setDate(5, getDoB().toSQLDate());
351 update.setInt(6, getId());
352 update.executeUpdate();
356 public Locale getPreferredLocale() {
360 public void setPreferredLocale(Locale locale) {
361 this.locale = locale;
365 public boolean isInGroup(Group g) {
366 return groups.contains(g);
369 public Set<Group> getGroups() {
370 return Collections.unmodifiableSet(groups);
373 public void grantGroup(User granter, Group toGrant) {
375 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
376 ps.setInt(1, getId());
377 ps.setString(2, toGrant.getDatabaseName());
378 ps.setInt(3, granter.getId());
383 public void revokeGroup(User revoker, Group toRevoke) {
384 groups.remove(toRevoke);
385 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
386 ps.setInt(1, revoker.getId());
387 ps.setString(2, toRevoke.getDatabaseName());
388 ps.setInt(3, getId());
393 public List<Organisation> getOrganisations() {
394 return getOrganisations(false);
397 public List<Organisation> getOrganisations(boolean isAdmin) {
398 List<Organisation> orgas = new ArrayList<>();
399 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
400 query.setInt(1, getId());
401 try (GigiResultSet res = query.executeQuery()) {
403 orgas.add(Organisation.getById(res.getInt(1)));
411 public static synchronized User getById(int id) {
412 CertificateOwner co = CertificateOwner.getById(id);
413 if (co instanceof User) {
420 public static User getByEmail(String mail) {
421 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
422 ps.setString(1, mail);
423 GigiResultSet rs = ps.executeQuery();
428 return User.getById(rs.getInt(1));
432 public static User[] findByEmail(String mail) {
433 LinkedList<User> results = new LinkedList<User>();
434 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")) {
435 ps.setString(1, mail);
436 GigiResultSet rs = ps.executeQuery();
438 results.add(User.getById(rs.getInt(1)));
440 return results.toArray(new User[results.size()]);
444 public EmailAddress[] getEmails() {
445 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
446 ps.setInt(1, getId());
448 GigiResultSet rs = ps.executeQuery();
449 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
452 data.add(EmailAddress.getById(rs.getInt(1)));
455 return data.toArray(new EmailAddress[0]);
460 public boolean isValidEmail(String email) {
461 for (EmailAddress em : getEmails()) {
462 if (em.getAddress().equals(email)) {
463 return em.isVerified();
470 public String[] getTrainings() {
471 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")) {
472 prep.setInt(1, getId());
473 GigiResultSet res = prep.executeQuery();
474 List<String> entries = new LinkedList<String>();
477 StringBuilder training = new StringBuilder();
478 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
479 training.append(" (");
480 training.append(res.getString(2));
481 if (res.getString(3).length() > 0) {
482 training.append(" ");
483 training.append(res.getString(3));
485 if (res.getString(4).length() > 0) {
486 training.append(", ");
487 training.append(res.getString(4));
489 training.append(")");
490 entries.add(training.toString());
493 return entries.toArray(new String[0]);
498 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
499 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
500 ps.setInt(1, getId());
501 ps.setInt(2, getId());
502 ps.setString(3, token);
503 ps.setString(4, PasswordHash.hash(privateToken));
505 return ps.lastInsertId();
509 public static User getResetWithToken(int id, String token) {
510 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
512 ps.setString(2, token);
513 ps.setInt(3, PasswordResetPage.HOUR_MAX);
514 GigiResultSet res = ps.executeQuery();
518 return User.getById(res.getInt(1));
522 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
523 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
525 ps.setInt(2, getId());
526 GigiResultSet rs = ps.executeQuery();
528 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
530 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
531 throw new GigiApiException("Private token does not match.");
533 setPassword(newPassword);
535 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
541 private Assurance assuranceByRes(GigiResultSet res) {
542 return new Assurance(res.getInt("id"), User.getById(res.getInt("from")), User.getById(res.getInt("to")), res.getString("location"), res.getString("method"), res.getInt("points"), res.getString("date"));
545 public static boolean isInVerificationLimit(int id) {
546 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT 1 FROM `notary` WHERE `to` = ? AND `when` > (now() - (interval '1 month' * ?)) AND (`expire` IS NULL OR `expire` > now()) AND `deleted` IS NULL;")) {
548 ps.setInt(2, VERIFICATION_MONTHS);
550 GigiResultSet rs = ps.executeQuery();