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 protected User(GigiResultSet rs) {
49 super(rs.getInt("id"));
53 private void updateName(GigiResultSet rs) {
54 name = new Name(rs.getString("fname"), rs.getString("lname"), rs.getString("mname"), rs.getString("suffix"));
55 dob = new DayDate(rs.getDate("dob"));
56 email = rs.getString("email");
58 String localeStr = rs.getString("language");
59 if (localeStr == null || localeStr.equals("")) {
60 locale = Locale.getDefault();
62 locale = Language.getLocaleFromString(localeStr);
65 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
66 psg.setInt(1, rs.getInt("id"));
68 try (GigiResultSet rs2 = psg.executeQuery()) {
70 groups.add(Group.getByString(rs2.getString(1)));
76 public User(String email, String password, Name name, DayDate dob, Locale locale) throws GigiApiException {
81 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `language`=?, id=?")) {
82 query.setString(1, email);
83 query.setString(2, PasswordHash.hash(password));
84 query.setString(3, name.getFname());
85 query.setString(4, name.getMname());
86 query.setString(5, name.getLname());
87 query.setString(6, name.getSuffix());
88 query.setDate(7, dob.toSQLDate());
89 query.setString(8, locale.toString());
90 query.setInt(9, getId());
93 new EmailAddress(this, email, locale);
96 public Name getName() {
100 public DayDate getDoB() {
104 public void setDoB(DayDate dob) {
108 public String getEmail() {
112 public void changePassword(String oldPass, String newPass) throws GigiApiException {
113 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
114 ps.setInt(1, getId());
115 try (GigiResultSet rs = ps.executeQuery()) {
117 throw new GigiApiException("User not found... very bad.");
119 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
120 throw new GigiApiException("Old password does not match.");
124 setPassword(newPass);
127 private void setPassword(String newPass) throws GigiApiException {
128 PasswordStrengthChecker.assertStrongPassword(newPass, getName(), getEmail());
129 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
130 ps.setString(1, PasswordHash.hash(newPass));
131 ps.setInt(2, getId());
136 public void setName(Name name) {
140 public boolean canAssure() {
141 if ( !CalendarUtil.isOfAge(dob, POJAM_AGE)) { // PoJAM
144 if (getAssurancePoints() < 100) {
148 return hasPassedCATS();
152 public boolean hasPassedCATS() {
153 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
154 query.setInt(1, getId());
155 query.setInt(2, CATS.ASSURER_CHALLANGE_ID);
156 try (GigiResultSet rs = query.executeQuery()) {
166 public int getAssurancePoints() {
167 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT sum(points) FROM `notary` where `to`=? AND `deleted` is NULL AND (`expire` IS NULL OR `expire` > CURRENT_TIMESTAMP)")) {
168 query.setInt(1, getId());
170 GigiResultSet rs = query.executeQuery();
174 points = rs.getInt(1);
181 public int getExperiencePoints() {
182 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT count(*) FROM `notary` where `from`=? AND `deleted` is NULL")) {
183 query.setInt(1, getId());
185 GigiResultSet rs = query.executeQuery();
189 points = rs.getInt(1) * 2;
197 * Gets the maximum allowed points NOW. Note that an assurance needs to
198 * re-check PoJam as it has taken place in the past.
200 * @return the maximal points @
202 public int getMaxAssurePoints() {
203 if ( !CalendarUtil.isOfAge(dob, ADULT_AGE)) {
207 int exp = getExperiencePoints();
229 public boolean isValidName(String name) {
230 return getName().matches(name);
233 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
234 for (EmailAddress email : getEmails()) {
235 if (email.getAddress().equals(newMail.getAddress())) {
236 if ( !email.isVerified()) {
237 throw new GigiApiException("Email not verified.");
240 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
241 ps.setString(1, newMail.getAddress());
242 ps.setInt(2, getId());
246 this.email = newMail.getAddress();
251 throw new GigiApiException("Given address not an address of the user.");
254 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
255 if (getEmail().equals(delMail.getAddress())) {
256 throw new GigiApiException("Can't delete user's default e-mail.");
259 for (EmailAddress email : getEmails()) {
260 if (email.getId() == delMail.getId()) {
261 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
262 ps.setInt(1, delMail.getId());
268 throw new GigiApiException("Email not one of user's email addresses.");
271 public synchronized Assurance[] getReceivedAssurances() {
272 if (receivedAssurances == null) {
273 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` WHERE `to`=? AND `deleted` IS NULL")) {
274 query.setInt(1, getId());
276 GigiResultSet res = query.executeQuery();
277 List<Assurance> assurances = new LinkedList<Assurance>();
280 assurances.add(assuranceByRes(res));
283 this.receivedAssurances = assurances.toArray(new Assurance[0]);
287 return receivedAssurances;
290 public synchronized Assurance[] getMadeAssurances() {
291 if (madeAssurances == null) {
292 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL")) {
293 query.setInt(1, getId());
295 try (GigiResultSet res = query.executeQuery()) {
296 List<Assurance> assurances = new LinkedList<Assurance>();
299 assurances.add(assuranceByRes(res));
302 this.madeAssurances = assurances.toArray(new Assurance[0]);
307 return madeAssurances;
310 public synchronized void invalidateMadeAssurances() {
311 madeAssurances = null;
314 public synchronized void invalidateReceivedAssurances() {
315 receivedAssurances = null;
318 public void updateUserData() throws GigiApiException {
319 synchronized (Notary.class) {
320 if (getReceivedAssurances().length != 0) {
321 throw new GigiApiException("No change after assurance allowed.");
327 protected void rawUpdateUserData() {
328 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?")) {
329 update.setString(1, name.getFname());
330 update.setString(2, name.getLname());
331 update.setString(3, name.getMname());
332 update.setString(4, name.getSuffix());
333 update.setDate(5, getDoB().toSQLDate());
334 update.setInt(6, getId());
335 update.executeUpdate();
339 public Locale getPreferredLocale() {
343 public void setPreferredLocale(Locale locale) {
344 this.locale = locale;
348 public boolean wantsDirectoryListing() {
349 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT listme FROM users WHERE id=?")) {
350 get.setInt(1, getId());
351 GigiResultSet exec = get.executeQuery();
352 return exec.next() && exec.getBoolean("listme");
356 public String getContactInformation() {
357 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT contactinfo FROM users WHERE id=?")) {
358 get.setInt(1, getId());
360 GigiResultSet exec = get.executeQuery();
362 return exec.getString("contactinfo");
366 public void setDirectoryListing(boolean on) {
367 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET listme = ? WHERE id = ?")) {
368 update.setBoolean(1, on);
369 update.setInt(2, getId());
370 update.executeUpdate();
374 public void setContactInformation(String contactInfo) {
375 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET contactinfo = ? WHERE id = ?")) {
376 update.setString(1, contactInfo);
377 update.setInt(2, getId());
378 update.executeUpdate();
382 public boolean isInGroup(Group g) {
383 return groups.contains(g);
386 public Set<Group> getGroups() {
387 return Collections.unmodifiableSet(groups);
390 public void grantGroup(User granter, Group toGrant) {
392 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
393 ps.setInt(1, getId());
394 ps.setString(2, toGrant.getDatabaseName());
395 ps.setInt(3, granter.getId());
400 public void revokeGroup(User revoker, Group toRevoke) {
401 groups.remove(toRevoke);
402 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
403 ps.setInt(1, revoker.getId());
404 ps.setString(2, toRevoke.getDatabaseName());
405 ps.setInt(3, getId());
410 public List<Organisation> getOrganisations() {
411 return getOrganisations(false);
414 public List<Organisation> getOrganisations(boolean isAdmin) {
415 List<Organisation> orgas = new ArrayList<>();
416 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
417 query.setInt(1, getId());
418 try (GigiResultSet res = query.executeQuery()) {
420 orgas.add(Organisation.getById(res.getInt(1)));
428 public static synchronized User getById(int id) {
429 CertificateOwner co = CertificateOwner.getById(id);
430 if (co instanceof User) {
437 public static User getByEmail(String mail) {
438 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
439 ps.setString(1, mail);
440 GigiResultSet rs = ps.executeQuery();
445 return User.getById(rs.getInt(1));
449 public static User[] findByEmail(String mail) {
450 LinkedList<User> results = new LinkedList<User>();
451 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")) {
452 ps.setString(1, mail);
453 GigiResultSet rs = ps.executeQuery();
455 results.add(User.getById(rs.getInt(1)));
457 return results.toArray(new User[results.size()]);
461 public EmailAddress[] getEmails() {
462 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
463 ps.setInt(1, getId());
465 GigiResultSet rs = ps.executeQuery();
466 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
469 data.add(EmailAddress.getById(rs.getInt(1)));
472 return data.toArray(new EmailAddress[0]);
477 public boolean isValidEmail(String email) {
478 for (EmailAddress em : getEmails()) {
479 if (em.getAddress().equals(email)) {
480 return em.isVerified();
487 public String[] getTrainings() {
488 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")) {
489 prep.setInt(1, getId());
490 GigiResultSet res = prep.executeQuery();
491 List<String> entries = new LinkedList<String>();
495 entries.add(DateSelector.getDateFormat().format(res.getTimestamp(1)) + " (" + res.getString(2) + ")");
498 return entries.toArray(new String[0]);
503 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
504 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
505 ps.setInt(1, getId());
506 ps.setInt(2, getId());
507 ps.setString(3, token);
508 ps.setString(4, PasswordHash.hash(privateToken));
510 return ps.lastInsertId();
514 public static User getResetWithToken(int id, String token) {
515 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL")) {
517 ps.setString(2, token);
518 GigiResultSet res = ps.executeQuery();
522 return User.getById(res.getInt(1));
526 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
527 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
529 ps.setInt(2, getId());
530 GigiResultSet rs = ps.executeQuery();
532 throw new GigiApiException("Token not found... very bad.");
534 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
535 throw new GigiApiException("Private token does not match.");
537 setPassword(newPassword);
539 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
545 private Assurance assuranceByRes(GigiResultSet res) {
546 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"));