1 package org.cacert.gigi.dbObjects;
3 import java.io.IOException;
4 import java.util.Locale;
6 import org.cacert.gigi.GigiApiException;
7 import org.cacert.gigi.database.DatabaseConnection;
8 import org.cacert.gigi.database.GigiPreparedStatement;
9 import org.cacert.gigi.database.GigiResultSet;
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, Verifyable {
17 private String address;
23 private String hash = null;
25 private EmailAddress(int id) {
26 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `memid`, `email`, `hash` FROM `emails` WHERE `id`=? AND `deleted` IS NULL");
29 GigiResultSet 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, Locale mailLocale) throws GigiApiException {
41 if ( !EmailProvider.MAIL.matcher(address).matches()) {
42 throw new IllegalArgumentException("Invalid email.");
44 this.address = address;
46 this.hash = RandomToken.generateToken(16);
47 insert(Language.getInstance(mailLocale));
50 private void insert(Language l) throws GigiApiException {
52 synchronized (EmailAddress.class) {
54 throw new IllegalStateException("already inserted.");
56 GigiPreparedStatement psCheck = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `emails` WHERE email=? AND deleted is NULL");
57 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `emails` SET memid=?, hash=?, email=?");
58 ps.setInt(1, owner.getId());
59 ps.setString(2, hash);
60 ps.setString(3, address);
61 psCheck.setString(1, address);
62 GigiResultSet res = psCheck.executeQuery();
64 throw new GigiApiException("The email is currently valid");
67 id = ps.lastInsertId();
70 MailProbe.sendMailProbe(l, "email", id, hash, address);
71 } catch (IOException e) {
80 public String getAddress() {
84 public synchronized void verify(String hash) throws GigiApiException {
85 if (this.hash.equals(hash)) {
86 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `emails` SET hash='' WHERE id=?");
91 // Verify user with that primary email
92 GigiPreparedStatement ps2 = DatabaseConnection.getInstance().prepare("update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'");
93 ps2.setInt(1, owner.getId());
94 ps2.setString(2, address);
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 synchronized EmailAddress getById(int id) throws IllegalArgumentException {
110 EmailAddress em = myCache.get(id);
112 myCache.put(em = new EmailAddress(id));