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.CATS.CATSType;
15 import org.cacert.gigi.localisation.Language;
16 import org.cacert.gigi.output.DateSelector;
17 import org.cacert.gigi.pages.PasswordResetPage;
18 import org.cacert.gigi.util.CalendarUtil;
19 import org.cacert.gigi.util.DayDate;
20 import org.cacert.gigi.util.Notary;
21 import org.cacert.gigi.util.PasswordHash;
22 import org.cacert.gigi.util.PasswordStrengthChecker;
25 * Represents an acting, assurable, user. Synchronizing on user means: no
26 * name-change and no assurance.
28 public class User extends CertificateOwner {
30 private Name name = new Name(null, null, null, null);
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;
53 * Time in months a verification is considered "recent".
55 public static final int VERIFICATION_MONTHS = 39;
57 protected User(GigiResultSet rs) {
58 super(rs.getInt("id"));
62 private void updateName(GigiResultSet rs) {
63 name = new Name(rs.getString("fname"), rs.getString("lname"), rs.getString("mname"), rs.getString("suffix"));
64 dob = new DayDate(rs.getDate("dob"));
65 email = rs.getString("email");
67 String localeStr = rs.getString("language");
68 if (localeStr == null || localeStr.equals("")) {
69 locale = Locale.getDefault();
71 locale = Language.getLocaleFromString(localeStr);
74 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
75 psg.setInt(1, rs.getInt("id"));
77 try (GigiResultSet rs2 = psg.executeQuery()) {
79 groups.add(Group.getByString(rs2.getString(1)));
85 public User(String email, String password, Name name, DayDate dob, Locale locale) throws GigiApiException {
90 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `language`=?, id=?")) {
91 query.setString(1, email);
92 query.setString(2, PasswordHash.hash(password));
93 query.setString(3, name.getFname());
94 query.setString(4, name.getMname());
95 query.setString(5, name.getLname());
96 query.setString(6, name.getSuffix());
97 query.setDate(7, dob.toSQLDate());
98 query.setString(8, locale.toString());
99 query.setInt(9, getId());
102 new EmailAddress(this, email, locale);
105 public Name getName() {
109 public DayDate getDoB() {
113 public void setDoB(DayDate dob) {
117 public String getEmail() {
121 public void changePassword(String oldPass, String newPass) throws GigiApiException {
122 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
123 ps.setInt(1, getId());
124 try (GigiResultSet rs = ps.executeQuery()) {
126 throw new GigiApiException("User not found... very bad.");
128 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
129 throw new GigiApiException("Old password does not match.");
133 setPassword(newPass);
136 private void setPassword(String newPass) throws GigiApiException {
137 PasswordStrengthChecker.assertStrongPassword(newPass, getName(), getEmail());
138 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
139 ps.setString(1, PasswordHash.hash(newPass));
140 ps.setInt(2, getId());
145 public void setName(Name name) {
149 public boolean canAssure() {
151 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
155 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
159 if (getAssurancePoints() < 100) {
163 return hasPassedCATS();
167 public boolean hasPassedCATS() {
168 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
169 query.setInt(1, getId());
170 query.setInt(2, CATSType.ASSURER_CHALLENGE.getId());
171 try (GigiResultSet rs = query.executeQuery()) {
181 public int getAssurancePoints() {
182 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT sum(points) FROM `notary` where `to`=? AND `deleted` is NULL AND (`expire` IS NULL OR `expire` > CURRENT_TIMESTAMP)")) {
183 query.setInt(1, getId());
185 GigiResultSet rs = query.executeQuery();
189 points = rs.getInt(1);
196 public int getExperiencePoints() {
197 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT count(*) FROM `notary` where `from`=? AND `deleted` is NULL")) {
198 query.setInt(1, getId());
200 GigiResultSet rs = query.executeQuery();
204 points = rs.getInt(1) * 2;
212 * Gets the maximum allowed points NOW. Note that an assurance needs to
213 * re-check PoJam as it has taken place in the past.
215 * @return the maximal points @
217 public int getMaxAssurePoints() {
218 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
222 int exp = getExperiencePoints();
244 public boolean isValidName(String name) {
245 return getName().matches(name);
248 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
249 for (EmailAddress email : getEmails()) {
250 if (email.getAddress().equals(newMail.getAddress())) {
251 if ( !email.isVerified()) {
252 throw new GigiApiException("Email not verified.");
255 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
256 ps.setString(1, newMail.getAddress());
257 ps.setInt(2, getId());
261 this.email = newMail.getAddress();
266 throw new GigiApiException("Given address not an address of the user.");
269 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
270 if (getEmail().equals(delMail.getAddress())) {
271 throw new GigiApiException("Can't delete user's default e-mail.");
274 for (EmailAddress email : getEmails()) {
275 if (email.getId() == delMail.getId()) {
276 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
277 ps.setInt(1, delMail.getId());
283 throw new GigiApiException("Email not one of user's email addresses.");
286 public synchronized Assurance[] getReceivedAssurances() {
287 if (receivedAssurances == null) {
288 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` WHERE `to`=? AND `deleted` IS NULL")) {
289 query.setInt(1, getId());
291 GigiResultSet res = query.executeQuery();
292 List<Assurance> assurances = new LinkedList<Assurance>();
295 assurances.add(assuranceByRes(res));
298 this.receivedAssurances = assurances.toArray(new Assurance[0]);
302 return receivedAssurances;
305 public synchronized Assurance[] getMadeAssurances() {
306 if (madeAssurances == null) {
307 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL")) {
308 query.setInt(1, getId());
310 try (GigiResultSet res = query.executeQuery()) {
311 List<Assurance> assurances = new LinkedList<Assurance>();
314 assurances.add(assuranceByRes(res));
317 this.madeAssurances = assurances.toArray(new Assurance[0]);
322 return madeAssurances;
325 public synchronized void invalidateMadeAssurances() {
326 madeAssurances = null;
329 public synchronized void invalidateReceivedAssurances() {
330 receivedAssurances = null;
333 public void updateUserData() throws GigiApiException {
334 synchronized (Notary.class) {
335 if (getReceivedAssurances().length != 0) {
336 throw new GigiApiException("No change after assurance allowed.");
342 protected void rawUpdateUserData() {
343 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?")) {
344 update.setString(1, name.getFname());
345 update.setString(2, name.getLname());
346 update.setString(3, name.getMname());
347 update.setString(4, name.getSuffix());
348 update.setDate(5, getDoB().toSQLDate());
349 update.setInt(6, getId());
350 update.executeUpdate();
354 public Locale getPreferredLocale() {
358 public void setPreferredLocale(Locale locale) {
359 this.locale = locale;
363 public boolean wantsDirectoryListing() {
364 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT listme FROM users WHERE id=?")) {
365 get.setInt(1, getId());
366 GigiResultSet exec = get.executeQuery();
367 return exec.next() && exec.getBoolean("listme");
371 public String getContactInformation() {
372 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT contactinfo FROM users WHERE id=?")) {
373 get.setInt(1, getId());
375 GigiResultSet exec = get.executeQuery();
377 return exec.getString("contactinfo");
381 public void setDirectoryListing(boolean on) {
382 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET listme = ? WHERE id = ?")) {
383 update.setBoolean(1, on);
384 update.setInt(2, getId());
385 update.executeUpdate();
389 public void setContactInformation(String contactInfo) {
390 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET contactinfo = ? WHERE id = ?")) {
391 update.setString(1, contactInfo);
392 update.setInt(2, getId());
393 update.executeUpdate();
397 public boolean isInGroup(Group g) {
398 return groups.contains(g);
401 public Set<Group> getGroups() {
402 return Collections.unmodifiableSet(groups);
405 public void grantGroup(User granter, Group toGrant) {
407 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
408 ps.setInt(1, getId());
409 ps.setString(2, toGrant.getDatabaseName());
410 ps.setInt(3, granter.getId());
415 public void revokeGroup(User revoker, Group toRevoke) {
416 groups.remove(toRevoke);
417 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
418 ps.setInt(1, revoker.getId());
419 ps.setString(2, toRevoke.getDatabaseName());
420 ps.setInt(3, getId());
425 public List<Organisation> getOrganisations() {
426 return getOrganisations(false);
429 public List<Organisation> getOrganisations(boolean isAdmin) {
430 List<Organisation> orgas = new ArrayList<>();
431 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
432 query.setInt(1, getId());
433 try (GigiResultSet res = query.executeQuery()) {
435 orgas.add(Organisation.getById(res.getInt(1)));
443 public static synchronized User getById(int id) {
444 CertificateOwner co = CertificateOwner.getById(id);
445 if (co instanceof User) {
452 public static User getByEmail(String mail) {
453 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
454 ps.setString(1, mail);
455 GigiResultSet rs = ps.executeQuery();
460 return User.getById(rs.getInt(1));
464 public static User[] findByEmail(String mail) {
465 LinkedList<User> results = new LinkedList<User>();
466 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")) {
467 ps.setString(1, mail);
468 GigiResultSet rs = ps.executeQuery();
470 results.add(User.getById(rs.getInt(1)));
472 return results.toArray(new User[results.size()]);
476 public EmailAddress[] getEmails() {
477 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
478 ps.setInt(1, getId());
480 GigiResultSet rs = ps.executeQuery();
481 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
484 data.add(EmailAddress.getById(rs.getInt(1)));
487 return data.toArray(new EmailAddress[0]);
492 public boolean isValidEmail(String email) {
493 for (EmailAddress em : getEmails()) {
494 if (em.getAddress().equals(email)) {
495 return em.isVerified();
502 public String[] getTrainings() {
503 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")) {
504 prep.setInt(1, getId());
505 GigiResultSet res = prep.executeQuery();
506 List<String> entries = new LinkedList<String>();
509 StringBuilder training = new StringBuilder();
510 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
511 training.append(" (");
512 training.append(res.getString(2));
513 if (res.getString(3).length() > 0) {
514 training.append(" ");
515 training.append(res.getString(3));
517 if (res.getString(4).length() > 0) {
518 training.append(", ");
519 training.append(res.getString(4));
521 training.append(")");
522 entries.add(training.toString());
525 return entries.toArray(new String[0]);
530 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
531 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
532 ps.setInt(1, getId());
533 ps.setInt(2, getId());
534 ps.setString(3, token);
535 ps.setString(4, PasswordHash.hash(privateToken));
537 return ps.lastInsertId();
541 public static User getResetWithToken(int id, String token) {
542 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
544 ps.setString(2, token);
545 ps.setInt(3, PasswordResetPage.HOUR_MAX);
546 GigiResultSet res = ps.executeQuery();
550 return User.getById(res.getInt(1));
554 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
555 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
557 ps.setInt(2, getId());
558 GigiResultSet rs = ps.executeQuery();
560 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
562 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
563 throw new GigiApiException("Private token does not match.");
565 setPassword(newPassword);
567 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
573 private Assurance assuranceByRes(GigiResultSet res) {
574 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"));
577 public static boolean isInVerificationLimit(int id) {
578 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;")) {
580 ps.setInt(2, VERIFICATION_MONTHS);
582 GigiResultSet rs = ps.executeQuery();