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 protected User(GigiResultSet rs) {
45 super(rs.getInt("id"));
49 private void updateName(GigiResultSet rs) {
50 name = new Name(rs.getString("fname"), rs.getString("lname"), rs.getString("mname"), rs.getString("suffix"));
51 dob = new DayDate(rs.getDate("dob"));
52 email = rs.getString("email");
54 String localeStr = rs.getString("language");
55 if (localeStr == null || localeStr.equals("")) {
56 locale = Locale.getDefault();
58 locale = Language.getLocaleFromString(localeStr);
61 try (GigiPreparedStatement psg = new GigiPreparedStatement("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL")) {
62 psg.setInt(1, rs.getInt("id"));
64 try (GigiResultSet rs2 = psg.executeQuery()) {
66 groups.add(Group.getByString(rs2.getString(1)));
72 public User(String email, String password, Name name, DayDate dob, Locale locale) throws GigiApiException {
77 try (GigiPreparedStatement query = new GigiPreparedStatement("INSERT INTO `users` SET `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `language`=?, id=?")) {
78 query.setString(1, email);
79 query.setString(2, PasswordHash.hash(password));
80 query.setString(3, name.getFname());
81 query.setString(4, name.getMname());
82 query.setString(5, name.getLname());
83 query.setString(6, name.getSuffix());
84 query.setDate(7, dob.toSQLDate());
85 query.setString(8, locale.toString());
86 query.setInt(9, getId());
89 new EmailAddress(this, email, locale);
92 public Name getName() {
96 public DayDate getDoB() {
100 public void setDoB(DayDate dob) {
104 public String getEmail() {
108 public void changePassword(String oldPass, String newPass) throws GigiApiException {
109 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `password` FROM `users` WHERE `id`=?")) {
110 ps.setInt(1, getId());
111 try (GigiResultSet rs = ps.executeQuery()) {
113 throw new GigiApiException("User not found... very bad.");
115 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
116 throw new GigiApiException("Old password does not match.");
120 setPassword(newPass);
123 private void setPassword(String newPass) throws GigiApiException {
124 PasswordStrengthChecker.assertStrongPassword(newPass, getName(), getEmail());
125 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET `password`=? WHERE id=?")) {
126 ps.setString(1, PasswordHash.hash(newPass));
127 ps.setInt(2, getId());
132 public void setName(Name name) {
136 public boolean canAssure() {
137 if ( !CalendarUtil.isOfAge(dob, 14)) { // PoJAM
140 if (getAssurancePoints() < 100) {
144 return hasPassedCATS();
148 public boolean hasPassedCATS() {
149 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?")) {
150 query.setInt(1, getId());
151 query.setInt(2, CATS.ASSURER_CHALLANGE_ID);
152 try (GigiResultSet rs = query.executeQuery()) {
162 public int getAssurancePoints() {
163 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT sum(points) FROM `notary` where `to`=? AND `deleted` is NULL AND (`expire` IS NULL OR `expire` > CURRENT_TIMESTAMP)")) {
164 query.setInt(1, getId());
166 GigiResultSet rs = query.executeQuery();
170 points = rs.getInt(1);
177 public int getExperiencePoints() {
178 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT count(*) FROM `notary` where `from`=? AND `deleted` is NULL")) {
179 query.setInt(1, getId());
181 GigiResultSet rs = query.executeQuery();
185 points = rs.getInt(1) * 2;
193 * Gets the maximum allowed points NOW. Note that an assurance needs to
194 * re-check PoJam as it has taken place in the past.
196 * @return the maximal points @
198 public int getMaxAssurePoints() {
199 if ( !CalendarUtil.isOfAge(dob, 18)) {
203 int exp = getExperiencePoints();
225 public boolean isValidName(String name) {
226 return getName().matches(name);
229 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
230 for (EmailAddress email : getEmails()) {
231 if (email.getAddress().equals(newMail.getAddress())) {
232 if ( !email.isVerified()) {
233 throw new GigiApiException("Email not verified.");
236 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE users SET email=? WHERE id=?")) {
237 ps.setString(1, newMail.getAddress());
238 ps.setInt(2, getId());
242 this.email = newMail.getAddress();
247 throw new GigiApiException("Given address not an address of the user.");
250 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
251 if (getEmail().equals(delMail.getAddress())) {
252 throw new GigiApiException("Can't delete user's default e-mail.");
255 for (EmailAddress email : getEmails()) {
256 if (email.getId() == delMail.getId()) {
257 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?")) {
258 ps.setInt(1, delMail.getId());
264 throw new GigiApiException("Email not one of user's email addresses.");
267 public synchronized Assurance[] getReceivedAssurances() {
268 if (receivedAssurances == null) {
269 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM `notary` WHERE `to`=? AND `deleted` IS NULL")) {
270 query.setInt(1, getId());
272 GigiResultSet res = query.executeQuery();
273 List<Assurance> assurances = new LinkedList<Assurance>();
276 assurances.add(assuranceByRes(res));
279 this.receivedAssurances = assurances.toArray(new Assurance[0]);
283 return receivedAssurances;
286 public synchronized Assurance[] getMadeAssurances() {
287 if (madeAssurances == null) {
288 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT * FROM notary WHERE `from`=? AND deleted is NULL")) {
289 query.setInt(1, getId());
291 try (GigiResultSet res = query.executeQuery()) {
292 List<Assurance> assurances = new LinkedList<Assurance>();
295 assurances.add(assuranceByRes(res));
298 this.madeAssurances = assurances.toArray(new Assurance[0]);
303 return madeAssurances;
306 public synchronized void invalidateMadeAssurances() {
307 madeAssurances = null;
310 public synchronized void invalidateReceivedAssurances() {
311 receivedAssurances = null;
314 public void updateUserData() throws GigiApiException {
315 synchronized (Notary.class) {
316 if (getReceivedAssurances().length != 0) {
317 throw new GigiApiException("No change after assurance allowed.");
323 protected void rawUpdateUserData() {
324 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?")) {
325 update.setString(1, name.getFname());
326 update.setString(2, name.getLname());
327 update.setString(3, name.getMname());
328 update.setString(4, name.getSuffix());
329 update.setDate(5, getDoB().toSQLDate());
330 update.setInt(6, getId());
331 update.executeUpdate();
335 public Locale getPreferredLocale() {
339 public void setPreferredLocale(Locale locale) {
340 this.locale = locale;
344 public boolean wantsDirectoryListing() {
345 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT listme FROM users WHERE id=?")) {
346 get.setInt(1, getId());
347 GigiResultSet exec = get.executeQuery();
348 return exec.next() && exec.getBoolean("listme");
352 public String getContactInformation() {
353 try (GigiPreparedStatement get = new GigiPreparedStatement("SELECT contactinfo FROM users WHERE id=?")) {
354 get.setInt(1, getId());
356 GigiResultSet exec = get.executeQuery();
358 return exec.getString("contactinfo");
362 public void setDirectoryListing(boolean on) {
363 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET listme = ? WHERE id = ?")) {
364 update.setBoolean(1, on);
365 update.setInt(2, getId());
366 update.executeUpdate();
370 public void setContactInformation(String contactInfo) {
371 try (GigiPreparedStatement update = new GigiPreparedStatement("UPDATE users SET contactinfo = ? WHERE id = ?")) {
372 update.setString(1, contactInfo);
373 update.setInt(2, getId());
374 update.executeUpdate();
378 public boolean isInGroup(Group g) {
379 return groups.contains(g);
382 public Set<Group> getGroups() {
383 return Collections.unmodifiableSet(groups);
386 public void grantGroup(User granter, Group toGrant) {
388 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?")) {
389 ps.setInt(1, getId());
390 ps.setString(2, toGrant.getDatabaseName());
391 ps.setInt(3, granter.getId());
396 public void revokeGroup(User revoker, Group toRevoke) {
397 groups.remove(toRevoke);
398 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?")) {
399 ps.setInt(1, revoker.getId());
400 ps.setString(2, toRevoke.getDatabaseName());
401 ps.setInt(3, getId());
406 public List<Organisation> getOrganisations() {
407 return getOrganisations(false);
410 public List<Organisation> getOrganisations(boolean isAdmin) {
411 List<Organisation> orgas = new ArrayList<>();
412 try (GigiPreparedStatement query = new GigiPreparedStatement("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL" + (isAdmin ? " AND master='y'" : ""))) {
413 query.setInt(1, getId());
414 try (GigiResultSet res = query.executeQuery()) {
416 orgas.add(Organisation.getById(res.getInt(1)));
424 public static synchronized User getById(int id) {
425 CertificateOwner co = CertificateOwner.getById(id);
426 if (co instanceof User) {
433 public static User getByEmail(String mail) {
434 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL")) {
435 ps.setString(1, mail);
436 GigiResultSet rs = ps.executeQuery();
441 return User.getById(rs.getInt(1));
445 public static User[] findByEmail(String mail) {
446 LinkedList<User> results = new LinkedList<User>();
447 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")) {
448 ps.setString(1, mail);
449 GigiResultSet rs = ps.executeQuery();
451 results.add(User.getById(rs.getInt(1)));
453 return results.toArray(new User[results.size()]);
457 public EmailAddress[] getEmails() {
458 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL")) {
459 ps.setInt(1, getId());
461 GigiResultSet rs = ps.executeQuery();
462 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
465 data.add(EmailAddress.getById(rs.getInt(1)));
468 return data.toArray(new EmailAddress[0]);
473 public boolean isValidEmail(String email) {
474 for (EmailAddress em : getEmails()) {
475 if (em.getAddress().equals(email)) {
476 return em.isVerified();
483 public String[] getTrainings() {
484 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")) {
485 prep.setInt(1, getId());
486 GigiResultSet res = prep.executeQuery();
487 List<String> entries = new LinkedList<String>();
491 entries.add(DateSelector.getDateFormat().format(res.getTimestamp(1)) + " (" + res.getString(2) + ")");
494 return entries.toArray(new String[0]);
499 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
500 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?")) {
501 ps.setInt(1, getId());
502 ps.setInt(2, getId());
503 ps.setString(3, token);
504 ps.setString(4, PasswordHash.hash(privateToken));
506 return ps.lastInsertId();
510 public static User getResetWithToken(int id, String token) {
511 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL")) {
513 ps.setString(2, token);
514 GigiResultSet res = ps.executeQuery();
518 return User.getById(res.getInt(1));
522 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
523 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL")) {
525 ps.setInt(2, getId());
526 GigiResultSet rs = ps.executeQuery();
528 throw new GigiApiException("Token not found... very bad.");
530 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
531 throw new GigiApiException("Private token does not match.");
533 setPassword(newPassword);
535 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?")) {
541 private Assurance assuranceByRes(GigiResultSet res) {
542 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"));