]> WPIA git - gigi.git/blob - src/club/wpia/gigi/dbObjects/EmailAddress.java
Merge "upd: remove 'browser install'"
[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
66                 if (isOrgMailAddress()) {
67                     throw new GigiApiException("The entered email address belongs to a registered organisation. Please contact the organisation to issue certificates for this email address.");
68                 }
69
70                 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `emails` SET memid=?, email=?")) {
71                     ps.setInt(1, owner.getId());
72                     ps.setString(2, address);
73                     ps.execute();
74                     id = ps.lastInsertId();
75                 }
76                 myCache.put(this);
77             }
78             ping(l);
79         } catch (IOException e) {
80             e.printStackTrace();
81         }
82     }
83
84     private void ping(Language l) throws IOException {
85         String hash = RandomToken.generateToken(16);
86         try (GigiPreparedStatement statmt = new GigiPreparedStatement("INSERT INTO `emailPinglog` SET `when`=NOW(), `email`=?, `result`='', `uid`=?, `type`='active', `status`='open'::`pingState`, `challenge`=?")) {
87             statmt.setString(1, address);
88             statmt.setInt(2, owner.getId());
89             statmt.setString(3, hash);
90             statmt.execute();
91         }
92
93         MailProbe.sendMailProbe(l, "email", id, hash, address);
94     }
95
96     public int getId() {
97         return id;
98     }
99
100     public String getAddress() {
101         return address;
102     }
103
104     public synchronized boolean isVerifyable(String hash) throws GigiApiException {
105         try (GigiPreparedStatement stmt = new GigiPreparedStatement("SELECT 1 FROM `emailPinglog` WHERE `email`=? AND `uid`=? AND `type`='active' AND `challenge`=? AND `status`='open'::`pingState`")) {
106             stmt.setString(1, address);
107             stmt.setInt(2, owner.getId());
108             stmt.setString(3, hash);
109             return stmt.executeQuery().next();
110         }
111     }
112
113     public synchronized void verify(String hash) throws GigiApiException {
114         try (GigiPreparedStatement stmt = new GigiPreparedStatement("UPDATE `emailPinglog` SET `status`='success'::`pingState` WHERE `email`=? AND `uid`=? AND `type`='active' AND `challenge`=? AND `status`='open'::`pingState`")) {
115             stmt.setString(1, address);
116             stmt.setInt(2, owner.getId());
117             stmt.setString(3, hash);
118             if ( !stmt.executeMaybeUpdate()) {
119                 throw new IllegalArgumentException("Given token could not be found to complete the verification process (Email Ping).");
120             }
121         }
122         // Verify user with that primary email
123         try (GigiPreparedStatement ps2 = new GigiPreparedStatement("update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'")) {
124             ps2.setInt(1, owner.getId());
125             ps2.setString(2, address);
126             ps2.execute();
127         }
128     }
129
130     public boolean isVerified() {
131         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)")) {
132             statmt.setString(1, address);
133             statmt.setInt(2, owner.getId());
134             statmt.setInt(3, TimeConditions.getInstance().getEmailPingMonths());
135             GigiResultSet e = statmt.executeQuery();
136             return e.next();
137         }
138     }
139
140     public Date getLastPing(boolean onlySuccess) {
141         Date lastExecution;
142         try (GigiPreparedStatement statmt = new GigiPreparedStatement("SELECT MAX(`when`) FROM `emailPinglog` WHERE `email`=? AND `uid`=? AND `type`='active'" + (onlySuccess ? " AND `status`='success'" : ""))) {
143             statmt.setString(1, address);
144             statmt.setInt(2, owner.getId());
145             GigiResultSet e = statmt.executeQuery();
146             if ( !e.next()) {
147                 return null;
148             }
149             lastExecution = e.getTimestamp(1);
150         }
151         return lastExecution;
152     }
153
154     public synchronized void requestReping(Language l) throws IOException, GigiApiException {
155         Date lastExecution = getLastPing(false);
156
157         if (lastExecution != null && lastExecution.getTime() + REPING_MINIMUM_DELAY >= System.currentTimeMillis()) {
158             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)));
159         }
160         ping(l);
161         return;
162     }
163
164     private static ObjectCache<EmailAddress> myCache = new ObjectCache<>();
165
166     public static synchronized EmailAddress getById(int id) throws IllegalArgumentException {
167         EmailAddress em = myCache.get(id);
168         if (em == null) {
169             myCache.put(em = new EmailAddress(id));
170         }
171         return em;
172     }
173
174     public User getOwner() {
175         return owner;
176     }
177
178     public static EmailAddress[] findByAllEmail(String mail) {
179         LinkedList<EmailAddress> results = new LinkedList<EmailAddress>();
180         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")) {
181             ps.setString(1, mail);
182             GigiResultSet rs = ps.executeQuery();
183             while (rs.next()) {
184                 results.add(EmailAddress.getById(rs.getInt(1)));
185             }
186             return results.toArray(new EmailAddress[results.size()]);
187         }
188     }
189
190     public boolean isOrgMailAddress() {
191         String[] parts = address.split("@");
192
193         try (GigiPreparedStatement statmt = new GigiPreparedStatement("SELECT 1 FROM `domains` AS d, `organisations` AS o WHERE d.`domain` = ? AND d.`deleted` IS NULL AND d.`memid` = o.`id`")) {
194             statmt.setString(1, parts[parts.length - 1]);
195             GigiResultSet e = statmt.executeQuery();
196             return e.next();
197         }
198     }
199 }