1 package org.cacert.gigi.dbObjects;
3 import java.util.ArrayList;
4 import java.util.Calendar;
5 import java.util.Collections;
6 import java.util.HashSet;
7 import java.util.LinkedList;
9 import java.util.Locale;
12 import org.cacert.gigi.GigiApiException;
13 import org.cacert.gigi.database.GigiPreparedStatement;
14 import org.cacert.gigi.database.GigiResultSet;
15 import org.cacert.gigi.localisation.Language;
16 import org.cacert.gigi.output.DateSelector;
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 protected User(GigiResultSet rs) {
43 super(rs.getInt("id"));
47 private void updateName(GigiResultSet rs) {
48 name = new Name(rs.getString("fname"), rs.getString("lname"), rs.getString("mname"), rs.getString("suffix"));
49 dob = new DayDate(rs.getDate("dob"));
50 email = rs.getString("email");
52 String localeStr = rs.getString("language");
53 if (localeStr == null || localeStr.equals("")) {
54 locale = Locale.getDefault();
56 locale = Language.getLocaleFromString(localeStr);
59 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
60 psg.setInt(1, rs.getInt("id"));
62 try (GigiResultSet rs2 = psg.executeQuery()) {
64 groups.add(Group.getByString(rs2.getString(1)));
70 public User(String email, String password, Name name, DayDate dob, Locale locale) throws GigiApiException {
75 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `language`=?, id=?")) {
76 query.setString(1, email);
77 query.setString(2, PasswordHash.hash(password));
78 query.setString(3, name.getFname());
79 query.setString(4, name.getMname());
80 query.setString(5, name.getLname());
81 query.setString(6, name.getSuffix());
82 query.setDate(7, dob.toSQLDate());
83 query.setString(8, locale.toString());
84 query.setInt(9, getId());
87 new EmailAddress(this, email, locale);
90 public Name getName() {
94 public DayDate getDoB() {
98 public void setDoB(DayDate dob) {
102 public String getEmail() {
106 public void changePassword(String oldPass, String newPass) throws GigiApiException {
107 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
108 ps.setInt(1, getId());
109 try (GigiResultSet rs = ps.executeQuery()) {
111 throw new GigiApiException("User not found... very bad.");
113 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
114 throw new GigiApiException("Old password does not match.");
118 setPassword(newPass);
121 private void setPassword(String newPass) throws GigiApiException {
122 PasswordStrengthChecker.assertStrongPassword(newPass, getName(), getEmail());
123 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
124 ps.setString(1, PasswordHash.hash(newPass));
125 ps.setInt(2, getId());
130 public void setName(Name name) {
134 public boolean canAssure() {
135 if ( !isOfAge(14)) { // PoJAM
138 if (getAssurancePoints() < 100) {
142 return hasPassedCATS();
146 public boolean hasPassedCATS() {
147 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
148 query.setInt(1, getId());
149 query.setInt(2, CATS.ASSURER_CHALLANGE_ID);
150 try (GigiResultSet rs = query.executeQuery()) {
160 public int getAssurancePoints() {
161 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT sum(points) FROM `notary` where `to`=? AND `deleted` is NULL AND (`expire` IS NULL OR `expire` > CURRENT_TIMESTAMP)")) {
162 query.setInt(1, getId());
164 GigiResultSet rs = query.executeQuery();
168 points = rs.getInt(1);
175 public int getExperiencePoints() {
176 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT count(*) FROM `notary` where `from`=? AND `deleted` is NULL")) {
177 query.setInt(1, getId());
179 GigiResultSet rs = query.executeQuery();
183 points = rs.getInt(1) * 2;
191 * Gets the maximum allowed points NOW. Note that an assurance needs to
192 * re-check PoJam as it has taken place in the past.
194 * @return the maximal points @
196 public int getMaxAssurePoints() {
201 int exp = getExperiencePoints();
223 public boolean isOfAge(int desiredAge) {
224 Calendar c = Calendar.getInstance();
225 c.setTimeInMillis(dob.getTime());
226 int year = c.get(Calendar.YEAR);
227 int month = c.get(Calendar.MONTH);
228 int day = c.get(Calendar.DAY_OF_MONTH);
229 c.set(year, month, day);
230 c.add(Calendar.YEAR, desiredAge);
231 return System.currentTimeMillis() >= c.getTime().getTime();
234 public boolean isValidName(String name) {
235 return getName().matches(name);
238 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
239 for (EmailAddress email : getEmails()) {
240 if (email.getAddress().equals(newMail.getAddress())) {
241 if ( !email.isVerified()) {
242 throw new GigiApiException("Email not verified.");
245 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
246 ps.setString(1, newMail.getAddress());
247 ps.setInt(2, getId());
251 this.email = newMail.getAddress();
256 throw new GigiApiException("Given address not an address of the user.");
259 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
260 if (getEmail().equals(delMail.getAddress())) {
261 throw new GigiApiException("Can't delete user's default e-mail.");
264 for (EmailAddress email : getEmails()) {
265 if (email.getId() == delMail.getId()) {
266 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
267 ps.setInt(1, delMail.getId());
273 throw new GigiApiException("Email not one of user's email addresses.");
276 public synchronized Assurance[] getReceivedAssurances() {
277 if (receivedAssurances == null) {
278 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` WHERE `to`=? AND `deleted` IS NULL")) {
279 query.setInt(1, getId());
281 GigiResultSet res = query.executeQuery();
282 List<Assurance> assurances = new LinkedList<Assurance>();
285 assurances.add(assuranceByRes(res));
288 this.receivedAssurances = assurances.toArray(new Assurance[0]);
292 return receivedAssurances;
295 public synchronized Assurance[] getMadeAssurances() {
296 if (madeAssurances == null) {
297 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL")) {
298 query.setInt(1, getId());
300 try (GigiResultSet res = query.executeQuery()) {
301 List<Assurance> assurances = new LinkedList<Assurance>();
304 assurances.add(assuranceByRes(res));
307 this.madeAssurances = assurances.toArray(new Assurance[0]);
312 return madeAssurances;
315 public synchronized void invalidateMadeAssurances() {
316 madeAssurances = null;
319 public synchronized void invalidateReceivedAssurances() {
320 receivedAssurances = null;
323 public void updateUserData() throws GigiApiException {
324 synchronized (Notary.class) {
325 if (getReceivedAssurances().length != 0) {
326 throw new GigiApiException("No change after assurance allowed.");
332 protected void rawUpdateUserData() {
333 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?")) {
334 update.setString(1, name.getFname());
335 update.setString(2, name.getLname());
336 update.setString(3, name.getMname());
337 update.setString(4, name.getSuffix());
338 update.setDate(5, getDoB().toSQLDate());
339 update.setInt(6, getId());
340 update.executeUpdate();
344 public Locale getPreferredLocale() {
348 public void setPreferredLocale(Locale locale) {
349 this.locale = locale;
353 public boolean wantsDirectoryListing() {
354 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT listme FROM users WHERE id=?")) {
355 get.setInt(1, getId());
356 GigiResultSet exec = get.executeQuery();
357 return exec.next() && exec.getBoolean("listme");
361 public String getContactInformation() {
362 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT contactinfo FROM users WHERE id=?")) {
363 get.setInt(1, getId());
365 GigiResultSet exec = get.executeQuery();
367 return exec.getString("contactinfo");
371 public void setDirectoryListing(boolean on) {
372 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET listme = ? WHERE id = ?")) {
373 update.setBoolean(1, on);
374 update.setInt(2, getId());
375 update.executeUpdate();
379 public void setContactInformation(String contactInfo) {
380 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET contactinfo = ? WHERE id = ?")) {
381 update.setString(1, contactInfo);
382 update.setInt(2, getId());
383 update.executeUpdate();
387 public boolean isInGroup(Group g) {
388 return groups.contains(g);
391 public Set<Group> getGroups() {
392 return Collections.unmodifiableSet(groups);
395 public void grantGroup(User granter, Group toGrant) {
397 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
398 ps.setInt(1, getId());
399 ps.setString(2, toGrant.getDatabaseName());
400 ps.setInt(3, granter.getId());
405 public void revokeGroup(User revoker, Group toRevoke) {
406 groups.remove(toRevoke);
407 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
408 ps.setInt(1, revoker.getId());
409 ps.setString(2, toRevoke.getDatabaseName());
410 ps.setInt(3, getId());
415 public List<Organisation> getOrganisations() {
416 return getOrganisations(false);
419 public List<Organisation> getOrganisations(boolean isAdmin) {
420 List<Organisation> orgas = new ArrayList<>();
421 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
422 query.setInt(1, getId());
423 try (GigiResultSet res = query.executeQuery()) {
425 orgas.add(Organisation.getById(res.getInt(1)));
433 public static synchronized User getById(int id) {
434 CertificateOwner co = CertificateOwner.getById(id);
435 if (co instanceof User) {
442 public static User getByEmail(String mail) {
443 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
444 ps.setString(1, mail);
445 GigiResultSet rs = ps.executeQuery();
450 return User.getById(rs.getInt(1));
454 public static User[] findByEmail(String mail) {
455 LinkedList<User> results = new LinkedList<User>();
456 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")) {
457 ps.setString(1, mail);
458 GigiResultSet rs = ps.executeQuery();
460 results.add(User.getById(rs.getInt(1)));
462 return results.toArray(new User[results.size()]);
466 public EmailAddress[] getEmails() {
467 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
468 ps.setInt(1, getId());
470 GigiResultSet rs = ps.executeQuery();
471 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
474 data.add(EmailAddress.getById(rs.getInt(1)));
477 return data.toArray(new EmailAddress[0]);
482 public boolean isValidEmail(String email) {
483 for (EmailAddress em : getEmails()) {
484 if (em.getAddress().equals(email)) {
485 return em.isVerified();
492 public String[] getTrainings() {
493 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")) {
494 prep.setInt(1, getId());
495 GigiResultSet res = prep.executeQuery();
496 List<String> entries = new LinkedList<String>();
500 entries.add(DateSelector.getDateFormat().format(res.getTimestamp(1)) + " (" + res.getString(2) + ")");
503 return entries.toArray(new String[0]);
508 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
509 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
510 ps.setInt(1, getId());
511 ps.setInt(2, getId());
512 ps.setString(3, token);
513 ps.setString(4, PasswordHash.hash(privateToken));
515 return ps.lastInsertId();
519 public static User getResetWithToken(int id, String token) {
520 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL")) {
522 ps.setString(2, token);
523 GigiResultSet res = ps.executeQuery();
527 return User.getById(res.getInt(1));
531 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
532 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
534 ps.setInt(2, getId());
535 GigiResultSet rs = ps.executeQuery();
537 throw new GigiApiException("Token not found... very bad.");
539 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
540 throw new GigiApiException("Private token does not match.");
542 setPassword(newPassword);
544 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
550 private Assurance assuranceByRes(GigiResultSet res) {
551 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"));