]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/EmailAddress.java
chg: Be more liberal in what email addresses are accepted.
[gigi.git] / src / org / cacert / gigi / dbObjects / EmailAddress.java
1 package org.cacert.gigi.dbObjects;
2
3 import java.io.IOException;
4 import java.util.Date;
5 import java.util.LinkedList;
6 import java.util.Locale;
7
8 import org.cacert.gigi.GigiApiException;
9 import org.cacert.gigi.database.GigiPreparedStatement;
10 import org.cacert.gigi.database.GigiResultSet;
11 import org.cacert.gigi.email.EmailProvider;
12 import org.cacert.gigi.email.MailProbe;
13 import org.cacert.gigi.localisation.Language;
14 import org.cacert.gigi.output.template.SprintfCommand;
15 import org.cacert.gigi.util.RandomToken;
16
17 public class EmailAddress implements IdCachable, Verifyable {
18
19     public static final int REPING_MINIMUM_DELAY = 5 * 60 * 1000;
20
21     private String address;
22
23     private int id;
24
25     private User owner;
26
27     private EmailAddress(int id) {
28         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid`, `email` FROM `emails` WHERE `id`=? AND `deleted` IS NULL")) {
29             ps.setInt(1, id);
30
31             GigiResultSet rs = ps.executeQuery();
32             if ( !rs.next()) {
33                 throw new IllegalArgumentException("Invalid email id " + id);
34             }
35             this.id = id;
36             owner = User.getById(rs.getInt(1));
37             address = rs.getString(2);
38         }
39     }
40
41     public EmailAddress(User owner, String address, Locale mailLocale) throws GigiApiException {
42         address = address.toLowerCase();
43         if ( !EmailProvider.isValidMailAddress(address)) {
44             throw new IllegalArgumentException("Invalid email.");
45         }
46         this.address = address;
47         this.owner = owner;
48         insert(Language.getInstance(mailLocale));
49     }
50
51     private void insert(Language l) throws GigiApiException {
52         try {
53             synchronized (EmailAddress.class) {
54                 if (id != 0) {
55                     throw new IllegalStateException("already inserted.");
56                 }
57                 try (GigiPreparedStatement psCheck = new GigiPreparedStatement("SELECT 1 FROM `emails` WHERE email=? AND deleted is NULL"); GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `emails` SET memid=?, email=?")) {
58                     ps.setInt(1, owner.getId());
59                     ps.setString(2, address);
60                     psCheck.setString(1, address);
61                     GigiResultSet res = psCheck.executeQuery();
62                     if (res.next()) {
63                         throw new GigiApiException("The email address is already known to the system.");
64                     }
65                     ps.execute();
66                     id = ps.lastInsertId();
67                 }
68                 myCache.put(this);
69             }
70             ping(l);
71         } catch (IOException e) {
72             e.printStackTrace();
73         }
74     }
75
76     private void ping(Language l) throws IOException {
77         String hash = RandomToken.generateToken(16);
78         try (GigiPreparedStatement statmt = new GigiPreparedStatement("INSERT INTO `emailPinglog` SET `when`=NOW(), `email`=?, `result`='', `uid`=?, `type`='active', `status`='open'::`pingState`, `challenge`=?")) {
79             statmt.setString(1, address);
80             statmt.setInt(2, owner.getId());
81             statmt.setString(3, hash);
82             statmt.execute();
83         }
84
85         MailProbe.sendMailProbe(l, "email", id, hash, address);
86     }
87
88     public int getId() {
89         return id;
90     }
91
92     public String getAddress() {
93         return address;
94     }
95
96     public synchronized void verify(String hash) throws GigiApiException {
97         try (GigiPreparedStatement stmt = new GigiPreparedStatement("UPDATE `emailPinglog` SET `status`='success'::`pingState` WHERE `email`=? AND `uid`=? AND `type`='active' AND `challenge`=?")) {
98             stmt.setString(1, address);
99             stmt.setInt(2, owner.getId());
100             stmt.setString(3, hash);
101             stmt.executeUpdate();
102         }
103         // Verify user with that primary email
104         try (GigiPreparedStatement ps2 = new GigiPreparedStatement("update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'")) {
105             ps2.setInt(1, owner.getId());
106             ps2.setString(2, address);
107             ps2.execute();
108         }
109     }
110
111     public boolean isVerified() {
112         try (GigiPreparedStatement statmt = new GigiPreparedStatement("SELECT 1 FROM `emailPinglog` WHERE `email`=? AND `uid`=? AND `type`='active' AND `status`='success'")) {
113             statmt.setString(1, address);
114             statmt.setInt(2, owner.getId());
115             GigiResultSet e = statmt.executeQuery();
116             return e.next();
117         }
118     }
119
120     public Date getLastPing(boolean onlySuccess) {
121         Date lastExecution;
122         try (GigiPreparedStatement statmt = new GigiPreparedStatement("SELECT MAX(`when`) FROM `emailPinglog` WHERE `email`=? AND `uid`=? AND `type`='active'" + (onlySuccess ? " AND `status`='success'" : ""))) {
123             statmt.setString(1, address);
124             statmt.setInt(2, owner.getId());
125             GigiResultSet e = statmt.executeQuery();
126             if ( !e.next()) {
127                 return null;
128             }
129             lastExecution = e.getTimestamp(1);
130         }
131         return lastExecution;
132     }
133
134     public synchronized void requestReping(Language l) throws IOException, GigiApiException {
135         Date lastExecution = getLastPing(false);
136
137         if (lastExecution != null && lastExecution.getTime() + REPING_MINIMUM_DELAY >= System.currentTimeMillis()) {
138             throw new GigiApiException(SprintfCommand.createSimple("Reping is only allowed after {0} minutes, yours end at {1}.", REPING_MINIMUM_DELAY / 60 / 1000, new Date(lastExecution.getTime() + REPING_MINIMUM_DELAY)));
139         }
140         ping(l);
141         return;
142     }
143
144     private static ObjectCache<EmailAddress> myCache = new ObjectCache<>();
145
146     public static synchronized EmailAddress getById(int id) throws IllegalArgumentException {
147         EmailAddress em = myCache.get(id);
148         if (em == null) {
149             myCache.put(em = new EmailAddress(id));
150         }
151         return em;
152     }
153
154     public User getOwner() {
155         return owner;
156     }
157
158     public static EmailAddress[] findByAllEmail(String mail) {
159         LinkedList<EmailAddress> results = new LinkedList<EmailAddress>();
160         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `emails`.`id` FROM `emails` INNER JOIN `users` ON `users`.`id` = `emails`.`memid` INNER JOIN `certOwners` ON `certOwners`.`id` = `users`.`id` WHERE `emails`.`email` LIKE ? AND `emails`.`deleted` IS NULL AND `certOwners`.`deleted` IS NULL ORDER BY `users`.`id`, `emails`.`email` LIMIT 100")) {
161             ps.setString(1, mail);
162             GigiResultSet rs = ps.executeQuery();
163             while (rs.next()) {
164                 results.add(EmailAddress.getById(rs.getInt(1)));
165             }
166             return results.toArray(new EmailAddress[results.size()]);
167         }
168     }
169 }