1 package org.cacert.gigi.dbObjects;
3 import java.io.IOException;
4 import java.sql.PreparedStatement;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
8 import org.cacert.gigi.GigiApiException;
9 import org.cacert.gigi.database.DatabaseConnection;
10 import org.cacert.gigi.email.EmailProvider;
11 import org.cacert.gigi.email.MailProbe;
12 import org.cacert.gigi.localisation.Language;
13 import org.cacert.gigi.util.RandomToken;
15 public class EmailAddress implements IdCachable {
17 private String address;
23 private String hash = null;
25 private EmailAddress(int id) throws SQLException {
26 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT memid, email, hash FROM `emails` WHERE id=? AND deleted=0");
29 ResultSet rs = ps.executeQuery();
31 throw new IllegalArgumentException("Invalid email id " + id);
34 owner = User.getById(rs.getInt(1));
35 address = rs.getString(2);
36 hash = rs.getString(3);
40 public EmailAddress(User owner, String address) {
41 if ( !EmailProvider.MAIL.matcher(address).matches()) {
42 throw new IllegalArgumentException("Invalid email.");
44 this.address = address;
46 this.hash = RandomToken.generateToken(16);
49 public void insert(Language l) {
51 throw new IllegalStateException("already inserted.");
54 PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `emails` SET memid=?, hash=?, email=?");
55 ps.setInt(1, owner.getId());
56 ps.setString(2, hash);
57 ps.setString(3, address);
58 synchronized (EmailAddress.class) {
60 id = DatabaseConnection.lastInsertId(ps);
63 MailProbe.sendMailProbe(l, "email", id, hash, address);
64 } catch (SQLException e) {
66 } catch (IOException e) {
75 public String getAddress() {
79 public synchronized void verify(String hash) throws GigiApiException {
80 if (this.hash.equals(hash)) {
83 PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `emails` SET hash='' WHERE id=?");
88 // Verify user with that primary email
89 PreparedStatement ps2 = DatabaseConnection.getInstance().prepare("update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'");
90 ps2.setInt(1, owner.getId());
91 ps2.setString(2, address);
94 } catch (SQLException e) {
95 throw new GigiApiException(e);
99 throw new GigiApiException("Email verification hash is invalid.");
103 public boolean isVerified() {
104 return hash.isEmpty();
107 private static ObjectCache<EmailAddress> myCache = new ObjectCache<>();
109 public static EmailAddress getById(int id) throws IllegalArgumentException {
110 EmailAddress em = myCache.get(id);
113 synchronized (EmailAddress.class) {
114 myCache.put(em = new EmailAddress(id));
116 } catch (SQLException e1) {
117 throw new IllegalArgumentException(e1);