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.");
113 PasswordStrengthChecker.assertStrongPassword(newPass, getName(), getEmail());
114 ps = DatabaseConnection.getInstance().prepare("UPDATE users SET `password`=? WHERE id=?");
115 ps.setString(1, PasswordHash.hash(newPass));
116 ps.setInt(2, getId());
120 public void setName(Name name) {
124 public boolean canAssure() {
125 if ( !isOfAge(14)) { // PoJAM
128 if (getAssurancePoints() < 100) {
132 return hasPassedCATS();
136 public boolean hasPassedCATS() {
137 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `cats_passed` where `user_id`=? AND `variant_id`=?");
138 query.setInt(1, getId());
139 query.setInt(2, CATS.ASSURER_CHALLANGE_ID);
140 try (GigiResultSet rs = query.executeQuery()) {
149 public int getAssurancePoints() {
150 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT sum(points) FROM `notary` where `to`=? AND `deleted` is NULL");
151 query.setInt(1, getId());
153 try (GigiResultSet rs = query.executeQuery()) {
157 points = rs.getInt(1);
164 public int getExperiencePoints() {
165 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT count(*) FROM `notary` where `from`=? AND `deleted` is NULL");
166 query.setInt(1, getId());
168 try (GigiResultSet rs = query.executeQuery()) {
172 points = rs.getInt(1) * 2;
180 * Gets the maximum allowed points NOW. Note that an assurance needs to
181 * re-check PoJam as it has taken place in the past.
183 * @return the maximal points @
185 public int getMaxAssurePoints() {
190 int exp = getExperiencePoints();
212 public boolean isOfAge(int desiredAge) {
213 Calendar c = Calendar.getInstance();
215 int year = c.get(Calendar.YEAR);
216 int month = c.get(Calendar.MONTH);
217 int day = c.get(Calendar.DAY_OF_MONTH);
218 c.set(year, month, day);
219 c.add(Calendar.YEAR, desiredAge);
220 return System.currentTimeMillis() >= c.getTime().getTime();
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 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET email=? WHERE id=?");
235 ps.setString(1, newMail.getAddress());
236 ps.setInt(2, getId());
239 this.email = newMail.getAddress();
244 throw new GigiApiException("Given address not an address of the user.");
247 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
248 if (getEmail().equals(delMail.getAddress())) {
249 throw new GigiApiException("Can't delete user's default e-mail.");
252 for (EmailAddress email : getEmails()) {
253 if (email.getId() == delMail.getId()) {
254 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?");
255 ps.setInt(1, delMail.getId());
260 throw new GigiApiException("Email not one of user's email addresses.");
263 public synchronized Assurance[] getReceivedAssurances() {
264 if (receivedAssurances == null) {
265 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM `notary` WHERE `to`=? AND `deleted` IS NULL");
266 query.setInt(1, getId());
268 try (GigiResultSet res = query.executeQuery()) {
269 List<Assurance> assurances = new LinkedList<Assurance>();
272 assurances.add(new Assurance(res));
275 this.receivedAssurances = assurances.toArray(new Assurance[0]);
279 return receivedAssurances;
282 public synchronized Assurance[] getMadeAssurances() {
283 if (madeAssurances == null) {
284 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `from`=? AND deleted is NULL");
285 query.setInt(1, getId());
287 try (GigiResultSet res = query.executeQuery()) {
288 List<Assurance> assurances = new LinkedList<Assurance>();
291 assurances.add(new Assurance(res));
294 this.madeAssurances = assurances.toArray(new Assurance[0]);
298 return madeAssurances;
301 public synchronized void invalidateMadeAssurances() {
302 madeAssurances = null;
305 public synchronized void invalidateReceivedAssurances() {
306 receivedAssurances = null;
309 public void updateUserData() throws GigiApiException {
310 synchronized (Notary.class) {
311 // FIXME: No assurance, not no points.
312 if (getAssurancePoints() != 0) {
313 throw new GigiApiException("No change after assurance allowed.");
319 protected void rawUpdateUserData() {
320 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?");
321 update.setString(1, name.getFname());
322 update.setString(2, name.getLname());
323 update.setString(3, name.getMname());
324 update.setString(4, name.getSuffix());
325 update.setDate(5, getDoB());
326 update.setInt(6, getId());
327 update.executeUpdate();
330 public Locale getPreferredLocale() {
334 public void setPreferredLocale(Locale locale) {
335 this.locale = locale;
339 public boolean wantsDirectoryListing() {
340 GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT listme FROM users WHERE id=?");
341 get.setInt(1, getId());
342 try (GigiResultSet exec = get.executeQuery()) {
343 return exec.next() && exec.getBoolean("listme");
347 public String getContactInformation() {
348 GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT contactinfo FROM users WHERE id=?");
349 get.setInt(1, getId());
351 try (GigiResultSet exec = get.executeQuery()) {
353 return exec.getString("contactinfo");
357 public void setDirectoryListing(boolean on) {
358 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET listme = ? WHERE id = ?");
359 update.setBoolean(1, on);
360 update.setInt(2, getId());
361 update.executeUpdate();
364 public void setContactInformation(String contactInfo) {
365 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET contactinfo = ? WHERE id = ?");
366 update.setString(1, contactInfo);
367 update.setInt(2, getId());
368 update.executeUpdate();
371 public boolean isInGroup(Group g) {
372 return groups.contains(g);
375 public Set<Group> getGroups() {
376 return Collections.unmodifiableSet(groups);
379 public void grantGroup(User granter, Group toGrant) {
381 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?");
382 ps.setInt(1, getId());
383 ps.setString(2, toGrant.getDatabaseName());
384 ps.setInt(3, granter.getId());
388 public void revokeGroup(User revoker, Group toRevoke) {
389 groups.remove(toRevoke);
390 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?");
391 ps.setInt(1, revoker.getId());
392 ps.setString(2, toRevoke.getDatabaseName());
393 ps.setInt(3, getId());
397 public List<Organisation> getOrganisations() {
398 List<Organisation> orgas = new ArrayList<>();
399 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL");
400 query.setInt(1, getId());
401 try (GigiResultSet res = query.executeQuery()) {
403 orgas.add(Organisation.getById(res.getInt(1)));
410 public static synchronized User getById(int id) {
411 CertificateOwner co = CertificateOwner.getById(id);
412 if (co instanceof User) {
419 public static User getByEmail(String mail) {
420 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL");
421 ps.setString(1, mail);
422 try (GigiResultSet rs = ps.executeQuery()) {
427 return User.getById(rs.getInt(1));
431 public static User[] findByEmail(String mail) {
432 LinkedList<User> results = new LinkedList<User>();
433 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");
434 ps.setString(1, mail);
435 try (GigiResultSet rs = ps.executeQuery()) {
437 results.add(User.getById(rs.getInt(1)));
439 return results.toArray(new User[results.size()]);
443 public EmailAddress[] getEmails() {
444 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL");
445 ps.setInt(1, getId());
447 try (GigiResultSet rs = ps.executeQuery()) {
448 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
451 data.add(EmailAddress.getById(rs.getInt(1)));
454 return data.toArray(new EmailAddress[0]);
459 public boolean isValidEmail(String email) {
460 for (EmailAddress em : getEmails()) {
461 if (em.getAddress().equals(email)) {
462 return em.isVerified();
469 public String[] getTrainings() {
470 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");
471 prep.setInt(1, getId());
472 GigiResultSet res = prep.executeQuery();
473 List<String> entries = new LinkedList<String>();
477 entries.add(DateSelector.getDateFormat().format(res.getTimestamp(1)) + " (" + res.getString(2) + ")");
480 return entries.toArray(new String[0]);