1 package club.wpia.gigi.dbObjects;
3 import java.io.IOException;
5 import java.util.LinkedList;
6 import java.util.Locale;
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;
18 public class EmailAddress implements IdCachable, Verifyable {
20 public static final int REPING_MINIMUM_DELAY = 5 * 60 * 1000;
22 private String address;
28 private EmailAddress(int id) {
29 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `memid`, `email` FROM `emails` WHERE `id`=? AND `deleted` IS NULL")) {
32 GigiResultSet rs = ps.executeQuery();
34 throw new IllegalArgumentException("Invalid email id " + id);
37 owner = User.getById(rs.getInt(1));
38 address = rs.getString(2);
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.");
47 this.address = address;
49 insert(Language.getInstance(mailLocale));
52 private void insert(Language l) throws GigiApiException {
54 synchronized (EmailAddress.class) {
56 throw new IllegalStateException("already inserted.");
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();
62 throw new GigiApiException("The email address is already known to the system.");
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.");
70 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `emails` SET memid=?, email=?")) {
71 ps.setInt(1, owner.getId());
72 ps.setString(2, address);
74 id = ps.lastInsertId();
79 } catch (IOException e) {
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);
93 MailProbe.sendMailProbe(l, "email", id, hash, address);
100 public String getAddress() {
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();
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).");
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);
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();
140 public Date getLastPing(boolean onlySuccess) {
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();
149 lastExecution = e.getTimestamp(1);
151 return lastExecution;
154 public synchronized void requestReping(Language l) throws IOException, GigiApiException {
155 Date lastExecution = getLastPing(false);
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)));
164 private static ObjectCache<EmailAddress> myCache = new ObjectCache<>();
166 public static synchronized EmailAddress getById(int id) throws IllegalArgumentException {
167 EmailAddress em = myCache.get(id);
169 myCache.put(em = new EmailAddress(id));
174 public User getOwner() {
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();
184 results.add(EmailAddress.getById(rs.getInt(1)));
186 return results.toArray(new EmailAddress[results.size()]);
190 public boolean isOrgMailAddress() {
191 String[] parts = address.split("@");
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();