chg: enforce email address for certificate was pinged within 6 months
[gigi.git] / src / club / wpia / gigi / dbObjects / EmailAddress.java
1 package club.wpia.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 club.wpia.gigi.GigiApiException;
9 import club.wpia.gigi.database.GigiPreparedStatement;
10 import club.wpia.gigi.database.GigiResultSet;
11 import club.wpia.gigi.email.EmailProvider;
12 import club.wpia.gigi.email.MailProbe;
13 import club.wpia.gigi.localisation.Language;
14 import club.wpia.gigi.output.template.SprintfCommand;
15 import club.wpia.gigi.util.RandomToken;
16 import club.wpia.gigi.util.TimeConditions;
17
18 public class EmailAddress implements IdCachable, Verifyable {
19
20     public static final int REPING_MINIMUM_DELAY = 5 * 60 * 1000;
21
22     private String address;
23
24     private int id;
25
26     private User owner;
27
28     private EmailAddress(int id) {
29         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid`, `email` FROM `emails` WHERE `id`=? AND `deleted` IS NULL")) {
30             ps.setInt(1, id);
31
32             GigiResultSet rs = ps.executeQuery();
33             if ( !rs.next()) {
34                 throw new IllegalArgumentException("Invalid email id " + id);
35             }
36             this.id = id;
37             owner = User.getById(rs.getInt(1));
38             address = rs.getString(2);
39         }
40     }
41
42     public EmailAddress(User owner, String address, Locale mailLocale) throws GigiApiException {
43         address = address.toLowerCase();
44         if ( !EmailProvider.isValidMailAddress(address)) {
45             throw new IllegalArgumentException("Invalid email.");
46         }
47         this.address = address;
48         this.owner = owner;
49         insert(Language.getInstance(mailLocale));
50     }
51
52     private void insert(Language l) throws GigiApiException {
53         try {
54             synchronized (EmailAddress.class) {
55                 if (id != 0) {
56                     throw new IllegalStateException("already inserted.");
57                 }
58                 try (GigiPreparedStatement psCheck = new GigiPreparedStatement("SELECT 1 FROM `emails` WHERE email=? AND deleted is NULL")) {
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                 }
65                 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `emails` SET memid=?, email=?")) {
66                     ps.setInt(1, owner.getId());
67                     ps.setString(2, address);
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 boolean isVerifyable(String hash) throws GigiApiException {
100         try (GigiPreparedStatement stmt = new GigiPreparedStatement("SELECT 1 FROM `emailPinglog` WHERE `email`=? AND `uid`=? AND `type`='active' AND `challenge`=? AND `status`='open'::`pingState`")) {
101             stmt.setString(1, address);
102             stmt.setInt(2, owner.getId());
103             stmt.setString(3, hash);
104             return stmt.executeQuery().next();
105         }
106     }
107
108     public synchronized void verify(String hash) throws GigiApiException {
109         try (GigiPreparedStatement stmt = new GigiPreparedStatement("UPDATE `emailPinglog` SET `status`='success'::`pingState` WHERE `email`=? AND `uid`=? AND `type`='active' AND `challenge`=? AND `status`='open'::`pingState`")) {
110             stmt.setString(1, address);
111             stmt.setInt(2, owner.getId());
112             stmt.setString(3, hash);
113             if ( !stmt.executeMaybeUpdate()) {
114                 throw new IllegalArgumentException("Given token could not be found to complete the verification process (Domain Ping).");
115             }
116         }
117         // Verify user with that primary email
118         try (GigiPreparedStatement ps2 = new GigiPreparedStatement("update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'")) {
119             ps2.setInt(1, owner.getId());
120             ps2.setString(2, address);
121             ps2.execute();
122         }
123     }
124
125     public boolean isVerified() {
126         try (GigiPreparedStatement statmt = new GigiPreparedStatement("SELECT 1 FROM `emailPinglog` WHERE `email`=? AND `uid`=? AND `type`='active' AND `status`='success' AND `when` > (now() - interval '1 months' * ?::INTEGER)")) {
127             statmt.setString(1, address);
128             statmt.setInt(2, owner.getId());
129             statmt.setInt(3, TimeConditions.getInstance().getEmailPingMonths());
130             GigiResultSet e = statmt.executeQuery();
131             return e.next();
132         }
133     }
134
135     public Date getLastPing(boolean onlySuccess) {
136         Date lastExecution;
137         try (GigiPreparedStatement statmt = new GigiPreparedStatement("SELECT MAX(`when`) FROM `emailPinglog` WHERE `email`=? AND `uid`=? AND `type`='active'" + (onlySuccess ? " AND `status`='success'" : ""))) {
138             statmt.setString(1, address);
139             statmt.setInt(2, owner.getId());
140             GigiResultSet e = statmt.executeQuery();
141             if ( !e.next()) {
142                 return null;
143             }
144             lastExecution = e.getTimestamp(1);
145         }
146         return lastExecution;
147     }
148
149     public synchronized void requestReping(Language l) throws IOException, GigiApiException {
150         Date lastExecution = getLastPing(false);
151
152         if (lastExecution != null && lastExecution.getTime() + REPING_MINIMUM_DELAY >= System.currentTimeMillis()) {
153             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)));
154         }
155         ping(l);
156         return;
157     }
158
159     private static ObjectCache<EmailAddress> myCache = new ObjectCache<>();
160
161     public static synchronized EmailAddress getById(int id) throws IllegalArgumentException {
162         EmailAddress em = myCache.get(id);
163         if (em == null) {
164             myCache.put(em = new EmailAddress(id));
165         }
166         return em;
167     }
168
169     public User getOwner() {
170         return owner;
171     }
172
173     public static EmailAddress[] findByAllEmail(String mail) {
174         LinkedList<EmailAddress> results = new LinkedList<EmailAddress>();
175         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")) {
176             ps.setString(1, mail);
177             GigiResultSet rs = ps.executeQuery();
178             while (rs.next()) {
179                 results.add(EmailAddress.getById(rs.getInt(1)));
180             }
181             return results.toArray(new EmailAddress[results.size()]);
182         }
183     }
184 }