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