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;
52 protected User(GigiResultSet rs) {
53 super(rs.getInt("id"));
57 private void updateName(GigiResultSet rs) {
58 name = new Name(rs.getString("fname"), rs.getString("lname"), rs.getString("mname"), rs.getString("suffix"));
59 dob = new DayDate(rs.getDate("dob"));
60 email = rs.getString("email");
62 String localeStr = rs.getString("language");
63 if (localeStr == null || localeStr.equals("")) {
64 locale = Locale.getDefault();
66 locale = Language.getLocaleFromString(localeStr);
69 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
70 psg.setInt(1, rs.getInt("id"));
72 try (GigiResultSet rs2 = psg.executeQuery()) {
74 groups.add(Group.getByString(rs2.getString(1)));
80 public User(String email, String password, Name name, DayDate dob, Locale locale) throws GigiApiException {
85 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `language`=?, id=?")) {
86 query.setString(1, email);
87 query.setString(2, PasswordHash.hash(password));
88 query.setString(3, name.getFname());
89 query.setString(4, name.getMname());
90 query.setString(5, name.getLname());
91 query.setString(6, name.getSuffix());
92 query.setDate(7, dob.toSQLDate());
93 query.setString(8, locale.toString());
94 query.setInt(9, getId());
97 new EmailAddress(this, email, locale);
100 public Name getName() {
104 public DayDate getDoB() {
108 public void setDoB(DayDate dob) {
112 public String getEmail() {
116 public void changePassword(String oldPass, String newPass) throws GigiApiException {
117 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
118 ps.setInt(1, getId());
119 try (GigiResultSet rs = ps.executeQuery()) {
121 throw new GigiApiException("User not found... very bad.");
123 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
124 throw new GigiApiException("Old password does not match.");
128 setPassword(newPass);
131 private void setPassword(String newPass) throws GigiApiException {
132 PasswordStrengthChecker.assertStrongPassword(newPass, getName(), getEmail());
133 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
134 ps.setString(1, PasswordHash.hash(newPass));
135 ps.setInt(2, getId());
140 public void setName(Name name) {
144 public boolean canAssure() {
146 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
150 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
154 if (getAssurancePoints() < 100) {
158 return hasPassedCATS();
162 public boolean hasPassedCATS() {
163 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
164 query.setInt(1, getId());
165 query.setInt(2, CATSType.ASSURER_CHALLENGE.getId());
166 try (GigiResultSet rs = query.executeQuery()) {
176 public int getAssurancePoints() {
177 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT sum(points) FROM `notary` where `to`=? AND `deleted` is NULL AND (`expire` IS NULL OR `expire` > CURRENT_TIMESTAMP)")) {
178 query.setInt(1, getId());
180 GigiResultSet rs = query.executeQuery();
184 points = rs.getInt(1);
191 public int getExperiencePoints() {
192 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT count(*) FROM `notary` where `from`=? AND `deleted` is NULL")) {
193 query.setInt(1, getId());
195 GigiResultSet rs = query.executeQuery();
199 points = rs.getInt(1) * 2;
207 * Gets the maximum allowed points NOW. Note that an assurance needs to
208 * re-check PoJam as it has taken place in the past.
210 * @return the maximal points @
212 public int getMaxAssurePoints() {
213 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
217 int exp = getExperiencePoints();
239 public boolean isValidName(String name) {
240 return getName().matches(name);
243 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
244 for (EmailAddress email : getEmails()) {
245 if (email.getAddress().equals(newMail.getAddress())) {
246 if ( !email.isVerified()) {
247 throw new GigiApiException("Email not verified.");
250 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
251 ps.setString(1, newMail.getAddress());
252 ps.setInt(2, getId());
256 this.email = newMail.getAddress();
261 throw new GigiApiException("Given address not an address of the user.");
264 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
265 if (getEmail().equals(delMail.getAddress())) {
266 throw new GigiApiException("Can't delete user's default e-mail.");
269 for (EmailAddress email : getEmails()) {
270 if (email.getId() == delMail.getId()) {
271 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
272 ps.setInt(1, delMail.getId());
278 throw new GigiApiException("Email not one of user's email addresses.");
281 public synchronized Assurance[] getReceivedAssurances() {
282 if (receivedAssurances == null) {
283 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` WHERE `to`=? AND `deleted` IS NULL")) {
284 query.setInt(1, getId());
286 GigiResultSet res = query.executeQuery();
287 List<Assurance> assurances = new LinkedList<Assurance>();
290 assurances.add(assuranceByRes(res));
293 this.receivedAssurances = assurances.toArray(new Assurance[0]);
297 return receivedAssurances;
300 public synchronized Assurance[] getMadeAssurances() {
301 if (madeAssurances == null) {
302 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL")) {
303 query.setInt(1, getId());
305 try (GigiResultSet res = query.executeQuery()) {
306 List<Assurance> assurances = new LinkedList<Assurance>();
309 assurances.add(assuranceByRes(res));
312 this.madeAssurances = assurances.toArray(new Assurance[0]);
317 return madeAssurances;
320 public synchronized void invalidateMadeAssurances() {
321 madeAssurances = null;
324 public synchronized void invalidateReceivedAssurances() {
325 receivedAssurances = null;
328 public void updateUserData() throws GigiApiException {
329 synchronized (Notary.class) {
330 if (getReceivedAssurances().length != 0) {
331 throw new GigiApiException("No change after assurance allowed.");
337 protected void rawUpdateUserData() {
338 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?")) {
339 update.setString(1, name.getFname());
340 update.setString(2, name.getLname());
341 update.setString(3, name.getMname());
342 update.setString(4, name.getSuffix());
343 update.setDate(5, getDoB().toSQLDate());
344 update.setInt(6, getId());
345 update.executeUpdate();
349 public Locale getPreferredLocale() {
353 public void setPreferredLocale(Locale locale) {
354 this.locale = locale;
358 public boolean wantsDirectoryListing() {
359 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT listme FROM users WHERE id=?")) {
360 get.setInt(1, getId());
361 GigiResultSet exec = get.executeQuery();
362 return exec.next() && exec.getBoolean("listme");
366 public String getContactInformation() {
367 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT contactinfo FROM users WHERE id=?")) {
368 get.setInt(1, getId());
370 GigiResultSet exec = get.executeQuery();
372 return exec.getString("contactinfo");
376 public void setDirectoryListing(boolean on) {
377 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET listme = ? WHERE id = ?")) {
378 update.setBoolean(1, on);
379 update.setInt(2, getId());
380 update.executeUpdate();
384 public void setContactInformation(String contactInfo) {
385 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET contactinfo = ? WHERE id = ?")) {
386 update.setString(1, contactInfo);
387 update.setInt(2, getId());
388 update.executeUpdate();
392 public boolean isInGroup(Group g) {
393 return groups.contains(g);
396 public Set<Group> getGroups() {
397 return Collections.unmodifiableSet(groups);
400 public void grantGroup(User granter, Group toGrant) {
402 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
403 ps.setInt(1, getId());
404 ps.setString(2, toGrant.getDatabaseName());
405 ps.setInt(3, granter.getId());
410 public void revokeGroup(User revoker, Group toRevoke) {
411 groups.remove(toRevoke);
412 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
413 ps.setInt(1, revoker.getId());
414 ps.setString(2, toRevoke.getDatabaseName());
415 ps.setInt(3, getId());
420 public List<Organisation> getOrganisations() {
421 return getOrganisations(false);
424 public List<Organisation> getOrganisations(boolean isAdmin) {
425 List<Organisation> orgas = new ArrayList<>();
426 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
427 query.setInt(1, getId());
428 try (GigiResultSet res = query.executeQuery()) {
430 orgas.add(Organisation.getById(res.getInt(1)));
438 public static synchronized User getById(int id) {
439 CertificateOwner co = CertificateOwner.getById(id);
440 if (co instanceof User) {
447 public static User getByEmail(String mail) {
448 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
449 ps.setString(1, mail);
450 GigiResultSet rs = ps.executeQuery();
455 return User.getById(rs.getInt(1));
459 public static User[] findByEmail(String mail) {
460 LinkedList<User> results = new LinkedList<User>();
461 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")) {
462 ps.setString(1, mail);
463 GigiResultSet rs = ps.executeQuery();
465 results.add(User.getById(rs.getInt(1)));
467 return results.toArray(new User[results.size()]);
471 public EmailAddress[] getEmails() {
472 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
473 ps.setInt(1, getId());
475 GigiResultSet rs = ps.executeQuery();
476 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
479 data.add(EmailAddress.getById(rs.getInt(1)));
482 return data.toArray(new EmailAddress[0]);
487 public boolean isValidEmail(String email) {
488 for (EmailAddress em : getEmails()) {
489 if (em.getAddress().equals(email)) {
490 return em.isVerified();
497 public String[] getTrainings() {
498 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")) {
499 prep.setInt(1, getId());
500 GigiResultSet res = prep.executeQuery();
501 List<String> entries = new LinkedList<String>();
504 StringBuilder training = new StringBuilder();
505 training.append(DateSelector.getDateFormat().format(res.getTimestamp(1)));
506 training.append(" (");
507 training.append(res.getString(2));
508 if (res.getString(3).length() > 0) {
509 training.append(" ");
510 training.append(res.getString(3));
512 if (res.getString(4).length() > 0) {
513 training.append(", ");
514 training.append(res.getString(4));
516 training.append(")");
517 entries.add(training.toString());
520 return entries.toArray(new String[0]);
525 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
526 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
527 ps.setInt(1, getId());
528 ps.setInt(2, getId());
529 ps.setString(3, token);
530 ps.setString(4, PasswordHash.hash(privateToken));
532 return ps.lastInsertId();
536 public static User getResetWithToken(int id, String token) {
537 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL AND `created` > CURRENT_TIMESTAMP - interval '1 hours' * ?")) {
539 ps.setString(2, token);
540 ps.setInt(3, PasswordResetPage.HOUR_MAX);
541 GigiResultSet res = ps.executeQuery();
545 return User.getById(res.getInt(1));
549 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
550 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
552 ps.setInt(2, getId());
553 GigiResultSet rs = ps.executeQuery();
555 throw new GigiApiException("Token could not be found, has already been used, or is expired.");
557 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
558 throw new GigiApiException("Private token does not match.");
560 setPassword(newPassword);
562 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
568 private Assurance assuranceByRes(GigiResultSet res) {
569 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"));