1 package org.cacert.gigi.dbObjects;
4 import java.util.ArrayList;
5 import java.util.Calendar;
6 import java.util.Collections;
7 import java.util.HashSet;
8 import java.util.LinkedList;
10 import java.util.Locale;
13 import org.cacert.gigi.GigiApiException;
14 import org.cacert.gigi.database.DatabaseConnection;
15 import org.cacert.gigi.database.GigiPreparedStatement;
16 import org.cacert.gigi.database.GigiResultSet;
17 import org.cacert.gigi.localisation.Language;
18 import org.cacert.gigi.output.DateSelector;
19 import org.cacert.gigi.util.Notary;
20 import org.cacert.gigi.util.PasswordHash;
21 import org.cacert.gigi.util.PasswordStrengthChecker;
23 public class User extends CertificateOwner {
25 private Name name = new Name(null, null, null, null);
31 private Assurance[] receivedAssurances;
33 private Assurance[] madeAssurances;
35 private Locale locale;
37 private final Set<Group> groups = new HashSet<>();
39 protected User(GigiResultSet rs) {
40 super(rs.getInt("id"));
44 private void updateName(GigiResultSet rs) {
45 name = new Name(rs.getString("fname"), rs.getString("lname"), rs.getString("mname"), rs.getString("suffix"));
46 dob = rs.getDate("dob");
47 email = rs.getString("email");
49 String localeStr = rs.getString("language");
50 if (localeStr == null || localeStr.equals("")) {
51 locale = Locale.getDefault();
53 locale = Language.getLocaleFromString(localeStr);
56 GigiPreparedStatement psg = DatabaseConnection.getInstance().prepare("SELECT `permission` FROM `user_groups` WHERE `user`=? AND `deleted` is NULL");
57 psg.setInt(1, rs.getInt("id"));
59 try (GigiResultSet rs2 = psg.executeQuery()) {
61 groups.add(Group.getByString(rs2.getString(1)));
66 public User(String email, String password, Name name, Date dob, Locale locale) throws GigiApiException {
71 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("INSERT INTO `users` SET `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + "`suffix`=?, `dob`=?, `language`=?, id=?");
72 query.setString(1, email);
73 query.setString(2, PasswordHash.hash(password));
74 query.setString(3, name.getFname());
75 query.setString(4, name.getMname());
76 query.setString(5, name.getLname());
77 query.setString(6, name.getSuffix());
78 query.setDate(7, dob);
79 query.setString(8, locale.toString());
80 query.setInt(9, getId());
82 new EmailAddress(this, email, locale);
85 public Name getName() {
89 public Date getDoB() {
93 public void setDoB(Date dob) {
97 public String getEmail() {
101 public void changePassword(String oldPass, String newPass) throws GigiApiException {
102 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `password` FROM `users` WHERE `id`=?");
103 ps.setInt(1, getId());
104 try (GigiResultSet rs = ps.executeQuery()) {
106 throw new GigiApiException("User not found... very bad.");
108 if (PasswordHash.verifyHash(oldPass, rs.getString(1)) == null) {
109 throw new GigiApiException("Old password does not match.");
112 setPassword(newPass);
115 private void setPassword(String newPass) throws GigiApiException {
116 GigiPreparedStatement ps;
117 PasswordStrengthChecker.assertStrongPassword(newPass, getName(), getEmail());
118 ps = DatabaseConnection.getInstance().prepare("UPDATE users SET `password`=? WHERE id=?");
119 ps.setString(1, PasswordHash.hash(newPass));
120 ps.setInt(2, getId());
124 public void setName(Name name) {
128 public boolean canAssure() {
129 if ( !isOfAge(14)) { // PoJAM
132 if (getAssurancePoints() < 100) {
136 return hasPassedCATS();
140 public boolean hasPassedCATS() {
141 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?");
142 query.setInt(1, getId());
143 query.setInt(2, CATS.ASSURER_CHALLANGE_ID);
144 try (GigiResultSet rs = query.executeQuery()) {
153 public int getAssurancePoints() {
154 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT sum(points) FROM `notary` where `to`=? AND `deleted` is NULL");
155 query.setInt(1, getId());
157 try (GigiResultSet rs = query.executeQuery()) {
161 points = rs.getInt(1);
168 public int getExperiencePoints() {
169 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT count(*) FROM `notary` where `from`=? AND `deleted` is NULL");
170 query.setInt(1, getId());
172 try (GigiResultSet rs = query.executeQuery()) {
176 points = rs.getInt(1) * 2;
184 * Gets the maximum allowed points NOW. Note that an assurance needs to
185 * re-check PoJam as it has taken place in the past.
187 * @return the maximal points @
189 public int getMaxAssurePoints() {
194 int exp = getExperiencePoints();
216 public boolean isOfAge(int desiredAge) {
217 Calendar c = Calendar.getInstance();
219 int year = c.get(Calendar.YEAR);
220 int month = c.get(Calendar.MONTH);
221 int day = c.get(Calendar.DAY_OF_MONTH);
222 c.set(year, month, day);
223 c.add(Calendar.YEAR, desiredAge);
224 return System.currentTimeMillis() >= c.getTime().getTime();
227 public boolean isValidName(String name) {
228 return getName().matches(name);
231 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
232 for (EmailAddress email : getEmails()) {
233 if (email.getAddress().equals(newMail.getAddress())) {
234 if ( !email.isVerified()) {
235 throw new GigiApiException("Email not verified.");
238 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET email=? WHERE id=?");
239 ps.setString(1, newMail.getAddress());
240 ps.setInt(2, getId());
243 this.email = newMail.getAddress();
248 throw new GigiApiException("Given address not an address of the user.");
251 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
252 if (getEmail().equals(delMail.getAddress())) {
253 throw new GigiApiException("Can't delete user's default e-mail.");
256 for (EmailAddress email : getEmails()) {
257 if (email.getId() == delMail.getId()) {
258 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?");
259 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 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM `notary` WHERE `to`=? AND `deleted` IS NULL");
270 query.setInt(1, getId());
272 try (GigiResultSet res = query.executeQuery()) {
273 List<Assurance> assurances = new LinkedList<Assurance>();
276 assurances.add(new Assurance(res));
279 this.receivedAssurances = assurances.toArray(new Assurance[0]);
283 return receivedAssurances;
286 public synchronized Assurance[] getMadeAssurances() {
287 if (madeAssurances == null) {
288 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("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(new Assurance(res));
298 this.madeAssurances = assurances.toArray(new Assurance[0]);
302 return madeAssurances;
305 public synchronized void invalidateMadeAssurances() {
306 madeAssurances = null;
309 public synchronized void invalidateReceivedAssurances() {
310 receivedAssurances = null;
313 public void updateUserData() throws GigiApiException {
314 synchronized (Notary.class) {
315 if (getReceivedAssurances().length != 0) {
316 throw new GigiApiException("No change after assurance allowed.");
322 protected void rawUpdateUserData() {
323 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?");
324 update.setString(1, name.getFname());
325 update.setString(2, name.getLname());
326 update.setString(3, name.getMname());
327 update.setString(4, name.getSuffix());
328 update.setDate(5, getDoB());
329 update.setInt(6, getId());
330 update.executeUpdate();
333 public Locale getPreferredLocale() {
337 public void setPreferredLocale(Locale locale) {
338 this.locale = locale;
342 public boolean wantsDirectoryListing() {
343 GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT listme FROM users WHERE id=?");
344 get.setInt(1, getId());
345 try (GigiResultSet exec = get.executeQuery()) {
346 return exec.next() && exec.getBoolean("listme");
350 public String getContactInformation() {
351 GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT contactinfo FROM users WHERE id=?");
352 get.setInt(1, getId());
354 try (GigiResultSet exec = get.executeQuery()) {
356 return exec.getString("contactinfo");
360 public void setDirectoryListing(boolean on) {
361 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET listme = ? WHERE id = ?");
362 update.setBoolean(1, on);
363 update.setInt(2, getId());
364 update.executeUpdate();
367 public void setContactInformation(String contactInfo) {
368 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET contactinfo = ? WHERE id = ?");
369 update.setString(1, contactInfo);
370 update.setInt(2, getId());
371 update.executeUpdate();
374 public boolean isInGroup(Group g) {
375 return groups.contains(g);
378 public Set<Group> getGroups() {
379 return Collections.unmodifiableSet(groups);
382 public void grantGroup(User granter, Group toGrant) {
384 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?");
385 ps.setInt(1, getId());
386 ps.setString(2, toGrant.getDatabaseName());
387 ps.setInt(3, granter.getId());
391 public void revokeGroup(User revoker, Group toRevoke) {
392 groups.remove(toRevoke);
393 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?");
394 ps.setInt(1, revoker.getId());
395 ps.setString(2, toRevoke.getDatabaseName());
396 ps.setInt(3, getId());
400 public List<Organisation> getOrganisations() {
401 List<Organisation> orgas = new ArrayList<>();
402 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL");
403 query.setInt(1, getId());
404 try (GigiResultSet res = query.executeQuery()) {
406 orgas.add(Organisation.getById(res.getInt(1)));
413 public static synchronized User getById(int id) {
414 CertificateOwner co = CertificateOwner.getById(id);
415 if (co instanceof User) {
422 public static User getByEmail(String mail) {
423 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL");
424 ps.setString(1, mail);
425 try (GigiResultSet rs = ps.executeQuery()) {
430 return User.getById(rs.getInt(1));
434 public static User[] findByEmail(String mail) {
435 LinkedList<User> results = new LinkedList<User>();
436 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("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");
437 ps.setString(1, mail);
438 try (GigiResultSet rs = ps.executeQuery()) {
440 results.add(User.getById(rs.getInt(1)));
442 return results.toArray(new User[results.size()]);
446 public EmailAddress[] getEmails() {
447 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL");
448 ps.setInt(1, getId());
450 try (GigiResultSet rs = ps.executeQuery()) {
451 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
454 data.add(EmailAddress.getById(rs.getInt(1)));
457 return data.toArray(new EmailAddress[0]);
462 public boolean isValidEmail(String email) {
463 for (EmailAddress em : getEmails()) {
464 if (em.getAddress().equals(email)) {
465 return em.isVerified();
472 public String[] getTrainings() {
473 GigiPreparedStatement prep = DatabaseConnection.getInstance().prepare("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");
474 prep.setInt(1, getId());
475 GigiResultSet res = prep.executeQuery();
476 List<String> entries = new LinkedList<String>();
480 entries.add(DateSelector.getDateFormat().format(res.getTimestamp(1)) + " (" + res.getString(2) + ")");
483 return entries.toArray(new String[0]);
486 public int generatePasswordResetTicket(User actor, String token, String privateToken) {
487 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `passwordResetTickets` SET `memid`=?, `creator`=?, `token`=?, `private_token`=?");
488 ps.setInt(1, getId());
489 ps.setInt(2, getId());
490 ps.setString(3, token);
491 ps.setString(4, PasswordHash.hash(privateToken));
493 return ps.lastInsertId();
496 public static User getResetWithToken(int id, String token) {
497 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `memid` FROM `passwordResetTickets` WHERE `id`=? AND `token`=? AND `used` IS NULL");
499 ps.setString(2, token);
500 GigiResultSet res = ps.executeQuery();
504 return User.getById(res.getInt(1));
507 public synchronized void consumePasswordResetTicket(int id, String private_token, String newPassword) throws GigiApiException {
508 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `private_token` FROM `passwordResetTickets` WHERE `id`=? AND `memid`=? AND `used` IS NULL");
510 ps.setInt(2, getId());
511 try (GigiResultSet rs = ps.executeQuery()) {
513 throw new GigiApiException("Token not found... very bad.");
515 ps = DatabaseConnection.getInstance().prepare("UPDATE `passwordResetTickets` SET `used` = CURRENT_TIMESTAMP WHERE `id`=?");
518 if (PasswordHash.verifyHash(private_token, rs.getString(1)) == null) {
519 throw new GigiApiException("Private token does not match.");
521 setPassword(newPassword);