1 package org.cacert.gigi;
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.database.DatabaseConnection;
9 import org.cacert.gigi.email.EmailProvider;
10 import org.cacert.gigi.email.MailProbe;
11 import org.cacert.gigi.localisation.Language;
12 import org.cacert.gigi.util.RandomToken;
14 public class EmailAddress {
16 private String address;
22 private String hash = null;
24 private EmailAddress(int id) throws SQLException {
25 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT memid, email, hash FROM `emails` WHERE id=? AND deleted=0");
28 ResultSet rs = ps.executeQuery();
30 throw new IllegalArgumentException("Invalid email id " + id);
33 owner = User.getById(rs.getInt(1));
34 address = rs.getString(2);
35 hash = rs.getString(3);
39 public EmailAddress(String address, User owner) {
40 if ( !EmailProvider.MAIL.matcher(address).matches()) {
41 throw new IllegalArgumentException("Invalid email.");
43 this.address = address;
45 this.hash = RandomToken.generateToken(16);
48 public void insert(Language l) {
50 throw new IllegalStateException("already inserted.");
53 PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `emails` SET memid=?, hash=?, email=?");
54 ps.setInt(1, owner.getId());
55 ps.setString(2, hash);
56 ps.setString(3, address);
58 id = DatabaseConnection.lastInsertId(ps);
59 MailProbe.sendMailProbe(l, "email", id, hash, address);
60 } catch (SQLException e) {
62 } catch (IOException e) {
71 public String getAddress() {
75 public synchronized void verify(String hash) throws GigiApiException {
76 if (this.hash.equals(hash)) {
79 PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `emails` SET hash='' WHERE id=?");
84 // Verify user with that primary email
85 PreparedStatement ps2 = DatabaseConnection.getInstance().prepare("update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'");
86 ps2.setInt(1, owner.getId());
87 ps2.setString(2, address);
90 } catch (SQLException e) {
91 throw new GigiApiException(e);
95 throw new GigiApiException("Email verification hash is invalid.");
99 public static EmailAddress getById(int id) throws IllegalArgumentException {
102 EmailAddress e = new EmailAddress(id);
104 } catch (SQLException e) {
105 throw new IllegalArgumentException(e);
109 public boolean isVerified() {
110 return hash.isEmpty();