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.localisation.Language;
15 import org.cacert.gigi.output.DateSelector;
16 import org.cacert.gigi.util.CalendarUtil;
17 import org.cacert.gigi.util.DayDate;
18 import org.cacert.gigi.util.Notary;
19 import org.cacert.gigi.util.PasswordHash;
20 import org.cacert.gigi.util.PasswordStrengthChecker;
23 * Represents an acting, assurable, user. Synchronizing on user means: no
24 * name-change and no assurance.
26 public class User extends CertificateOwner {
28 private Name name = new Name(null, null, null, null);
34 private Assurance[] receivedAssurances;
36 private Assurance[] madeAssurances;
38 private Locale locale;
40 private final Set<Group> groups = new HashSet<>();
42 public static final int MINIMUM_AGE = 16;
44 public static final int POJAM_AGE = 14;
46 public static final int ADULT_AGE = 18;
48 public static final boolean POJAM_ENABLED = false;
50 protected User(GigiResultSet rs) {
51 super(rs.getInt("id"));
55 private void updateName(GigiResultSet rs) {
56 name = new Name(rs.getString("fname"), rs.getString("lname"), rs.getString("mname"), rs.getString("suffix"));
57 dob = new DayDate(rs.getDate("dob"));
58 email = rs.getString("email");
60 String localeStr = rs.getString("language");
61 if (localeStr == null || localeStr.equals("")) {
62 locale = Locale.getDefault();
64 locale = Language.getLocaleFromString(localeStr);
67 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
68 psg.setInt(1, rs.getInt("id"));
70 try (GigiResultSet rs2 = psg.executeQuery()) {
72 groups.add(Group.getByString(rs2.getString(1)));
78 public User(String email, String password, Name name, DayDate dob, Locale locale) throws GigiApiException {
83 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `language`=?, id=?")) {
84 query.setString(1, email);
85 query.setString(2, PasswordHash.hash(password));
86 query.setString(3, name.getFname());
87 query.setString(4, name.getMname());
88 query.setString(5, name.getLname());
89 query.setString(6, name.getSuffix());
90 query.setDate(7, dob.toSQLDate());
91 query.setString(8, locale.toString());
92 query.setInt(9, getId());
95 new EmailAddress(this, email, locale);
98 public Name getName() {
102 public DayDate getDoB() {
106 public void setDoB(DayDate dob) {
110 public String getEmail() {
114 public void changePassword(String oldPass, String newPass) throws GigiApiException {
115 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
116 ps.setInt(1, getId());
117 try (GigiResultSet rs = ps.executeQuery()) {
119 throw new GigiApiException("User not found... very bad.");
121 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
122 throw new GigiApiException("Old password does not match.");
126 setPassword(newPass);
129 private void setPassword(String newPass) throws GigiApiException {
130 PasswordStrengthChecker.assertStrongPassword(newPass, getName(), getEmail());
131 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
132 ps.setString(1, PasswordHash.hash(newPass));
133 ps.setInt(2, getId());
138 public void setName(Name name) {
142 public boolean canAssure() {
144 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
148 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
152 if (getAssurancePoints() < 100) {
156 return hasPassedCATS();
160 public boolean hasPassedCATS() {
161 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
162 query.setInt(1, getId());
163 query.setInt(2, CATS.ASSURER_CHALLANGE_ID);
164 try (GigiResultSet rs = query.executeQuery()) {
174 public int getAssurancePoints() {
175 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT sum(points) FROM `notary` where `to`=? AND `deleted` is NULL AND (`expire` IS NULL OR `expire` > CURRENT_TIMESTAMP)")) {
176 query.setInt(1, getId());
178 GigiResultSet rs = query.executeQuery();
182 points = rs.getInt(1);
189 public int getExperiencePoints() {
190 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT count(*) FROM `notary` where `from`=? AND `deleted` is NULL")) {
191 query.setInt(1, getId());
193 GigiResultSet rs = query.executeQuery();
197 points = rs.getInt(1) * 2;
205 * Gets the maximum allowed points NOW. Note that an assurance needs to
206 * re-check PoJam as it has taken place in the past.
208 * @return the maximal points @
210 public int getMaxAssurePoints() {
211 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE) && POJAM_ENABLED) {
215 int exp = getExperiencePoints();
237 public boolean isValidName(String name) {
238 return getName().matches(name);
241 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
242 for (EmailAddress email : getEmails()) {
243 if (email.getAddress().equals(newMail.getAddress())) {
244 if ( !email.isVerified()) {
245 throw new GigiApiException("Email not verified.");
248 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
249 ps.setString(1, newMail.getAddress());
250 ps.setInt(2, getId());
254 this.email = newMail.getAddress();
259 throw new GigiApiException("Given address not an address of the user.");
262 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
263 if (getEmail().equals(delMail.getAddress())) {
264 throw new GigiApiException("Can't delete user's default e-mail.");
267 for (EmailAddress email : getEmails()) {
268 if (email.getId() == delMail.getId()) {
269 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
270 ps.setInt(1, delMail.getId());
276 throw new GigiApiException("Email not one of user's email addresses.");
279 public synchronized Assurance[] getReceivedAssurances() {
280 if (receivedAssurances == null) {
281 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` WHERE `to`=? AND `deleted` IS NULL")) {
282 query.setInt(1, getId());
284 GigiResultSet res = query.executeQuery();
285 List<Assurance> assurances = new LinkedList<Assurance>();
288 assurances.add(assuranceByRes(res));
291 this.receivedAssurances = assurances.toArray(new Assurance[0]);
295 return receivedAssurances;
298 public synchronized Assurance[] getMadeAssurances() {
299 if (madeAssurances == null) {
300 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL")) {
301 query.setInt(1, getId());
303 try (GigiResultSet res = query.executeQuery()) {
304 List<Assurance> assurances = new LinkedList<Assurance>();
307 assurances.add(assuranceByRes(res));
310 this.madeAssurances = assurances.toArray(new Assurance[0]);
315 return madeAssurances;
318 public synchronized void invalidateMadeAssurances() {
319 madeAssurances = null;
322 public synchronized void invalidateReceivedAssurances() {
323 receivedAssurances = null;
326 public void updateUserData() throws GigiApiException {
327 synchronized (Notary.class) {
328 if (getReceivedAssurances().length != 0) {
329 throw new GigiApiException("No change after assurance allowed.");
335 protected void rawUpdateUserData() {
336 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?")) {
337 update.setString(1, name.getFname());
338 update.setString(2, name.getLname());
339 update.setString(3, name.getMname());
340 update.setString(4, name.getSuffix());
341 update.setDate(5, getDoB().toSQLDate());
342 update.setInt(6, getId());
343 update.executeUpdate();
347 public Locale getPreferredLocale() {
351 public void setPreferredLocale(Locale locale) {
352 this.locale = locale;
356 public boolean wantsDirectoryListing() {
357 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT listme FROM users WHERE id=?")) {
358 get.setInt(1, getId());
359 GigiResultSet exec = get.executeQuery();
360 return exec.next() && exec.getBoolean("listme");
364 public String getContactInformation() {
365 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT contactinfo FROM users WHERE id=?")) {
366 get.setInt(1, getId());
368 GigiResultSet exec = get.executeQuery();
370 return exec.getString("contactinfo");
374 public void setDirectoryListing(boolean on) {
375 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET listme = ? WHERE id = ?")) {
376 update.setBoolean(1, on);
377 update.setInt(2, getId());
378 update.executeUpdate();
382 public void setContactInformation(String contactInfo) {
383 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET contactinfo = ? WHERE id = ?")) {
384 update.setString(1, contactInfo);
385 update.setInt(2, getId());
386 update.executeUpdate();
390 public boolean isInGroup(Group g) {
391 return groups.contains(g);
394 public Set<Group> getGroups() {
395 return Collections.unmodifiableSet(groups);
398 public void grantGroup(User granter, Group toGrant) {
400 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
401 ps.setInt(1, getId());
402 ps.setString(2, toGrant.getDatabaseName());
403 ps.setInt(3, granter.getId());
408 public void revokeGroup(User revoker, Group toRevoke) {
409 groups.remove(toRevoke);
410 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
411 ps.setInt(1, revoker.getId());
412 ps.setString(2, toRevoke.getDatabaseName());
413 ps.setInt(3, getId());
418 public List<Organisation> getOrganisations() {
419 return getOrganisations(false);
422 public List<Organisation> getOrganisations(boolean isAdmin) {
423 List<Organisation> orgas = new ArrayList<>();
424 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
425 query.setInt(1, getId());
426 try (GigiResultSet res = query.executeQuery()) {
428 orgas.add(Organisation.getById(res.getInt(1)));
436 public static synchronized User getById(int id) {
437 CertificateOwner co = CertificateOwner.getById(id);
438 if (co instanceof User) {
445 public static User getByEmail(String mail) {
446 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
447 ps.setString(1, mail);
448 GigiResultSet rs = ps.executeQuery();
453 return User.getById(rs.getInt(1));
457 public static User[] findByEmail(String mail) {
458 LinkedList<User> results = new LinkedList<User>();
459 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")) {
460 ps.setString(1, mail);
461 GigiResultSet rs = ps.executeQuery();
463 results.add(User.getById(rs.getInt(1)));
465 return results.toArray(new User[results.size()]);
469 public EmailAddress[] getEmails() {
470 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
471 ps.setInt(1, getId());
473 GigiResultSet rs = ps.executeQuery();
474 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
477 data.add(EmailAddress.getById(rs.getInt(1)));
480 return data.toArray(new EmailAddress[0]);
485 public boolean isValidEmail(String email) {
486 for (EmailAddress em : getEmails()) {
487 if (em.getAddress().equals(email)) {
488 return em.isVerified();
495 public String[] getTrainings() {
496 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `pass_date`, `type_text` FROM `cats_passed` LEFT JOIN `cats_type` ON `cats_type`.`id`=`cats_passed`.`variant_id` WHERE `user_id`=? ORDER BY `pass_date` ASC")) {
497 prep.setInt(1, getId());
498 GigiResultSet res = prep.executeQuery();
499 List<String> entries = new LinkedList<String>();
503 entries.add(DateSelector.getDateFormat().format(res.getTimestamp(1)) + " (" + res.getString(2) + ")");
506 return entries.toArray(new String[0]);
511 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
512 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
513 ps.setInt(1, getId());
514 ps.setInt(2, getId());
515 ps.setString(3, token);
516 ps.setString(4, PasswordHash.hash(privateToken));
518 return ps.lastInsertId();
522 public static User getResetWithToken(int id, String token) {
523 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL")) {
525 ps.setString(2, token);
526 GigiResultSet res = ps.executeQuery();
530 return User.getById(res.getInt(1));
534 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
535 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
537 ps.setInt(2, getId());
538 GigiResultSet rs = ps.executeQuery();
540 throw new GigiApiException("Token not found... very bad.");
542 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
543 throw new GigiApiException("Private token does not match.");
545 setPassword(newPassword);
547 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
553 private Assurance assuranceByRes(GigiResultSet res) {
554 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"));