]> WPIA git - gigi.git/blob - src/org/cacert/gigi/util/Notary.java
cba93aba8ee78f92a6b40b00252d8bc7c55eaf6b
[gigi.git] / src / org / cacert / gigi / util / Notary.java
1 package org.cacert.gigi.util;
2
3 import java.io.IOException;
4 import java.text.ParseException;
5 import java.util.Calendar;
6 import java.util.Date;
7 import java.util.GregorianCalendar;
8 import java.util.HashMap;
9 import java.util.Map;
10
11 import org.cacert.gigi.GigiApiException;
12 import org.cacert.gigi.database.GigiPreparedStatement;
13 import org.cacert.gigi.database.GigiResultSet;
14 import org.cacert.gigi.dbObjects.Assurance.AssuranceType;
15 import org.cacert.gigi.dbObjects.Group;
16 import org.cacert.gigi.dbObjects.Name;
17 import org.cacert.gigi.dbObjects.User;
18 import org.cacert.gigi.localisation.Language;
19 import org.cacert.gigi.output.ArrayIterable;
20 import org.cacert.gigi.output.DateSelector;
21 import org.cacert.gigi.output.template.MailTemplate;
22 import org.cacert.gigi.output.template.SprintfCommand;
23
24 public class Notary {
25
26     // minimum date range between 2 verifications of the RA-Agent to the same
27     // Applicant
28     public final static int LIMIT_DAYS_VERIFICATION = TimeConditions.getInstance().getVerificationLimitDays();
29
30     // maximum date range from date when the verification took place and the
31     // entering to the system
32     public final static int LIMIT_MAX_MONTHS_VERIFICATION = TimeConditions.getInstance().getVerificationMaxAgeMonths();
33
34     public static void writeUserAgreement(User member, String document, String method, String comment, boolean active, int secmemid) {
35         try (GigiPreparedStatement q = new GigiPreparedStatement("INSERT INTO `user_agreements` SET `memid`=?, `secmemid`=?," + " `document`=?,`date`=NOW(), `active`=?,`method`=?,`comment`=?")) {
36             q.setInt(1, member.getId());
37             q.setInt(2, secmemid);
38             q.setString(3, document);
39             q.setBoolean(4, active);
40             q.setString(5, method);
41             q.setString(6, comment);
42             q.execute();
43         }
44     }
45
46     public static boolean checkAssuranceIsPossible(User assurer, Name target) {
47         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT 1 FROM `notary` where `to`=? and `from`=? and `method` = ? ::`notaryType` AND `deleted` IS NULL AND `when` > (now() - interval '1 days' * ?)")) {
48             ps.setInt(1, target.getId());
49             ps.setInt(2, assurer.getId());
50             ps.setString(3, AssuranceType.FACE_TO_FACE.getDescription());
51             ps.setInt(4, LIMIT_DAYS_VERIFICATION);
52             GigiResultSet rs = ps.executeQuery();
53             return !rs.next();
54         }
55     }
56
57     public static final Group ASSURER_BLOCKED = Group.getByString("blockedassurer");
58
59     public static final Group ASSUREE_BLOCKED = Group.getByString("blockedassuree");
60
61     /**
62      * This method assures another user.
63      * 
64      * @see User#canAssure() (for assurer)
65      * @see #checkAssuranceIsPossible(User, User) (for assurer or assuree)
66      * @param assurer
67      *            the person that wants to assure
68      * @param assuree
69      *            the person that should be assured
70      * @param assureeName
71      *            the Name that was personally verified
72      * @param dob
73      *            the Date of birth that the assurer verified
74      * @param awarded
75      *            the points that should be awarded in total
76      * @param location
77      *            the location where the assurance took place
78      * @param date
79      *            the date when the assurance took place
80      * @throws GigiApiException
81      *             if the assurance fails (for various reasons)
82      */
83     public synchronized static void assure(User assurer, User assuree, Name assureeName, DayDate dob, int awarded, String location, String date, AssuranceType type) throws GigiApiException {
84         may(assurer, assuree, AssuranceType.FACE_TO_FACE);
85         GigiApiException gae = new GigiApiException();
86         if ( !gae.isEmpty()) {
87             throw gae;
88         }
89         if (date == null || date.equals("")) {
90             gae.mergeInto(new GigiApiException("You must enter the date when you met the assuree."));
91         } else {
92             try {
93                 Date d = DateSelector.getDateFormat().parse(date);
94                 Calendar gc = GregorianCalendar.getInstance();
95                 gc.setTimeInMillis(System.currentTimeMillis());
96                 gc.add(Calendar.HOUR_OF_DAY, 12);
97                 if (d.getTime() > gc.getTimeInMillis()) {
98                     gae.mergeInto(new GigiApiException("You must not enter a date in the future."));
99                 }
100                 gc.setTimeInMillis(System.currentTimeMillis());
101                 gc.add(Calendar.MONTH, -LIMIT_MAX_MONTHS_VERIFICATION);
102                 if (d.getTime() < gc.getTimeInMillis()) {
103                     gae.mergeInto(new GigiApiException(SprintfCommand.createSimple("Verifications older than {0} months are not accepted.", LIMIT_MAX_MONTHS_VERIFICATION)));
104                 }
105             } catch (ParseException e) {
106                 gae.mergeInto(new GigiApiException("You must enter the date in this format: YYYY-MM-DD."));
107             }
108         }
109         // check location, min 3 characters
110         if (location == null || location.equals("")) {
111             gae.mergeInto(new GigiApiException("You failed to enter a location of your meeting."));
112         } else if (location.length() <= 2) {
113             gae.mergeInto(new GigiApiException("You must enter a location with at least 3 characters eg town and country."));
114         }
115         synchronized (assuree) {
116             if (assurer.getId() == assuree.getId()) {
117                 throw new GigiApiException("You cannot verify yourself.");
118             }
119             if (assureeName.getOwner() != assuree) {
120                 throw new GigiApiException("Internal error, name does not belong to applicant.");
121             }
122             if ( !assurer.canAssure()) {
123                 throw new GigiApiException("You are not an RA-Agent.");
124             }
125
126             if ( !checkAssuranceIsPossible(assurer, assureeName)) {
127                 gae.mergeInto(new GigiApiException(SprintfCommand.createSimple("You have already verified this applicant within the last {0} days.", LIMIT_DAYS_VERIFICATION)));
128             }
129
130             if ( !assuree.getDoB().equals(dob)) {
131                 gae.mergeInto(new GigiApiException("The person you are assuring changed his personal details."));
132             }
133
134             if (awarded < 0) {
135                 gae.mergeInto(new GigiApiException("The points you are trying to award are out of range."));
136             } else {
137                 if (type == AssuranceType.NUCLEUS) {
138                     if (awarded > 50) {
139                         gae.mergeInto(new GigiApiException("The points you are trying to award are out of range."));
140                     }
141                 } else {
142                     if (awarded > assurer.getMaxAssurePoints()) {
143                         gae.mergeInto(new GigiApiException("The points you are trying to award are out of range."));
144                     }
145                 }
146             }
147
148             if ( !gae.isEmpty()) {
149                 throw gae;
150             }
151
152             if (type == AssuranceType.FACE_TO_FACE) {
153                 assureF2F(assurer, assuree, assureeName, awarded, location, date);
154             } else if (type == AssuranceType.NUCLEUS) {
155                 assureNucleus(assurer, assuree, assureeName, awarded, location, date);
156             } else if (type == AssuranceType.TTP_ASSISTED) {
157                 assureTTP(assurer, assuree, assureeName, awarded, location, date);
158             } else {
159                 throw new GigiApiException(SprintfCommand.createSimple("Unknown Assurance type: {0}", type.toString()));
160             }
161             assurer.invalidateMadeAssurances();
162             assuree.invalidateReceivedAssurances();
163         }
164     }
165
166     private static void assureF2F(User assurer, User assuree, Name name, int awarded, String location, String date) throws GigiApiException {
167         may(assurer, assuree, AssuranceType.FACE_TO_FACE);
168         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?")) {
169             ps.setInt(1, assurer.getId());
170             ps.setInt(2, name.getId());
171             ps.setInt(3, awarded);
172             ps.setString(4, location);
173             ps.setString(5, date);
174             ps.execute();
175         }
176     }
177
178     private static void assureTTP(User assurer, User assuree, Name name, int awarded, String location, String date) throws GigiApiException {
179         may(assurer, assuree, AssuranceType.TTP_ASSISTED);
180         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?, `method`='TTP-Assisted'")) {
181             ps.setInt(1, assurer.getId());
182             ps.setInt(2, name.getId());
183             ps.setInt(3, awarded);
184             ps.setString(4, location);
185             ps.setString(5, date);
186             ps.execute();
187             assuree.revokeGroup(assurer, Group.TTP_APPLICANT);
188         }
189     }
190
191     public static void may(User assurer, User assuree, AssuranceType t) throws GigiApiException {
192         if (assuree.isInGroup(ASSUREE_BLOCKED)) {
193             throw new GigiApiException("The applicant is blocked.");
194         }
195         if (assurer.isInGroup(ASSURER_BLOCKED)) {
196             throw new GigiApiException("The RA Agent is blocked.");
197         }
198
199         if (t == AssuranceType.NUCLEUS) {
200             if ( !assurer.isInGroup(Group.NUCLEUS_ASSURER)) {
201                 throw new GigiApiException("RA Agent needs to be Nucleus RA Agent.");
202             }
203             return;
204         } else if (t == AssuranceType.TTP_ASSISTED) {
205             if ( !assurer.isInGroup(Group.TTP_ASSURER)) {
206                 throw new GigiApiException("RA Agent needs to be TTP RA Agent.");
207             }
208             if ( !assuree.isInGroup(Group.TTP_APPLICANT)) {
209                 throw new GigiApiException("Applicant needs to be TTP Applicant.");
210             }
211             return;
212         } else if (t == AssuranceType.FACE_TO_FACE) {
213             return;
214         }
215         throw new GigiApiException("Verification type not possible.");
216     }
217
218     private static void assureNucleus(User assurer, User assuree, Name name, int awarded, String location, String date) throws GigiApiException {
219         may(assurer, assuree, AssuranceType.NUCLEUS);
220         // Do up to 35 points as f2f
221         int f2fPoints = Math.min(assurer.getMaxAssurePoints(), awarded);
222         assureF2F(assurer, assuree, name, f2fPoints, location, date);
223
224         awarded -= f2fPoints;
225         if (awarded <= 0) {
226             return;
227         }
228
229         // Assure remaining points as "Nucleus Bonus"
230         // Valid for 4 Weeks = 28 days
231         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?, `method`='Nucleus Bonus', `expire` = CURRENT_TIMESTAMP + interval '28 days'")) {
232             ps.setInt(1, assurer.getId());
233             ps.setInt(2, name.getId());
234             ps.setInt(3, awarded);
235             ps.setString(4, location);
236             ps.setString(5, date);
237             ps.execute();
238         }
239     }
240
241     public synchronized static void assureAll(User assurer, User assuree, DayDate dob, int awarded, String location, String date, AssuranceType type, Name[] toAssure) throws GigiApiException {
242         boolean[] hadLessThan50Points = new boolean[toAssure.length];
243         boolean hadTotalLessThan100 = assuree.getAssurancePoints() < 100;
244         for (int i = 0; i < toAssure.length; i++) {
245             hadLessThan50Points[i] = toAssure[i].getAssurancePoints() < 50;
246
247             assure(assurer, assuree, toAssure[i], dob, awarded, location, date, type);
248         }
249         sendVerificationNotificationApplicant(assurer, assuree, toAssure, awarded, hadLessThan50Points, hadTotalLessThan100);
250     }
251
252     private static final MailTemplate verificationEntered = new MailTemplate(Notary.class.getResource("VerificationEntered.templ"));
253
254     private static void sendVerificationNotificationApplicant(User assurer, User assuree, Name[] toAssure, final int awarded, final boolean[] hadLessThan50Points, boolean hadTotalLessThan100) {
255         HashMap<String, Object> mailVars = new HashMap<>();
256         mailVars.put("agent", assurer.getPreferredName().toString());
257         mailVars.put("names", new ArrayIterable<Name>(toAssure) {
258
259             @Override
260             public void apply(Name t, Language l, Map<String, Object> vars) {
261                 int totalVP = t.getAssurancePoints();
262                 vars.put("name", t.toString());
263                 vars.put("points", Integer.toString(awarded));
264                 vars.put("total", totalVP);
265                 if (totalVP < 50) {
266                     vars.put("rem", (50 - totalVP));
267                     vars.remove("gotGreater");
268                 } else if (hadLessThan50Points[i]) {
269                     vars.put("gotGreater", true);
270                     vars.remove("rem");
271                 }
272             }
273
274         });
275
276         int grandTotalVP = assuree.getAssurancePoints();
277         if (grandTotalVP >= 50 && grandTotalVP < 100) {
278             mailVars.put("remAll", (100 - grandTotalVP));
279             mailVars.remove("gotGreaterAll");
280         } else if (hadTotalLessThan100) {
281             mailVars.put("gotGreaterAll", true);
282             mailVars.remove("remAll");
283         }
284         try {
285             verificationEntered.sendMail(Language.getInstance(assuree.getPreferredLocale()), mailVars, assuree.getEmail());
286         } catch (IOException e) {
287             e.printStackTrace();
288         }
289     }
290 }