1 package org.cacert.gigi.dbObjects;
3 import java.io.IOException;
4 import org.cacert.gigi.GigiApiException;
5 import org.cacert.gigi.database.DatabaseConnection;
6 import org.cacert.gigi.database.GigiPreparedStatement;
7 import org.cacert.gigi.database.GigiResultSet;
8 import org.cacert.gigi.email.EmailProvider;
9 import org.cacert.gigi.email.MailProbe;
10 import org.cacert.gigi.localisation.Language;
11 import org.cacert.gigi.util.RandomToken;
13 public class EmailAddress implements IdCachable {
15 private String address;
21 private String hash = null;
23 private EmailAddress(int id) {
24 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT memid, email, hash FROM `emails` WHERE id=? AND deleted=0");
27 GigiResultSet rs = ps.executeQuery();
29 throw new IllegalArgumentException("Invalid email id " + id);
32 owner = User.getById(rs.getInt(1));
33 address = rs.getString(2);
34 hash = rs.getString(3);
38 public EmailAddress(User owner, String address) {
39 if ( !EmailProvider.MAIL.matcher(address).matches()) {
40 throw new IllegalArgumentException("Invalid email.");
42 this.address = address;
44 this.hash = RandomToken.generateToken(16);
47 public void insert(Language l) {
49 throw new IllegalStateException("already inserted.");
52 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `emails` SET memid=?, hash=?, email=?");
53 ps.setInt(1, owner.getId());
54 ps.setString(2, hash);
55 ps.setString(3, address);
56 synchronized (EmailAddress.class) {
58 id = ps.lastInsertId();
61 MailProbe.sendMailProbe(l, "email", id, hash, address);
62 } catch (IOException e) {
71 public String getAddress() {
75 public synchronized void verify(String hash) throws GigiApiException {
76 if (this.hash.equals(hash)) {
77 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `emails` SET hash='' WHERE id=?");
82 // Verify user with that primary email
83 GigiPreparedStatement ps2 = DatabaseConnection.getInstance().prepare("update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'");
84 ps2.setInt(1, owner.getId());
85 ps2.setString(2, address);
90 throw new GigiApiException("Email verification hash is invalid.");
94 public boolean isVerified() {
95 return hash.isEmpty();
98 private static ObjectCache<EmailAddress> myCache = new ObjectCache<>();
100 public static synchronized EmailAddress getById(int id) throws IllegalArgumentException {
101 EmailAddress em = myCache.get(id);
103 myCache.put(em = new EmailAddress(id));