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`=1");
138 query.setInt(1, getId());
139 try (GigiResultSet rs = query.executeQuery()) {
148 public int getAssurancePoints() {
149 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT sum(points) FROM `notary` where `to`=? AND `deleted` is NULL");
150 query.setInt(1, getId());
152 try (GigiResultSet rs = query.executeQuery()) {
156 points = rs.getInt(1);
163 public int getExperiencePoints() {
164 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT count(*) FROM `notary` where `from`=? AND `deleted` is NULL");
165 query.setInt(1, getId());
167 try (GigiResultSet rs = query.executeQuery()) {
171 points = rs.getInt(1) * 2;
179 * Gets the maximum allowed points NOW. Note that an assurance needs to
180 * re-check PoJam as it has taken place in the past.
182 * @return the maximal points @
184 public int getMaxAssurePoints() {
189 int exp = getExperiencePoints();
211 public boolean isOfAge(int desiredAge) {
212 Calendar c = Calendar.getInstance();
214 int year = c.get(Calendar.YEAR);
215 int month = c.get(Calendar.MONTH);
216 int day = c.get(Calendar.DAY_OF_MONTH);
217 c.set(year, month, day);
218 c.add(Calendar.YEAR, desiredAge);
219 return System.currentTimeMillis() >= c.getTime().getTime();
222 public boolean isValidName(String name) {
223 return getName().matches(name);
226 public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException {
227 for (EmailAddress email : getEmails()) {
228 if (email.getAddress().equals(newMail.getAddress())) {
229 if ( !email.isVerified()) {
230 throw new GigiApiException("Email not verified.");
233 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET email=? WHERE id=?");
234 ps.setString(1, newMail.getAddress());
235 ps.setInt(2, getId());
238 this.email = newMail.getAddress();
243 throw new GigiApiException("Given address not an address of the user.");
246 public void deleteEmail(EmailAddress delMail) throws GigiApiException {
247 if (getEmail().equals(delMail.getAddress())) {
248 throw new GigiApiException("Can't delete user's default e-mail.");
251 for (EmailAddress email : getEmails()) {
252 if (email.getId() == delMail.getId()) {
253 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `emails` SET `deleted`=CURRENT_TIMESTAMP WHERE `id`=?");
254 ps.setInt(1, delMail.getId());
259 throw new GigiApiException("Email not one of user's email addresses.");
262 public synchronized Assurance[] getReceivedAssurances() {
263 if (receivedAssurances == null) {
264 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM `notary` WHERE `to`=? AND `deleted` IS NULL");
265 query.setInt(1, getId());
267 try (GigiResultSet res = query.executeQuery()) {
268 List<Assurance> assurances = new LinkedList<Assurance>();
271 assurances.add(new Assurance(res));
274 this.receivedAssurances = assurances.toArray(new Assurance[0]);
278 return receivedAssurances;
281 public synchronized Assurance[] getMadeAssurances() {
282 if (madeAssurances == null) {
283 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT * FROM notary WHERE `from`=? AND deleted is NULL");
284 query.setInt(1, getId());
286 try (GigiResultSet res = query.executeQuery()) {
287 List<Assurance> assurances = new LinkedList<Assurance>();
290 assurances.add(new Assurance(res));
293 this.madeAssurances = assurances.toArray(new Assurance[0]);
297 return madeAssurances;
300 public synchronized void invalidateMadeAssurances() {
301 madeAssurances = null;
304 public synchronized void invalidateReceivedAssurances() {
305 receivedAssurances = null;
308 public void updateUserData() throws GigiApiException {
309 synchronized (Notary.class) {
310 // FIXME: No assurance, not no points.
311 if (getAssurancePoints() != 0) {
312 throw new GigiApiException("No change after assurance allowed.");
318 protected void rawUpdateUserData() {
319 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET fname=?, lname=?, mname=?, suffix=?, dob=? WHERE id=?");
320 update.setString(1, name.getFname());
321 update.setString(2, name.getLname());
322 update.setString(3, name.getMname());
323 update.setString(4, name.getSuffix());
324 update.setDate(5, getDoB());
325 update.setInt(6, getId());
326 update.executeUpdate();
329 public Locale getPreferredLocale() {
333 public void setPreferredLocale(Locale locale) {
334 this.locale = locale;
338 public boolean wantsDirectoryListing() {
339 GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT listme FROM users WHERE id=?");
340 get.setInt(1, getId());
341 try (GigiResultSet exec = get.executeQuery()) {
342 return exec.next() && exec.getBoolean("listme");
346 public String getContactInformation() {
347 GigiPreparedStatement get = DatabaseConnection.getInstance().prepare("SELECT contactinfo FROM users WHERE id=?");
348 get.setInt(1, getId());
350 try (GigiResultSet exec = get.executeQuery()) {
352 return exec.getString("contactinfo");
356 public void setDirectoryListing(boolean on) {
357 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET listme = ? WHERE id = ?");
358 update.setBoolean(1, on);
359 update.setInt(2, getId());
360 update.executeUpdate();
363 public void setContactInformation(String contactInfo) {
364 GigiPreparedStatement update = DatabaseConnection.getInstance().prepare("UPDATE users SET contactinfo = ? WHERE id = ?");
365 update.setString(1, contactInfo);
366 update.setInt(2, getId());
367 update.executeUpdate();
370 public boolean isInGroup(Group g) {
371 return groups.contains(g);
374 public Set<Group> getGroups() {
375 return Collections.unmodifiableSet(groups);
378 public void grantGroup(User granter, Group toGrant) {
380 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `user_groups` SET `user`=?, `permission`=?::`userGroup`, `grantedby`=?");
381 ps.setInt(1, getId());
382 ps.setString(2, toGrant.getDatabaseName());
383 ps.setInt(3, granter.getId());
387 public void revokeGroup(User revoker, Group toRevoke) {
388 groups.remove(toRevoke);
389 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `user_groups` SET `deleted`=CURRENT_TIMESTAMP, `revokedby`=? WHERE `deleted` IS NULL AND `permission`=?::`userGroup` AND `user`=?");
390 ps.setInt(1, revoker.getId());
391 ps.setString(2, toRevoke.getDatabaseName());
392 ps.setInt(3, getId());
396 public List<Organisation> getOrganisations() {
397 List<Organisation> orgas = new ArrayList<>();
398 GigiPreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT `orgid` FROM `org_admin` WHERE `memid`=? AND `deleted` IS NULL");
399 query.setInt(1, getId());
400 try (GigiResultSet res = query.executeQuery()) {
402 orgas.add(Organisation.getById(res.getInt(1)));
409 public static synchronized User getById(int id) {
410 CertificateOwner co = CertificateOwner.getById(id);
411 if (co instanceof User) {
418 public static User getByEmail(String mail) {
419 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `users`.`id` FROM `users` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `email`=? AND `deleted` IS NULL");
420 ps.setString(1, mail);
421 try (GigiResultSet rs = ps.executeQuery()) {
426 return User.getById(rs.getInt(1));
430 public static User[] findByEmail(String mail) {
431 LinkedList<User> results = new LinkedList<User>();
432 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");
433 ps.setString(1, mail);
434 try (GigiResultSet rs = ps.executeQuery()) {
436 results.add(User.getById(rs.getInt(1)));
438 return results.toArray(new User[results.size()]);
442 public EmailAddress[] getEmails() {
443 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `id` FROM `emails` WHERE `memid`=? AND `deleted` IS NULL");
444 ps.setInt(1, getId());
446 try (GigiResultSet rs = ps.executeQuery()) {
447 LinkedList<EmailAddress> data = new LinkedList<EmailAddress>();
450 data.add(EmailAddress.getById(rs.getInt(1)));
453 return data.toArray(new EmailAddress[0]);
458 public boolean isValidEmail(String email) {
459 for (EmailAddress em : getEmails()) {
460 if (em.getAddress().equals(email)) {
461 return em.isVerified();
468 public String[] getTrainings() {
469 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");
470 prep.setInt(1, getId());
471 GigiResultSet res = prep.executeQuery();
472 List<String> entries = new LinkedList<String>();
476 entries.add(DateSelector.getDateFormat().format(res.getTimestamp(1)) + " (" + res.getString(2) + ")");
479 return entries.toArray(new String[0]);