Commit 4ec450be authored by Matija Obreza's avatar Matija Obreza
Browse files

Password policy

parent 7e375120
......@@ -23,6 +23,7 @@ import org.genesys2.server.exception.UserException;
import org.genesys2.server.listener.RunAsAdminListener;
import org.genesys2.server.model.UserRole;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.service.PasswordPolicy.PasswordPolicyException;
import org.genesys2.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
......@@ -47,12 +48,12 @@ public class CreateAdminListener extends RunAsAdminListener {
}
}
private void createDefaultAccounts() throws UserException {
private void createDefaultAccounts() throws UserException, PasswordPolicyException {
createAdmin(true, "SYSTEM", null, "SYSTEM");
createAdmin(false, "admin@example.com", "admin", "First Admin");
}
private void createAdmin(boolean systemAccount, String email, String passwd, String name) throws UserException {
private void createAdmin(boolean systemAccount, String email, String passwd, String name) throws UserException, PasswordPolicyException {
final User user = new User();
user.setSystemAccount(systemAccount);
user.setEmail(email);
......
......@@ -17,6 +17,7 @@
package org.genesys2.server.service;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.service.PasswordPolicy.PasswordPolicyException;
import org.genesys2.server.service.TokenVerificationService.NoSuchVerificationTokenException;
public interface EMailVerificationService {
......@@ -29,5 +30,5 @@ public interface EMailVerificationService {
void validateEMail(String tokenUuid, String key) throws NoSuchVerificationTokenException;
void changePassword(String tokenUuid, String key, String password) throws NoSuchVerificationTokenException;
void changePassword(String tokenUuid, String key, String password) throws NoSuchVerificationTokenException, PasswordPolicyException;
}
/*
* Copyright 2016 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys2.server.service;
/**
* Password policy interface
*/
public interface PasswordPolicy {
/**
* Check that password meets policy requirements
*
* @param password
* @throws PasswordPolicyException
*/
void assureGoodPassword(final String password) throws PasswordPolicyException;
/**
* Thrown when password is not okay
*/
public static final class PasswordPolicyException extends Exception {
private static final long serialVersionUID = -4692900263383479542L;
public PasswordPolicyException(String message) {
super(message);
}
}
}
......@@ -22,6 +22,7 @@ import org.genesys2.server.exception.UserException;
import org.genesys2.server.model.UserRole;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.model.wrapper.UserWrapper;
import org.genesys2.server.service.PasswordPolicy.PasswordPolicyException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
......@@ -32,15 +33,15 @@ public interface UserService {
List<UserRole> listAvailableRoles();
@PreAuthorize("hasRole('ADMINISTRATOR')")
void addUser(User user) throws UserException;
void addUser(User user) throws UserException, PasswordPolicyException;
User createAccount(String email, String initialPassword, String fullName);
User createAccount(String email, String initialPassword, String fullName) throws PasswordPolicyException;
@PreAuthorize("hasRole('ADMINISTRATOR') || hasPermission(#user, 'WRITE')")
void updateUser(User user) throws UserException;
// @PreAuthorize("hasRole('ADMINISTRATOR') || principal.user.id == #userId")
void updatePassword(long userId, String rawPassword) throws UserException;
void updatePassword(long userId, String rawPassword) throws UserException, PasswordPolicyException;
@PreAuthorize("hasRole('ADMINISTRATOR') || hasPermission(#user, 'WRITE')")
void removeUser(User user) throws UserException;
......
......@@ -28,6 +28,7 @@ import org.genesys2.server.model.impl.VerificationToken;
import org.genesys2.server.service.ContentService;
import org.genesys2.server.service.EMailService;
import org.genesys2.server.service.EMailVerificationService;
import org.genesys2.server.service.PasswordPolicy.PasswordPolicyException;
import org.genesys2.server.service.TokenVerificationService;
import org.genesys2.server.service.TokenVerificationService.NoSuchVerificationTokenException;
import org.genesys2.server.service.UserService;
......@@ -101,8 +102,8 @@ public class EMailVerificationServiceImpl implements EMailVerificationService {
}
@Override
@Transactional
public void changePassword(String tokenUuid, String key, String password) throws NoSuchVerificationTokenException {
@Transactional(rollbackFor = Throwable.class)
public void changePassword(String tokenUuid, String key, String password) throws NoSuchVerificationTokenException, PasswordPolicyException {
final VerificationToken consumedToken = tokenVerificationService.consumeToken("email-password", tokenUuid, key);
try {
final User user = userService.getUserByUuid(consumedToken.getData());
......
/*
* Copyright 2016 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.genesys2.server.service.impl;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.genesys2.server.service.PasswordPolicy;
import org.springframework.stereotype.Component;
/**
* Simple password policy
*/
@Component
public class SimplePasswordPolicy implements PasswordPolicy {
private int minLength = 8;
private int maxLength = Integer.MAX_VALUE;
private int minDigits = 1;
private int minSpecialChars = 1;
private static final Pattern DIGITS = Pattern.compile("[0-9]");
private static final Pattern SPECIAL = Pattern.compile("[^0-9a-zA-Z]");
/**
* Check that password follows defined policy.
*/
@Override
public void assureGoodPassword(final String password) throws PasswordPolicyException {
if (password == null) {
throw new PasswordPolicyException("Password cannot be null");
}
if (password.length() < minLength) {
throw new PasswordPolicyException("Password must be at least " + minLength + " characters");
}
if (password.length() > maxLength) {
throw new PasswordPolicyException("Password must be at most " + maxLength + " characters");
}
int digitsCount = 0;
Matcher matcher = DIGITS.matcher(password);
while (matcher.find()) {
digitsCount++;
}
if (digitsCount < minDigits) {
throw new PasswordPolicyException("Password must have at least " + minDigits + " number(s)");
}
int specialCount = 0;
matcher = SPECIAL.matcher(password);
while (matcher.find()) {
specialCount++;
}
if (specialCount < minSpecialChars) {
throw new PasswordPolicyException("Password must have at least " + minSpecialChars + " special character(s)");
}
}
}
......@@ -38,6 +38,8 @@ import org.genesys2.server.model.impl.User;
import org.genesys2.server.model.wrapper.UserWrapper;
import org.genesys2.server.persistence.domain.UserPersistence;
import org.genesys2.server.security.AuthUserDetails;
import org.genesys2.server.service.PasswordPolicy;
import org.genesys2.server.service.PasswordPolicy.PasswordPolicyException;
import org.genesys2.server.service.UserService;
import org.genesys2.spring.SecurityContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -78,6 +80,9 @@ public class UserServiceImpl implements UserService {
private EmailValidator emailValidator = EmailValidator.getInstance();
@Autowired
private PasswordPolicy passwordPolicy;
/**
* Set number of milliseconds for user account lockout
*/
......@@ -124,8 +129,7 @@ public class UserServiceImpl implements UserService {
userPersistence.save(user);
}
final AuthUserDetails userDetails = new AuthUserDetails(user.getUuid(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired,
accountNonLocked, getGrantedAuthorities(user));
final AuthUserDetails userDetails = new AuthUserDetails(user.getUuid(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, getGrantedAuthorities(user));
// set actual DB user for possible further purposes
userDetails.setUser(user);
......@@ -198,7 +202,7 @@ public class UserServiceImpl implements UserService {
@Override
@Transactional(readOnly = false)
public User createAccount(String email, String initialPassword, String fullName) {
public User createAccount(String email, String initialPassword, String fullName) throws PasswordPolicyException {
final User user = new User();
user.setEmail(email);
user.setName(fullName);
......@@ -212,18 +216,17 @@ public class UserServiceImpl implements UserService {
/**
* @param user
* @throws UserException
* @throws PasswordPolicyException
*/
@Override
@PreAuthorize("hasRole('ADMINISTRATOR')")
@Transactional(readOnly = false, rollbackFor = NotUniqueUserException.class)
public void addUser(User user) throws UserException {
public void addUser(User user) throws UserException, PasswordPolicyException {
try {
if (user.isSystemAccount()) {
user.setPassword("THIS-IS-NOT-A-PASSWORD");
} else {
final String rawPassword = user.getPassword();
// encrypt password
user.setPassword(passwordEncoder.encode(rawPassword));
setPassword(user, user.getPassword());
}
// save user
......@@ -271,7 +274,7 @@ public class UserServiceImpl implements UserService {
@Override
@Transactional(readOnly = false)
public void updatePassword(long userId, String rawPassword) throws UserException {
public void updatePassword(long userId, String rawPassword) throws UserException, PasswordPolicyException {
final User user = userPersistence.findOne(userId);
setPassword(user, rawPassword);
userPersistence.save(user);
......@@ -315,7 +318,14 @@ public class UserServiceImpl implements UserService {
setAccountLockLocal(uuid, locked);
}
private void setPassword(User user, String rawPassword) {
/**
* Set the password hash on User
*
* @throws PasswordPolicyException when password is not matching policy
*/
private void setPassword(User user, String rawPassword) throws PasswordPolicyException {
passwordPolicy.assureGoodPassword(rawPassword);
// encrypt password
user.setPassword(passwordEncoder.encode(rawPassword));
}
......@@ -449,7 +459,7 @@ public class UserServiceImpl implements UserService {
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof AuthUserDetails) {
if (! ((AuthUserDetails) principal).getUser().getId().equals(user.getId())) {
if (!((AuthUserDetails) principal).getUser().getId().equals(user.getId())) {
LOG.warn("Not adding role, user != principal");
return;
}
......
......@@ -24,6 +24,7 @@ import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.RandomStringUtils;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.service.PasswordPolicy.PasswordPolicyException;
import org.genesys2.server.service.UserService;
import org.genesys2.server.servlet.util.GoogleOAuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -57,8 +58,11 @@ public class GoogleSocialController extends BaseController {
response.sendRedirect(googleOAuthUtil.getAuthenticationUrl());
}
/**
* @throws PasswordPolicyException Shouldn't happen
*/
@RequestMapping(GoogleOAuthUtil.LOCAL_GOOGLEAUTH_PATH)
public void googleAuth(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
public void googleAuth(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, PasswordPolicyException {
String accessToken = null;
try {
......@@ -77,7 +81,7 @@ public class GoogleSocialController extends BaseController {
final Person userInfo = google.plusOperations().getGoogleProfile();
if (!userService.exists(userInfo.getAccountEmail())) {
final String pwd = RandomStringUtils.randomAlphanumeric(20);
final String pwd = RandomStringUtils.randomAlphanumeric(20) + "!@#$%^&*()<>";
final User user = userService.createAccount(userInfo.getAccountEmail(), pwd, userInfo.getDisplayName());
userService.userEmailValidated(user.getUuid());
}
......
......@@ -162,12 +162,6 @@ public class HtmlController extends BaseController {
return "redirect:/registration.html?error=true";
}
@RequestMapping(value = "/forgot-password")
public String forgotPassword(ModelMap model) {
model.addAttribute("blurp", contentService.getGlobalArticle("user.reset-password-instructions", getLocale()));
return "/user/email";
}
@RequestMapping("/access-denied")
public void accessDenied() {
throw new AccessDeniedException("Spring Security denied access to the resource.");
......
......@@ -16,21 +16,29 @@
package org.genesys2.server.servlet.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.genesys2.server.exception.NotUniqueUserException;
import org.genesys2.server.exception.UserException;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.service.ContentService;
import org.genesys2.server.service.EMailVerificationService;
import org.genesys2.server.service.PasswordPolicy.PasswordPolicyException;
import org.genesys2.server.service.TeamService;
import org.genesys2.server.service.TokenVerificationService.NoSuchVerificationTokenException;
import org.genesys2.server.service.UserService;
import org.genesys2.spring.ResourceNotFoundException;
import org.genesys2.util.ReCaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
......@@ -52,6 +60,15 @@ public class UserProfileController extends BaseController {
@Autowired
private EMailVerificationService emailVerificationService;
@Autowired
private ContentService contentService;
@Value("${captcha.siteKey}")
private String captchaSiteKey;
@Value("${captcha.privateKey}")
private String captchaPrivateKey;
@RequestMapping
@PreAuthorize("isAuthenticated()")
public String welcome(ModelMap model) {
......@@ -130,8 +147,25 @@ public class UserProfileController extends BaseController {
}
}
@RequestMapping(value = "/forgot-password")
public String forgotPassword(ModelMap model) {
model.addAttribute("captchaSiteKey", captchaSiteKey);
model.addAttribute("blurp", contentService.getGlobalArticle("user.reset-password-instructions", getLocale()));
return "/user/email";
}
@RequestMapping(value = "/password/reset", method = RequestMethod.POST)
public String resetPassword(ModelMap model, @RequestParam("email") String email) {
public String resetPassword(ModelMap model, HttpServletRequest req, @RequestParam(value = "g-recaptcha-response", required = false) String response, @RequestParam("email") String email,
RedirectAttributes redirectAttributes) throws IOException {
// Validate the reCAPTCHA
if (!ReCaptchaUtil.isValid(response, req.getRemoteAddr(), captchaPrivateKey)) {
_logger.warn("Invalid captcha.");
redirectAttributes.addFlashAttribute("error", "errors.badCaptcha");
return "redirect:/profile/forgot-password";
}
try {
final User user = userService.getUserByEmail(email);
if (user != null) {
......@@ -139,6 +173,10 @@ public class UserProfileController extends BaseController {
}
return "redirect:/content/user.password-reset-email-sent";
} catch (UsernameNotFoundException e) {
redirectAttributes.addFlashAttribute("error", "errors.no-such-user");
return "redirect:/profile/forgot-password";
}
}
@RequestMapping(value = "/{tokenUuid:.+}/pwdreset", method = RequestMethod.GET)
......@@ -148,24 +186,35 @@ public class UserProfileController extends BaseController {
}
@RequestMapping(value = "/{tokenUuid:.+}/pwdreset", method = RequestMethod.POST)
public String updatePassword(ModelMap model, @PathVariable("tokenUuid") String tokenUuid, @RequestParam(value = "key", required = true) String key,
@RequestParam("password") String password) throws UserException {
public String updatePassword(ModelMap model, @PathVariable("tokenUuid") String tokenUuid, HttpServletRequest req, @RequestParam(value = "g-recaptcha-response", required = false) String response,
@RequestParam(value = "key", required = true) String key, @RequestParam("password") String password, RedirectAttributes redirectAttributes) throws IOException {
// Validate the reCAPTCHA
if (!ReCaptchaUtil.isValid(response, req.getRemoteAddr(), captchaPrivateKey)) {
model.addAttribute("tokenUuid", tokenUuid);
model.addAttribute("key", key);
model.addAttribute("error", "errors.badCaptcha");
return "/user/password";
}
try {
emailVerificationService.changePassword(tokenUuid, key, password);
return "redirect:/content/user.password-reset";
} catch (final NoSuchVerificationTokenException e) {
// Not valid
model.addAttribute("tokenUuid", tokenUuid);
model.addAttribute("error", "error");
return "/user/password";
model.addAttribute("error", "verification.invalid-key");
} catch (PasswordPolicyException e) {
model.addAttribute("tokenUuid", tokenUuid);
model.addAttribute("key", key);
model.addAttribute("error", e.getMessage());
}
return "/user/password";
}
@RequestMapping(value = "/{uuid:.+}/update", method = { RequestMethod.POST })
@PreAuthorize("hasRole('ADMINISTRATOR') || principal.user.uuid == #uuid")
public String update(ModelMap model, @PathVariable("uuid") String uuid, @RequestParam("name") String name, @RequestParam("email") String email,
@RequestParam("pwd1") String pwd1, @RequestParam("pwd2") String pwd2, RedirectAttributes redirectAttributes) {
public String update(ModelMap model, @PathVariable("uuid") String uuid, @RequestParam("name") String name, @RequestParam("email") String email, @RequestParam("pwd1") String pwd1,
@RequestParam("pwd2") String pwd2, RedirectAttributes redirectAttributes) {
final User user = userService.getUserByUuid(uuid);
if (user == null) {
throw new ResourceNotFoundException();
......@@ -188,10 +237,15 @@ public class UserProfileController extends BaseController {
userService.updatePassword(user.getId(), pwd1);
_logger.warn("Password updated for " + user);
} catch (final UserException e) {
redirectAttributes.addFlashAttribute("emailError", e.getMessage());
_logger.error(e.getMessage(), e);
} catch (PasswordPolicyException e) {
redirectAttributes.addFlashAttribute("emailError", e.getMessage());
_logger.error(e.getMessage());
}
} else {
_logger.warn("Passwords didn't match for " + user);
redirectAttributes.addFlashAttribute("emailError", "Passwords didn't match for " + user);
}
}
......
......@@ -21,7 +21,6 @@ import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
......
......@@ -23,6 +23,7 @@ import org.genesys2.server.exception.NotUniqueUserException;
import org.genesys2.server.exception.UserException;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.service.EMailVerificationService;
import org.genesys2.server.service.PasswordPolicy.PasswordPolicyException;
import org.genesys2.server.service.TeamService;
import org.genesys2.server.service.TokenVerificationService.NoSuchVerificationTokenException;
import org.genesys2.server.service.UserService;
......@@ -31,6 +32,7 @@ import org.genesys2.spring.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
......@@ -41,6 +43,7 @@ import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller("adminUsersController")
@RequestMapping(UserProfileController.URLBASE)
@PreAuthorize("hasRole('ADMINISTRATOR')")
public class UserProfileController extends BaseController {
public static final String URLBASE = "/admin/users/";
......@@ -140,7 +143,7 @@ public class UserProfileController extends BaseController {
@RequestMapping(value = "/{tokenUuid:.+}/pwdreset", method = RequestMethod.POST)
public String updatePassword(ModelMap model, @PathVariable("tokenUuid") String tokenUuid, @RequestParam(value = "key", required = true) String key,
@RequestParam("password") String password) throws UserException {
@RequestParam("password") String password, RedirectAttributes redirectAttributes) throws UserException {
try {
emailVerificationService.changePassword(tokenUuid, key, password);
......@@ -148,9 +151,11 @@ public class UserProfileController extends BaseController {
} catch (final NoSuchVerificationTokenException e) {
// Not valid
model.addAttribute("tokenUuid", tokenUuid);
model.addAttribute("error", "error");
return VIEWBASE + "password";
redirectAttributes.addFlashAttribute("error", e.getMessage());
} catch (PasswordPolicyException e) {
redirectAttributes.addFlashAttribute("error", e.getMessage());
}
return VIEWBASE + "password";
}
@RequestMapping(value = "/{uuid:.+}/update", method = { RequestMethod.POST })
......@@ -179,6 +184,12 @@ public class UserProfileController extends BaseController {
_logger.warn("Password updated for " + user);
} catch (final UserException e) {
_logger.error(e.getMessage(), e);
redirectAttributes.addFlashAttribute("error", e.getMessage());
return "redirect:" + URLBASE + user.getUuid() + "/edit";
} catch (PasswordPolicyException e) {
_logger.error(e.getMessage());
redirectAttributes.addFlashAttribute("error", e.getMessage());
return "redirect:" + URLBASE + user.getUuid() + "/edit";
}
} else {
_logger.warn("Passwords didn't match for " + user);
......
......@@ -16,12 +16,16 @@
package org.genesys2.server.servlet.controller.rest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.genesys2.server.exception.NotUniqueUserException;
import org.genesys2.server.exception.UserException;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.service.EMailVerificationService;
import org.genesys2.server.service.OAuth2ClientDetailsService;
import org.genesys2.server.service.PasswordPolicy.PasswordPolicyException;
import org.genesys2.server.service.TeamService;
import org.genesys2.server.service.UserService;
import org.genesys2.server.servlet.controller.rest.model.UserChangedDataJson;
......@@ -34,11 +38,12 @@ import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;