source: main/trunk/greenstone3/src/java/org/greenstone/gsdl3/service/Authentication.java@ 25722

Last change on this file since 25722 was 25722, checked in by sjm84, 12 years ago

An attempt at fixing the registration problem for systems behind a firewall that does not let them access google services

File size: 30.6 KB
Line 
1package org.greenstone.gsdl3.service;
2
3import java.io.File;
4import java.io.Serializable;
5import java.math.BigInteger;
6import java.security.MessageDigest;
7import java.sql.SQLException;
8import java.util.ArrayList;
9import java.util.HashMap;
10import java.util.UUID;
11import java.util.Vector;
12import java.util.regex.Pattern;
13
14import net.tanesha.recaptcha.ReCaptchaImpl;
15import net.tanesha.recaptcha.ReCaptchaResponse;
16
17import org.greenstone.gsdl3.util.DerbyWrapper;
18import org.greenstone.gsdl3.util.GSXML;
19import org.greenstone.gsdl3.util.UserQueryResult;
20import org.greenstone.gsdl3.util.UserTermInfo;
21import org.w3c.dom.Element;
22import org.w3c.dom.NodeList;
23
24public class Authentication extends ServiceRack
25{
26 //Error codes
27 protected static final int NO_ERROR = 0;
28 protected static final int ERROR_REQUEST_HAS_NO_PARAM_LIST = -1;
29 protected static final int ERROR_NOT_LOGGED_IN = -2;
30 protected static final int ERROR_ADMIN_NOT_LOGGED_IN = -3;
31 protected static final int ERROR_COULD_NOT_GET_USER_INFO = -4;
32 protected static final int ERROR_USERNAME_NOT_SPECIFIED = -5;
33 protected static final int ERROR_REQUESTED_USER_NOT_FOUND = -6;
34 protected static final int ERROR_SQL_EXCEPTION = -7;
35 protected static final int ERROR_INVALID_USERNAME = -8;
36 protected static final int ERROR_INVALID_PASSWORD = -9;
37 protected static final int ERROR_INCORRECT_PASSWORD = -10;
38 protected static final int ERROR_USER_ALREADY_EXISTS = -11;
39 protected static final int ERROR_ADDING_USER = -12;
40 protected static final int ERROR_REMOVING_USER = -13;
41 protected static final int ERROR_CAPTCHA_DOES_NOT_MATCH = -14;
42 protected static final int ERROR_CAPTCHA_MISSING = -15;
43 protected static final int ERROR_NOT_AUTHORISED = -16;
44
45 protected static final HashMap<Integer, String> _errorMessageMap;
46 static
47 {
48 //Corresponding error messages
49 HashMap<Integer, String> errorMessageMap = new HashMap<Integer, String>();
50 errorMessageMap.put(ERROR_REQUEST_HAS_NO_PARAM_LIST, "The list of parameters for this request was empty.");
51 errorMessageMap.put(ERROR_NOT_LOGGED_IN, "You must be logged in to access this page.");
52 errorMessageMap.put(ERROR_ADMIN_NOT_LOGGED_IN, "You must be logged in as an administrator to access this page.");
53 errorMessageMap.put(ERROR_COULD_NOT_GET_USER_INFO, "There was a error getting the user information.");
54 errorMessageMap.put(ERROR_USERNAME_NOT_SPECIFIED, "No username was specified.");
55 errorMessageMap.put(ERROR_REQUESTED_USER_NOT_FOUND, "The requested user was not found in the database.");
56 errorMessageMap.put(ERROR_SQL_EXCEPTION, "There was an SQL exception while accessing the database.");
57 errorMessageMap.put(ERROR_INVALID_USERNAME, "The username specified was invalid.");
58 errorMessageMap.put(ERROR_INVALID_PASSWORD, "The password specified was invalid.");
59 errorMessageMap.put(ERROR_INCORRECT_PASSWORD, "The password specified was incorrect.");
60 errorMessageMap.put(ERROR_USER_ALREADY_EXISTS, "This user already exists and therefore cannot be added.");
61 errorMessageMap.put(ERROR_ADDING_USER, "There was an error adding this user to the database.");
62 errorMessageMap.put(ERROR_REMOVING_USER, "There was an error removing this user from the database.");
63 errorMessageMap.put(ERROR_CAPTCHA_DOES_NOT_MATCH, "The words you entered did not match the image, please try again.");
64 errorMessageMap.put(ERROR_CAPTCHA_MISSING, "The information from the captcha is missing.");
65 errorMessageMap.put(ERROR_NOT_AUTHORISED, "You are not authorised to access this page.");
66
67 _errorMessageMap = errorMessageMap;
68 }
69
70 //Admin-required operations
71 protected static final String LIST_USERS = "ListUsers";
72 protected static final String PERFORM_ADD = "PerformAdd";
73 protected static final String PERFORM_EDIT = "PerformEdit";
74 protected static final String ADD_USER = "AddUser";
75 protected static final String EDIT_USER = "EditUser";
76 protected static final String PERFORM_DELETE_USER = "PerformDeleteUser";
77
78 protected static final ArrayList<String> _adminOpList;
79 static
80 {
81 ArrayList<String> opList = new ArrayList<String>();
82 opList.add(LIST_USERS);
83 opList.add(PERFORM_ADD);
84 opList.add(PERFORM_EDIT);
85 opList.add(EDIT_USER);
86 opList.add(PERFORM_DELETE_USER);
87
88 _adminOpList = opList;
89 }
90
91 //User-required operations
92 protected static final String ACCOUNT_SETTINGS = "AccountSettings";
93 protected static final String PERFORM_ACCOUNT_EDIT = "PerformAccEdit";
94 protected static final String PERFORM_RESET_PASSWORD = "PerformResetPassword";
95 protected static final ArrayList<String> _userOpList;
96 static
97 {
98 ArrayList<String> opList = new ArrayList<String>();
99 opList.add(ACCOUNT_SETTINGS);
100 opList.add(PERFORM_ACCOUNT_EDIT);
101 opList.add(PERFORM_RESET_PASSWORD);
102 opList.addAll(_adminOpList);
103 _userOpList = opList;
104 }
105
106 //Other operations
107 protected static final String REGISTER = "Register";
108 protected static final String PERFORM_REGISTER = "PerformRegister";
109 protected static final String LOGIN = "Login";
110
111 //the services on offer
112 protected static final String AUTHENTICATION_SERVICE = "Authentication";
113 protected static final String GET_USER_INFORMATION_SERVICE = "GetUserInformation";
114
115 protected DerbyWrapper _derbyWrapper = null;
116
117 protected String _recaptchaPrivateKey = null;
118 protected String _recaptchaPublicKey = null;
119
120 /** constructor */
121 public Authentication()
122 {
123 }
124
125 public boolean configure(Element info, Element extra_info)
126 {
127 logger.info("Configuring Authentication...");
128 this.config_info = info;
129
130 // set up Authentication service info - for now just has name and type
131 Element authentication_service = this.doc.createElement(GSXML.SERVICE_ELEM);
132 authentication_service.setAttribute(GSXML.TYPE_ATT, "authen");
133 authentication_service.setAttribute(GSXML.NAME_ATT, AUTHENTICATION_SERVICE);
134 this.short_service_info.appendChild(authentication_service);
135
136 // set up Authentication service info - for now just has name and type
137 Element getUserInformation_service = this.doc.createElement(GSXML.SERVICE_ELEM);
138 getUserInformation_service.setAttribute(GSXML.TYPE_ATT, GSXML.SERVICE_TYPE_PROCESS);
139 getUserInformation_service.setAttribute(GSXML.NAME_ATT, GET_USER_INFORMATION_SERVICE);
140 this.short_service_info.appendChild(getUserInformation_service);
141
142 NodeList recaptchaElems = info.getElementsByTagName("recaptcha");
143
144 for (int i = 0; i < recaptchaElems.getLength(); i++)
145 {
146 Element currentElem = (Element) recaptchaElems.item(i);
147 if (currentElem.getAttribute(GSXML.NAME_ATT) != null && currentElem.getAttribute(GSXML.NAME_ATT).equals("public_key"))
148 {
149 if (currentElem.getAttribute(GSXML.VALUE_ATT) != null)
150 {
151 _recaptchaPublicKey = currentElem.getAttribute(GSXML.VALUE_ATT);
152 }
153 }
154 else if (currentElem.getAttribute(GSXML.NAME_ATT) != null && currentElem.getAttribute(GSXML.NAME_ATT).equals("private_key"))
155 {
156 if (currentElem.getAttribute(GSXML.VALUE_ATT) != null)
157 {
158 _recaptchaPrivateKey = currentElem.getAttribute(GSXML.VALUE_ATT);
159 }
160 }
161 }
162
163 return true;
164 }
165
166 protected Element getServiceDescription(String service_id, String lang, String subset)
167 {
168
169 Element authen_service = this.doc.createElement(GSXML.SERVICE_ELEM);
170
171 if (service_id.equals(AUTHENTICATION_SERVICE))
172 {
173 authen_service.setAttribute(GSXML.TYPE_ATT, "authen");
174 authen_service.setAttribute(GSXML.NAME_ATT, AUTHENTICATION_SERVICE);
175 }
176 else if (service_id.equals(GET_USER_INFORMATION_SERVICE))
177 {
178 authen_service.setAttribute(GSXML.TYPE_ATT, GSXML.SERVICE_TYPE_PROCESS);
179 authen_service.setAttribute(GSXML.NAME_ATT, GET_USER_INFORMATION_SERVICE);
180 }
181 else
182 {
183 return null;
184 }
185
186 if (service_id.equals(AUTHENTICATION_SERVICE) && (subset == null || subset.equals(GSXML.DISPLAY_TEXT_ELEM + GSXML.LIST_MODIFIER)))
187 {
188 authen_service.appendChild(GSXML.createDisplayTextElement(this.doc, GSXML.DISPLAY_TEXT_NAME, getServiceName(service_id, lang)));
189 authen_service.appendChild(GSXML.createDisplayTextElement(this.doc, GSXML.DISPLAY_TEXT_DESCRIPTION, getServiceDescription(service_id, lang)));
190 }
191 return authen_service;
192 }
193
194 protected String getServiceName(String service_id, String lang)
195 {
196 return getTextString(service_id + ".name", lang);
197 }
198
199 protected String getServiceSubmit(String service_id, String lang)
200 {
201 return getTextString(service_id + ".submit", lang);
202 }
203
204 protected String getServiceDescription(String service_id, String lang)
205 {
206 return getTextString(service_id + ".description", lang);
207 }
208
209 protected void addCustomParams(String service, Element param_list, String lang)
210 {
211 }
212
213 protected void createParameter(String name, Element param_list, String lang)
214 {
215 }
216
217 protected Element processGetUserInformation(Element request)
218 {
219 // Create a new (empty) result message
220 Element result = this.doc.createElement(GSXML.RESPONSE_ELEM);
221
222 result.setAttribute(GSXML.FROM_ATT, GET_USER_INFORMATION_SERVICE);
223 result.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_PROCESS);
224
225 Element paramList = (Element) GSXML.getChildByTagName(request, GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
226 if (paramList == null)
227 {
228 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_REQUEST_HAS_NO_PARAM_LIST));
229 return result;
230 }
231
232 HashMap<String, Serializable> params = GSXML.extractParams(paramList, true);
233
234 String username = (String) params.get("username");
235
236 if (username == null)
237 {
238 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_USERNAME_NOT_SPECIFIED));
239 return result;
240 }
241
242 DerbyWrapper dbWrapper = new DerbyWrapper();
243
244 String usersDB_dir = this.site_home + File.separatorChar + "etc" + File.separatorChar + "usersDB";
245 dbWrapper.connectDatabase(usersDB_dir, true);
246
247 UserQueryResult userQueryResult;
248 try
249 {
250 userQueryResult = dbWrapper.findUser(username);
251 Vector<UserTermInfo> terms = userQueryResult.getUserTerms();
252
253 if (terms.size() == 0)
254 {
255 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_REQUESTED_USER_NOT_FOUND));
256 return result;
257 }
258
259 UserTermInfo userInfo = terms.get(0);
260 Element userInfoList = this.doc.createElement(GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
261 result.appendChild(userInfoList);
262
263 Element usernameField = GSXML.createParameter(this.doc, "username", userInfo.username);
264 Element passwordField = GSXML.createParameter(this.doc, "password", userInfo.password);
265 Element groupsField = GSXML.createParameter(this.doc, "groups", userInfo.groups);
266 Element accountStatusField = GSXML.createParameter(this.doc, "accountstatus", userInfo.accountstatus);
267 Element commentField = GSXML.createParameter(this.doc, "comment", userInfo.comment);
268
269 userInfoList.appendChild(usernameField);
270 userInfoList.appendChild(passwordField);
271 userInfoList.appendChild(groupsField);
272 userInfoList.appendChild(accountStatusField);
273 userInfoList.appendChild(commentField);
274 }
275 catch (SQLException ex)
276 {
277 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_SQL_EXCEPTION));
278 ex.printStackTrace();
279 }
280
281 return result;
282 }
283
284 protected Element processAuthentication(Element request)
285 {
286 checkAdminUserExists();
287
288 // Create a new (empty) result message
289 Element result = this.doc.createElement(GSXML.RESPONSE_ELEM);
290 result.setAttribute(GSXML.FROM_ATT, AUTHENTICATION_SERVICE);
291 result.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_PROCESS);
292
293 // Create an Authentication node put into the result
294 Element authenNode = this.doc.createElement(GSXML.AUTHEN_NODE_ELEM);
295 result.appendChild(authenNode);
296 result.appendChild(getCollectList(this.site_home + File.separatorChar + "collect"));
297
298 // Create a service node added into the Authentication node
299 Element serviceNode = this.doc.createElement(GSXML.SERVICE_ELEM);
300 authenNode.appendChild(serviceNode);
301
302 // Get the parameters of the request
303 Element param_list = (Element) GSXML.getChildByTagName(request, GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
304 if (param_list == null)
305 {
306 serviceNode.setAttribute("operation", LOGIN);
307 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_REQUEST_HAS_NO_PARAM_LIST));
308 return result; // Return the empty result
309 }
310 HashMap<String, Serializable> paramMap = GSXML.extractParams(param_list, false);
311 String op = (String) paramMap.get("authpage");
312 serviceNode.setAttribute("operation", op);
313
314 String username = null;
315 String groups = null;
316
317 Element userInformation = (Element) GSXML.getChildByTagName(request, GSXML.USER_INFORMATION_ELEM);
318 if (userInformation == null && _userOpList.contains(op))
319 {
320 serviceNode.setAttribute("operation", LOGIN);
321 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_NOT_LOGGED_IN));
322 return result;
323 }
324
325 if (userInformation != null)
326 {
327 username = userInformation.getAttribute(GSXML.USERNAME_ATT);
328 groups = userInformation.getAttribute(GSXML.GROUPS_ATT);
329 }
330
331 if (username == null && _userOpList.contains(op))
332 {
333 serviceNode.setAttribute("operation", LOGIN);
334 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_NOT_LOGGED_IN));
335 return result;
336 }
337
338 if (_adminOpList.contains(op) && (groups == null || !groups.matches(".*\\badministrator\\b.*")))
339 {
340 serviceNode.setAttribute("operation", LOGIN);
341 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_ADMIN_NOT_LOGGED_IN));
342 return result;
343 }
344
345 if (op.equals(LIST_USERS))
346 {
347 int error = addUserInformationToNode(null, serviceNode);
348 if (error != NO_ERROR)
349 {
350 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
351 }
352 }
353 else if (op.equals(PERFORM_ADD))
354 {
355 String newUsername = (String) paramMap.get("username");
356 String newPassword = (String) paramMap.get("password");
357 String newGroups = (String) paramMap.get("groups");
358 String newStatus = (String) paramMap.get("status");
359 String newComment = (String) paramMap.get("comment");
360 String newEmail = (String) paramMap.get("email");
361
362 //Check the given user name
363 int error;
364 if ((error = checkUsername(newUsername)) != NO_ERROR)
365 {
366 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
367 return result;
368 }
369
370 //Check the given password
371 if ((error = checkPassword(newPassword)) != NO_ERROR)
372 {
373 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
374 return result;
375 }
376
377 newPassword = hashPassword(newPassword);
378
379 error = addUser(newUsername, newPassword, newGroups, newStatus, newComment, newEmail);
380 if (error != NO_ERROR)
381 {
382 serviceNode.setAttribute("operation", ADD_USER);
383 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
384 }
385 else
386 {
387 addUserInformationToNode(null, serviceNode);
388 serviceNode.setAttribute("operation", LIST_USERS);
389 }
390 }
391 else if (op.equals(PERFORM_REGISTER))
392 {
393 String newUsername = (String) paramMap.get("username");
394 String newPassword = (String) paramMap.get("password");
395 String newEmail = (String) paramMap.get("email");
396
397 //Check the given user name
398 int error;
399 if ((error = checkUsername(newUsername)) != NO_ERROR)
400 {
401 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
402 return result;
403 }
404
405 //Check the given password
406 if ((error = checkPassword(newPassword)) != NO_ERROR)
407 {
408 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
409 return result;
410 }
411
412 newPassword = hashPassword(newPassword);
413
414 if (_recaptchaPrivateKey != null)
415 {
416 ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
417 reCaptcha.setPrivateKey(_recaptchaPrivateKey);
418
419 String challenge = (String) paramMap.get("recaptcha_challenge_field");
420 String uResponse = (String) paramMap.get("recaptcha_response_field");
421
422 if (challenge == null || uResponse == null)
423 {
424 serviceNode.setAttribute("operation", REGISTER);
425 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_CAPTCHA_MISSING));
426 return result;
427 }
428
429 ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(request.getAttribute("remoteAddress"), challenge, uResponse);
430
431 if (!reCaptchaResponse.isValid())
432 {
433 serviceNode.setAttribute("operation", REGISTER);
434 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_CAPTCHA_DOES_NOT_MATCH));
435 return result;
436 }
437 }
438
439 error = addUser(newUsername, newPassword, "", "true", "", newEmail);
440 if (error != NO_ERROR)
441 {
442 serviceNode.setAttribute("operation", REGISTER);
443 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
444 }
445 }
446 else if (op.equals(PERFORM_EDIT))
447 {
448 String previousUsername = (String) paramMap.get("prevUsername");
449 String newUsername = (String) paramMap.get("newUsername");
450 String newPassword = (String) paramMap.get("password");
451 String newGroups = (String) paramMap.get("groups");
452 String newStatus = (String) paramMap.get("status");
453 String newComment = (String) paramMap.get("comment");
454 String newEmail = (String) paramMap.get("email");
455
456 //Check the given user name
457 int error;
458 if ((error = checkUsername(newUsername)) != NO_ERROR)
459 {
460 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
461 return result;
462 }
463
464 if (newPassword == null)
465 {
466 newPassword = retrieveDataForUser(previousUsername, "password");
467 }
468 else
469 {
470 //Check the given password
471 if ((error = checkPassword(newPassword)) != NO_ERROR)
472 {
473 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
474 return result;
475 }
476
477 newPassword = hashPassword(newPassword);
478 }
479
480 error = removeUser(previousUsername);
481 if (error != NO_ERROR)
482 {
483 if (error == ERROR_USERNAME_NOT_SPECIFIED)
484 {
485 addUserInformationToNode(null, serviceNode);
486 serviceNode.setAttribute("operation", LIST_USERS);
487 }
488 else
489 {
490 serviceNode.setAttribute("operation", EDIT_USER);
491 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
492 }
493 return result;
494 }
495
496 error = addUser(newUsername, newPassword, newGroups, newStatus, newComment, newEmail);
497 if (error != NO_ERROR)
498 {
499 serviceNode.setAttribute("operation", EDIT_USER);
500 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
501 }
502 else
503 {
504 addUserInformationToNode(null, serviceNode);
505 serviceNode.setAttribute("operation", LIST_USERS);
506 }
507 }
508 else if (op.equals(PERFORM_ACCOUNT_EDIT))
509 {
510 String previousUsername = (String) paramMap.get("prevUsername");
511 String newUsername = (String) paramMap.get("newUsername");
512 String oldPassword = (String) paramMap.get("oldPassword");
513 String newPassword = (String) paramMap.get("newPassword");
514 String newEmail = (String) paramMap.get("newEmail");
515
516 //Make sure the user name does not already exist
517 if (!previousUsername.equals(newUsername) && checkUserExists(newUsername))
518 {
519 addUserInformationToNode(previousUsername, serviceNode);
520 serviceNode.setAttribute("operation", ACCOUNT_SETTINGS);
521 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_USER_ALREADY_EXISTS));
522 return result;
523 }
524
525 String prevPassword = retrieveDataForUser(previousUsername, "password");
526
527 if (newPassword != null)
528 {
529 oldPassword = hashPassword(oldPassword);
530
531 if (oldPassword == null || !oldPassword.equals(prevPassword))
532 {
533 addUserInformationToNode(previousUsername, serviceNode);
534 serviceNode.setAttribute("operation", ACCOUNT_SETTINGS);
535 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_INCORRECT_PASSWORD), "Incorrect Password");
536 return result;
537 }
538
539 //Check the given password
540 int error;
541 if ((error = checkPassword(newPassword)) != NO_ERROR)
542 {
543 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
544 return result;
545 }
546
547 newPassword = hashPassword(newPassword);
548 }
549 else
550 {
551 newPassword = prevPassword;
552 }
553
554 //Check the given user name
555 int error;
556 if ((error = checkUsername(newUsername)) != NO_ERROR)
557 {
558 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
559 return result;
560 }
561
562 String prevGroups = retrieveDataForUser(previousUsername, "groups");
563 String prevStatus = retrieveDataForUser(previousUsername, "status");
564 String prevComment = retrieveDataForUser(previousUsername, "comment");
565
566 error = removeUser(previousUsername);
567 if (error != NO_ERROR)
568 {
569 if (error == ERROR_USERNAME_NOT_SPECIFIED)
570 {
571 addUserInformationToNode(null, serviceNode);
572 serviceNode.setAttribute("operation", LIST_USERS);
573 }
574 else
575 {
576 addUserInformationToNode(previousUsername, serviceNode);
577 serviceNode.setAttribute("operation", ACCOUNT_SETTINGS);
578 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
579 }
580 return result;
581 }
582
583 error = addUser(newUsername, newPassword, prevGroups, prevStatus, prevComment, newEmail);
584 if (error != NO_ERROR)
585 {
586 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
587 }
588
589 addUserInformationToNode(null, serviceNode);
590 serviceNode.setAttribute("operation", LIST_USERS);
591 }
592 else if (op.equals(EDIT_USER))
593 {
594 String editUsername = (String) paramMap.get("username");
595 int error = addUserInformationToNode(editUsername, serviceNode);
596 if (error != NO_ERROR)
597 {
598 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
599 }
600 }
601 else if (op.equals(ACCOUNT_SETTINGS))
602 {
603 String editUsername = (String) paramMap.get("username");
604
605 if (editUsername == null)
606 {
607 serviceNode.setAttribute("operation", "");
608 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_USERNAME_NOT_SPECIFIED));
609 return result;
610 }
611
612 if (!editUsername.equals(username))
613 {
614 serviceNode.setAttribute("operation", LOGIN);
615 GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_NOT_AUTHORISED));
616 return result;
617 }
618 int error = addUserInformationToNode(editUsername, serviceNode);
619 if (error != NO_ERROR)
620 {
621 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
622 }
623 }
624 else if (op.equals(PERFORM_RESET_PASSWORD))
625 {
626 String passwordResetUser = (String) paramMap.get("username");
627
628 String newPassword = UUID.randomUUID().toString();
629 newPassword = newPassword.substring(0, newPassword.indexOf("-"));
630
631 String email = retrieveDataForUser(passwordResetUser, "email");
632 String from = "[email protected]";
633 String host = request.getAttribute("remoteAddress");
634
635 //TODO: FINISH THIS
636 }
637 else if (op.equals(REGISTER))
638 {
639 try
640 {
641 ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
642 reCaptcha.setPrivateKey(_recaptchaPrivateKey);
643 reCaptcha.checkAnswer(request.getAttribute("remoteAddress"), "", "");
644 }
645 catch(Exception ex)
646 {
647 return result;
648 }
649
650 if (_recaptchaPublicKey != null && _recaptchaPrivateKey != null)
651 {
652 Element recaptchaElem = this.doc.createElement("recaptcha");
653 recaptchaElem.setAttribute("publicKey", _recaptchaPublicKey);
654 recaptchaElem.setAttribute("privateKey", _recaptchaPrivateKey);
655 result.appendChild(recaptchaElem);
656 }
657 }
658 else if (op.equals(PERFORM_DELETE_USER))
659 {
660 String usernameToDelete = (String) paramMap.get("username");
661 int error = removeUser(usernameToDelete);
662 if (error != NO_ERROR)
663 {
664 GSXML.addError(this.doc, result, _errorMessageMap.get(error));
665 }
666 addUserInformationToNode(null, serviceNode);
667 serviceNode.setAttribute("operation", LIST_USERS);
668 }
669
670 return result;
671 }
672
673 public int checkUsernameAndPassword(String username, String password)
674 {
675 int uResult = checkUsername(username);
676 int pResult = checkPassword(password);
677
678 return (uResult != NO_ERROR ? uResult : (pResult != NO_ERROR ? pResult : NO_ERROR));
679 }
680
681 public int checkUsername(String username)
682 {
683 //Check the given user name
684 if ((username == null) || (username.length() < 2) || (username.length() > 30) || (!(Pattern.matches("[a-zA-Z0-9//_//.]+", username))))
685 {
686 return ERROR_INVALID_USERNAME;
687 }
688 return NO_ERROR;
689 }
690
691 public int checkPassword(String password)
692 {
693 //Check the given password
694 if ((password == null) || (password.length() < 3) || (password.length() > 8) || (!(Pattern.matches("[\\p{ASCII}]+", password))))
695 {
696 return ERROR_INVALID_PASSWORD;
697 }
698 return NO_ERROR;
699 }
700
701 public static String hashPassword(String password)
702 {
703 String hashedPassword = null;
704 try
705 {
706 MessageDigest digest = MessageDigest.getInstance("SHA-1");
707 digest.reset();
708 hashedPassword = new String(digest.digest(password.getBytes("US-ASCII"))); // toHex after using ASCII charset will result in acceptable length of hex string
709 hashedPassword = toHex(hashedPassword); // this conversion is required to avoid the strange error of login failure on some legal password strings
710 }
711 catch (Exception ex)
712 {
713 ex.printStackTrace();
714 }
715 return hashedPassword;
716 }
717
718 // This method can also be used for printing out the password in hex (in case
719 // the password used the UTF-8 Charset), or the hex values in any unicode string.
720 // From http://stackoverflow.com/questions/923863/converting-a-string-to-hexadecimal-in-java
721 public static String toHex(String arg)
722 {
723 try
724 {
725 return String.format("%x", new BigInteger(arg.getBytes("US-ASCII"))); // set to same charset as used by hashPassword
726 }
727 catch (Exception e)
728 { // UnsupportedEncodingException
729 e.printStackTrace();
730 }
731 return "Unable to print";
732 }
733
734 private void checkAdminUserExists()
735 {
736 if (_derbyWrapper == null)
737 {
738 openDatabase();
739 }
740
741 UserQueryResult userQueryResult = _derbyWrapper.findUser(null, null);
742 closeDatabase();
743
744 if (userQueryResult != null)
745 {
746 Vector userInfo = userQueryResult.users;
747
748 boolean adminFound = false;
749 for (int i = 0; i < userQueryResult.getSize(); i++)
750 {
751 if (((UserTermInfo) userInfo.get(i)).groups != null && ((UserTermInfo) userInfo.get(i)).groups.matches(".*\\badministrator\\b.*"))
752 {
753 adminFound = true;
754 }
755 }
756
757 if (!adminFound)
758 {
759 addUser("admin", "admin", "administrator", "true", "Change the password for this account as soon as possible", "");
760 }
761 }
762
763 closeDatabase();
764 }
765
766 private boolean openDatabase()
767 {
768 _derbyWrapper = new DerbyWrapper();
769
770 // check the usersDb database, if it isn't existing, check the etc dir, create the etc dir if it isn't existing, then create the user database and add a "admin" user
771 String usersDB_dir = this.site_home + File.separatorChar + "etc" + File.separatorChar + "usersDB";
772 File usersDB_file = new File(usersDB_dir);
773 if (!usersDB_file.exists())
774 {
775 String etc_dir = this.site_home + File.separatorChar + "etc";
776 File etc_file = new File(etc_dir);
777 if (!etc_file.exists())
778 {
779 boolean success = etc_file.mkdir();
780 if (!success)
781 {
782 logger.error("Couldn't create the etc dir under " + this.site_home + ".");
783 return false;
784 }
785 }
786 _derbyWrapper.connectDatabase(usersDB_dir, true);
787 _derbyWrapper.createDatabase();
788 }
789 else
790 {
791 _derbyWrapper.connectDatabase(usersDB_dir, false);
792 }
793 return true;
794 }
795
796 private void closeDatabase()
797 {
798 if (_derbyWrapper != null)
799 {
800 _derbyWrapper.closeDatabase();
801 _derbyWrapper = null;
802 }
803 }
804
805 private int addUserInformationToNode(String username, Element serviceNode)
806 {
807 if (_derbyWrapper == null)
808 {
809 openDatabase();
810 }
811
812 UserQueryResult userQueryResult = _derbyWrapper.findUser(username, null);
813 closeDatabase();
814
815 if (userQueryResult != null)
816 {
817 Element user_node = getUserNode(userQueryResult);
818 serviceNode.appendChild(user_node);
819 closeDatabase();
820 return NO_ERROR;
821 }
822
823 closeDatabase();
824 return ERROR_COULD_NOT_GET_USER_INFO;
825 }
826
827 private int removeUser(String username)
828 {
829 if (username == null)
830 {
831 return ERROR_USERNAME_NOT_SPECIFIED;
832 }
833
834 if (_derbyWrapper == null)
835 {
836 openDatabase();
837 }
838
839 boolean success = _derbyWrapper.deleteUser(username);
840 closeDatabase();
841
842 if (success)
843 {
844 return NO_ERROR;
845 }
846
847 return ERROR_REMOVING_USER;
848 }
849
850 private int addUser(String newUsername, String newPassword, String newGroups, String newStatus, String newComment, String newEmail)
851 {
852 if (_derbyWrapper == null)
853 {
854 openDatabase();
855 }
856
857 newGroups = newGroups.replaceAll(" ", "");
858
859 //Check if the user already exists
860 UserQueryResult userQueryResult = _derbyWrapper.findUser(newUsername, null);
861 if (userQueryResult != null)
862 {
863 closeDatabase();
864 return ERROR_USER_ALREADY_EXISTS;
865 }
866 else
867 {
868 System.err.println("ADDING " + newUsername + " " + newPassword);
869 boolean success = _derbyWrapper.addUser(newUsername, newPassword, newGroups, newStatus, newComment, newEmail);
870 if (!success)
871 {
872 closeDatabase();
873 return ERROR_ADDING_USER;
874 }
875 }
876 closeDatabase();
877 return NO_ERROR;
878 }
879
880 private boolean checkUserExists(String username)
881 {
882 if (_derbyWrapper == null)
883 {
884 openDatabase();
885 }
886
887 try
888 {
889 UserQueryResult result = _derbyWrapper.findUser(username);
890
891 if (result != null)
892 {
893 return true;
894 }
895 else
896 {
897 return false;
898 }
899
900 }
901 catch (Exception ex)
902 {
903 return false;
904 }
905 finally
906 {
907 closeDatabase();
908 }
909 }
910
911 private String retrieveDataForUser(String username, String dataType)
912 {
913 if (_derbyWrapper == null)
914 {
915 openDatabase();
916 }
917
918 String password = null;
919
920 try
921 {
922 UserQueryResult result = _derbyWrapper.findUser(username);
923 Vector userInfo = result.users;
924
925 for (int i = 0; i < result.getSize(); i++)
926 {
927 if (dataType.equals("password"))
928 {
929 return ((UserTermInfo) userInfo.get(i)).password;
930 }
931 else if (dataType.equals("groups"))
932 {
933 return ((UserTermInfo) userInfo.get(i)).groups;
934 }
935 else if (dataType.equals("status"))
936 {
937 return ((UserTermInfo) userInfo.get(i)).accountstatus;
938 }
939 else if (dataType.equals("comment"))
940 {
941 return ((UserTermInfo) userInfo.get(i)).comment;
942 }
943 else if (dataType.equals("email"))
944 {
945 return ((UserTermInfo) userInfo.get(i)).email;
946 }
947 }
948 }
949 catch (Exception ex)
950 {
951 ex.printStackTrace();
952 }
953
954 closeDatabase();
955 return password;
956 }
957
958 private Element getUserNode(UserQueryResult userQueryResult)
959 {
960 Element user_list_node = this.doc.createElement(GSXML.USER_NODE_ELEM + "List");
961
962 Vector userInfo = userQueryResult.users;
963
964 for (int i = 0; i < userQueryResult.getSize(); i++)
965 {
966 Element user_node = this.doc.createElement(GSXML.USER_NODE_ELEM);
967 String username = ((UserTermInfo) userInfo.get(i)).username;
968 String groups = ((UserTermInfo) userInfo.get(i)).groups;
969 String accountstatus = ((UserTermInfo) userInfo.get(i)).accountstatus;
970 String comment = ((UserTermInfo) userInfo.get(i)).comment;
971 String email = ((UserTermInfo) userInfo.get(i)).email;
972 user_node.setAttribute("username", username);
973 user_node.setAttribute("groups", groups);
974 user_node.setAttribute("status", accountstatus);
975 user_node.setAttribute("comment", comment);
976 user_node.setAttribute("email", email);
977
978 user_list_node.appendChild(user_node);
979 }
980 return user_list_node;
981 }
982
983 private Element getCollectList(String collect)
984 {
985 Element collect_list_node = this.doc.createElement(GSXML.COLLECTION_ELEM + "List");
986 File[] collect_dir = (new File(collect)).listFiles();
987 if (collect_dir != null && collect_dir.length > 0)
988 {
989 for (int i = 0; i < collect_dir.length; i++)
990 {
991 if (collect_dir[i].isDirectory() && (!collect_dir[i].getName().startsWith(".svn")))
992 {
993 Element collect_node = this.doc.createElement(GSXML.COLLECTION_ELEM);
994 collect_node.setAttribute("name", collect_dir[i].getName());
995 collect_list_node.appendChild(collect_node);
996 }
997 }
998 }
999 return collect_list_node;
1000 }
1001}
Note: See TracBrowser for help on using the repository browser.