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