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 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 ( !CalendarUtil.isOfAge(dob, 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() {
197 if ( !CalendarUtil.isOfAge(dob, 18)) {
201 int exp = getExperiencePoints();
223 public boolean isValidName(String name) {
224 return getName().matches(name);
227 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
228 for (EmailAddress email : getEmails()) {
229 if (email.getAddress().equals(newMail.getAddress())) {
230 if ( !email.isVerified()) {
231 throw new GigiApiException("Email not verified.");
234 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
235 ps.setString(1, newMail.getAddress());
236 ps.setInt(2, getId());
240 this.email = newMail.getAddress();
245 throw new GigiApiException("Given address not an address of the user.");
248 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
249 if (getEmail().equals(delMail.getAddress())) {
250 throw new GigiApiException("Can't delete user's default e-mail.");
253 for (EmailAddress email : getEmails()) {
254 if (email.getId() == delMail.getId()) {
255 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
256 ps.setInt(1, delMail.getId());
262 throw new GigiApiException("Email not one of user's email addresses.");
265 public synchronized Assurance[] getReceivedAssurances() {
266 if (receivedAssurances == null) {
267 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` WHERE `to`=? AND `deleted` IS NULL")) {
268 query.setInt(1, getId());
270 GigiResultSet res = query.executeQuery();
271 List<Assurance> assurances = new LinkedList<Assurance>();
274 assurances.add(assuranceByRes(res));
277 this.receivedAssurances = assurances.toArray(new Assurance[0]);
281 return receivedAssurances;
284 public synchronized Assurance[] getMadeAssurances() {
285 if (madeAssurances == null) {
286 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL")) {
287 query.setInt(1, getId());
289 try (GigiResultSet res = query.executeQuery()) {
290 List<Assurance> assurances = new LinkedList<Assurance>();
293 assurances.add(assuranceByRes(res));
296 this.madeAssurances = assurances.toArray(new Assurance[0]);
301 return madeAssurances;
304 public synchronized void invalidateMadeAssurances() {
305 madeAssurances = null;
308 public synchronized void invalidateReceivedAssurances() {
309 receivedAssurances = null;
312 public void updateUserData() throws GigiApiException {
313 synchronized (Notary.class) {
314 if (getReceivedAssurances().length != 0) {
315 throw new GigiApiException("No change after assurance allowed.");
321 protected void rawUpdateUserData() {
322 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?")) {
323 update.setString(1, name.getFname());
324 update.setString(2, name.getLname());
325 update.setString(3, name.getMname());
326 update.setString(4, name.getSuffix());
327 update.setDate(5, getDoB().toSQLDate());
328 update.setInt(6, getId());
329 update.executeUpdate();
333 public Locale getPreferredLocale() {
337 public void setPreferredLocale(Locale locale) {
338 this.locale = locale;
342 public boolean wantsDirectoryListing() {
343 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT listme FROM users WHERE id=?")) {
344 get.setInt(1, getId());
345 GigiResultSet exec = get.executeQuery();
346 return exec.next() && exec.getBoolean("listme");
350 public String getContactInformation() {
351 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT contactinfo FROM users WHERE id=?")) {
352 get.setInt(1, getId());
354 GigiResultSet exec = get.executeQuery();
356 return exec.getString("contactinfo");
360 public void setDirectoryListing(boolean on) {
361 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET listme = ? WHERE id = ?")) {
362 update.setBoolean(1, on);
363 update.setInt(2, getId());
364 update.executeUpdate();
368 public void setContactInformation(String contactInfo) {
369 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET contactinfo = ? WHERE id = ?")) {
370 update.setString(1, contactInfo);
371 update.setInt(2, getId());
372 update.executeUpdate();
376 public boolean isInGroup(Group g) {
377 return groups.contains(g);
380 public Set<Group> getGroups() {
381 return Collections.unmodifiableSet(groups);
384 public void grantGroup(User granter, Group toGrant) {
386 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
387 ps.setInt(1, getId());
388 ps.setString(2, toGrant.getDatabaseName());
389 ps.setInt(3, granter.getId());
394 public void revokeGroup(User revoker, Group toRevoke) {
395 groups.remove(toRevoke);
396 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
397 ps.setInt(1, revoker.getId());
398 ps.setString(2, toRevoke.getDatabaseName());
399 ps.setInt(3, getId());
404 public List<Organisation> getOrganisations() {
405 return getOrganisations(false);
408 public List<Organisation> getOrganisations(boolean isAdmin) {
409 List<Organisation> orgas = new ArrayList<>();
410 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
411 query.setInt(1, getId());
412 try (GigiResultSet res = query.executeQuery()) {
414 orgas.add(Organisation.getById(res.getInt(1)));
422 public static synchronized User getById(int id) {
423 CertificateOwner co = CertificateOwner.getById(id);
424 if (co instanceof User) {
431 public static User getByEmail(String mail) {
432 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
433 ps.setString(1, mail);
434 GigiResultSet rs = ps.executeQuery();
439 return User.getById(rs.getInt(1));
443 public static User[] findByEmail(String mail) {
444 LinkedList<User> results = new LinkedList<User>();
445 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")) {
446 ps.setString(1, mail);
447 GigiResultSet rs = ps.executeQuery();
449 results.add(User.getById(rs.getInt(1)));
451 return results.toArray(new User[results.size()]);
455 public EmailAddress[] getEmails() {
456 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
457 ps.setInt(1, getId());
459 GigiResultSet rs = ps.executeQuery();
460 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
463 data.add(EmailAddress.getById(rs.getInt(1)));
466 return data.toArray(new EmailAddress[0]);
471 public boolean isValidEmail(String email) {
472 for (EmailAddress em : getEmails()) {
473 if (em.getAddress().equals(email)) {
474 return em.isVerified();
481 public String[] getTrainings() {
482 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")) {
483 prep.setInt(1, getId());
484 GigiResultSet res = prep.executeQuery();
485 List<String> entries = new LinkedList<String>();
489 entries.add(DateSelector.getDateFormat().format(res.getTimestamp(1)) + " (" + res.getString(2) + ")");
492 return entries.toArray(new String[0]);
497 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
498 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
499 ps.setInt(1, getId());
500 ps.setInt(2, getId());
501 ps.setString(3, token);
502 ps.setString(4, PasswordHash.hash(privateToken));
504 return ps.lastInsertId();
508 public static User getResetWithToken(int id, String token) {
509 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL")) {
511 ps.setString(2, token);
512 GigiResultSet res = ps.executeQuery();
516 return User.getById(res.getInt(1));
520 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
521 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
523 ps.setInt(2, getId());
524 GigiResultSet rs = ps.executeQuery();
526 throw new GigiApiException("Token not found... very bad.");
528 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
529 throw new GigiApiException("Private token does not match.");
531 setPassword(newPassword);
533 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
539 private Assurance assuranceByRes(GigiResultSet res) {
540 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"));