Commit 11e10f7d authored by Matija Obreza's avatar Matija Obreza
Browse files

User profiles

parent e9fb3515
......@@ -16,7 +16,6 @@
package org.genesys2.server.model.impl;
import java.util.HashSet;
import java.util.Set;
......@@ -40,93 +39,104 @@ import org.genesys2.server.model.UserRole;
@Table(name = "user")
public class User extends BusinessModel {
/**
/**
*
*/
private static final long serialVersionUID = 4564013753931115445L;
//validation
@NotNull(message = "sample.error.not.null")
@NotEmpty(message = "sample.error.not.empty")
@Email(message = "sample.error.wrong.email")
//hibernate
@Column(name = "email", nullable = false, unique = true)
private String email;
//validation
@NotNull(message = "sample.error.not.null")
@NotEmpty(message = "sample.error.not.empty")
//hibernate
@Column(name = "password", nullable = false)
private String password;
//validation
@NotNull(message = "sample.error.not.null")
@NotEmpty(message = "sample.error.not.empty")
//hibernate
@Column(name = "name", nullable = false)
private String name;
//validation
@ElementCollection
@Enumerated(EnumType.STRING)
@CollectionTable(name="user_role", joinColumns=@JoinColumn(name="user_id"))
@Column(name="user_role")
private Set<UserRole> roles = new HashSet<UserRole>();
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<UserRole> getRoles() {
return roles;
}
public void setRoles(Set<UserRole> roles) {
this.roles = roles;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
if (email != null ? !email.equals(user.email) : user.email != null) return false;
if (name != null ? !name.equals(user.name) : user.name != null) return false;
if (password != null ? !password.equals(user.password) : user.password != null) return false;
if (roles != null ? !roles.equals(user.roles) : user.roles != null) return false;
return true;
}
@Override
public int hashCode() {
int result = email != null ? email.hashCode() : 0;
result = 31 * result + (password != null ? password.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (roles != null ? roles.hashCode() : 0);
return result;
}
// validation
@NotNull(message = "sample.error.not.null")
@NotEmpty(message = "sample.error.not.empty")
@Email(message = "sample.error.wrong.email")
// hibernate
@Column(name = "email", nullable = false, unique = true)
private String email;
// validation
@NotNull(message = "sample.error.not.null")
@NotEmpty(message = "sample.error.not.empty")
// hibernate
@Column(name = "password", nullable = false)
private String password;
// validation
@NotNull(message = "sample.error.not.null")
@NotEmpty(message = "sample.error.not.empty")
// hibernate
@Column(name = "name", nullable = false)
private String name;
// validation
@ElementCollection
@Enumerated(EnumType.STRING)
@CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"))
@Column(name = "user_role")
private Set<UserRole> roles = new HashSet<UserRole>();
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<UserRole> getRoles() {
return roles;
}
public void setRoles(Set<UserRole> roles) {
this.roles = roles;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof User))
return false;
User user = (User) o;
if (email != null ? !email.equals(user.email) : user.email != null)
return false;
if (name != null ? !name.equals(user.name) : user.name != null)
return false;
if (password != null ? !password.equals(user.password) : user.password != null)
return false;
if (roles != null ? !roles.equals(user.roles) : user.roles != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = email != null ? email.hashCode() : 0;
result = 31 * result + (password != null ? password.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (roles != null ? roles.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "User id=" + id + " email=" + email;
}
}
......@@ -14,7 +14,6 @@
* limitations under the License.
**/
package org.genesys2.server.service;
import org.genesys2.server.exception.UserException;
......@@ -25,31 +24,34 @@ import org.springframework.security.access.prepost.PreAuthorize;
public interface UserService {
Page<User> getCurrentPage(int page, int pageSize) throws UserException;
Page<User> getCurrentPage(int page, int pageSize) throws UserException;
@PreAuthorize("hasRole('ADMINISTRATOR')")
void addUser(User user) throws UserException;
@PreAuthorize("hasRole('ADMINISTRATOR')")
void addUser(User user) throws UserException;
@PreAuthorize("hasRole('ADMINISTRATOR') || hasPermission(#user, 'WRITE')")
void updateUser(User user) throws UserException;
@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;
@PreAuthorize("hasRole('ADMINISTRATOR') || principal.user.id == #userId")
void updatePassword(long userId, String rawPassword) throws UserException;
@PreAuthorize("hasRole('ADMINISTRATOR') || hasPermission(#user, 'WRITE')")
void removeUser(User user) throws UserException;
@PreAuthorize("hasRole('ADMINISTRATOR') || hasPermission(#user, 'WRITE')")
void removeUser(User user) throws UserException;
@PreAuthorize("hasRole('ADMINISTRATOR') || hasPermission(#user, 'WRITE')")
void removeUserById(long userId) throws UserException;
@PreAuthorize("hasRole('ADMINISTRATOR') || hasPermission(#user, 'WRITE')")
void removeUserById(long userId) throws UserException;
User getUserByEmail(String email);
User getUserByEmail(String email);
User getUserById(long userId) throws UserException;
User getUserById(long userId) throws UserException;
boolean exists(String username) throws UserException;
boolean exists(String username) throws UserException;
Page<UserWrapper> listWrapped(int startRow, int pageSize) throws UserException;
UserWrapper getWrappedById(long userId) throws UserException;
@PreAuthorize("hasRole('ADMINISTRATOR') || principal.user.id == #userId")
User updateData(long userId, String name);
}
......@@ -35,13 +35,14 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
@Transactional(readOnly = true)
public class UserServiceImpl implements UserService {
@Autowired
......@@ -67,21 +68,21 @@ public class UserServiceImpl implements UserService {
}
}
@Override
@Transactional
public UserWrapper getWrappedById(long userId) throws UserException {
try {
User user = userPersistence.findOne(userId);
@Override
@Transactional
public UserWrapper getWrappedById(long userId) throws UserException {
try {
User user = userPersistence.findOne(userId);
if (user == null) {
throw new NoUserFoundException(userId);
}
if (user == null) {
throw new NoUserFoundException(userId);
}
return transformUserToWrapper(user);
} catch (RuntimeException e) {
throw new UserException(e);
}
}
return transformUserToWrapper(user);
} catch (RuntimeException e) {
throw new UserException(e);
}
}
@Override
public Page<UserWrapper> listWrapped(int startRow, int pageSize) throws UserException {
......@@ -114,7 +115,7 @@ public class UserServiceImpl implements UserService {
}
@Override
@Transactional(rollbackFor = NotUniqueUserException.class)
@Transactional(readOnly = false, rollbackFor = NotUniqueUserException.class)
public void addUser(User user) throws UserException {
try {
String rawPassword = user.getPassword();
......@@ -133,7 +134,7 @@ public class UserServiceImpl implements UserService {
}
@Override
@Transactional(rollbackFor = NotUniqueUserException.class)
@Transactional(readOnly = false, rollbackFor = NotUniqueUserException.class)
public void updateUser(User user) throws UserException {
try {
userPersistence.save(user);
......@@ -147,6 +148,17 @@ public class UserServiceImpl implements UserService {
}
@Override
@PreAuthorize("hasRole('ADMINISTRATOR') || principal.user.id == #userId")
@Transactional(readOnly = false)
public User updateData(long userId, String name) {
User user = userPersistence.findOne(userId);
user.setName(name);
userPersistence.save(user);
return user;
}
@Override
@Transactional(readOnly = false)
public void updatePassword(long userId, String rawPassword) throws UserException {
User user = userPersistence.findOne(userId);
......@@ -157,7 +169,7 @@ public class UserServiceImpl implements UserService {
}
@Override
@Transactional
@Transactional(readOnly = false)
public void removeUser(User user) throws UserException {
try {
userPersistence.delete(user);
......@@ -169,7 +181,7 @@ public class UserServiceImpl implements UserService {
}
@Override
@Transactional(rollbackFor = NoUserFoundException.class)
@Transactional(readOnly = false, rollbackFor = NoUserFoundException.class)
public void removeUserById(long userId) throws UserException {
try {
userPersistence.delete(userId);
......@@ -193,7 +205,6 @@ public class UserServiceImpl implements UserService {
}
@Override
@Transactional
public User getUserById(long userId) throws UserException {
try {
User user = userPersistence.findOne(userId);
......
......@@ -20,7 +20,7 @@ import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.security.AuthUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -56,10 +56,11 @@ public abstract class BaseController {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null && !ANONYMOUS_USER.equals(authentication.getName());
}
protected User getUser() {
protected Long getUserId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication!=null && authentication.getDetails() instanceof User ? (User) authentication.getDetails() : null;
return authentication != null && authentication.getPrincipal() instanceof AuthUserDetails ? ((AuthUserDetails) authentication.getPrincipal()).getUser()
.getId() : null;
}
protected boolean hasRole(String role) {
......
......@@ -128,7 +128,7 @@ public class HtmlController extends BaseController {
}
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword()));
return "redirect:/index.html";
return "redirect:/";
}
} catch (Exception e) {
simpleExceptionHandler(e);
......
......@@ -16,6 +16,7 @@
package org.genesys2.server.servlet.controller;
import org.apache.commons.lang.StringUtils;
import org.genesys2.server.exception.UserException;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.service.ContentService;
......@@ -27,14 +28,13 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Controller which simply handles *.html requests
*/
@Controller("/profile")
@Controller
@RequestMapping("/profile")
public class UserProfileController extends BaseController {
@Autowired
......@@ -54,29 +54,50 @@ public class UserProfileController extends BaseController {
@RequestMapping
public String welcome(ModelMap model) {
User user = getUser();
model.addAttribute("user", user);
User user;
try {
user = userService.getUserById(getUserId());
} catch (UserException e) {
throw new ResourceNotFoundException();
}
return "redirect:/profile/" + user.getEmail();
}
@RequestMapping("/{email:.+}")
public String someProfile(ModelMap model, @PathVariable("email") String email) {
User user = userService.getUserByEmail(email);
if (user == null) {
throw new ResourceNotFoundException();
}
return "/user/me";
model.addAttribute("user", user);
return "/user/profile";
}
@RequestMapping("/edit")
public String edit(ModelMap model) {
welcome(model);
@RequestMapping("/{email:.+}/edit")
@PreAuthorize("hasRole('ADMINISTRATOR') || principal.user.email == #email")
public String edit(ModelMap model, @PathVariable("email") String email) {
System.err.println("email=" +email);
someProfile(model, email);
return "/user/edit";
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/update", method = { RequestMethod.POST })
public String updateMe(ModelMap model, @RequestParam("pwd1") String pwd1, @RequestParam("pwd2") String pwd2) {
User user = getUser();
if (user == null) {
public String updateMe(ModelMap model, @RequestParam("name") String name, @RequestParam("pwd1") String pwd1, @RequestParam("pwd2") String pwd2) {
User user;
try {
user = userService.getUserById(getUserId());
} catch (UserException e1) {
throw new ResourceNotFoundException();
}
if (pwd1 != null) {
userService.updateData(user.getId(), name);
if (StringUtils.isNotBlank(pwd1)) {
if (pwd1.equals(pwd2)) {
try {
_logger.info("Updating password for " + user);
......@@ -85,9 +106,11 @@ public class UserProfileController extends BaseController {
} catch (UserException e) {
_logger.error(e.getMessage(), e);
}
} else {
_logger.warn("Passwords didn't match for " + user);
}
}
return "redirect:/profile";
}
}
......@@ -90,6 +90,11 @@ user.pulldown.administration=Administration
user.pulldown.logout=Logout
user.pulldown.profile=View profile
user.create-new-account=Create an account
user.full-name=Full Name
user.email=E-mail Address
userprofile.page.title=User profile
userprofile.update.title=Update your profile
crop.croplist=Crop list
crop.page.profile.title={0} profile
......
......@@ -49,6 +49,7 @@
<!-- <intercept-url pattern="/data/**" access="isAuthenticated()" /> -->
<sec:intercept-url pattern="/admin/**" access="hasRole('ADMINISTRATOR')" />
<sec:intercept-url pattern="/profile**" access="isAuthenticated()" />
<sec:intercept-url pattern="/oauth/authorize" access="isAuthenticated()" />
<!--Override default login and logout pages -->
......
......@@ -53,7 +53,7 @@
<sec:authorize access="hasRole('ADMINISTRATOR')">
<li><a href="<c:url value="/admin/" />"><spring:message code="user.pulldown.administration" /></a></li>
</sec:authorize>
<li><a href="<c:url value="/profile" />"><spring:message code="user.pulldown.profile" /></a></li>
<li><a href="<c:url value="/profile/${user.username}" />"><spring:message code="user.pulldown.profile" /></a></li>
<li><a href="<c:url value="/logout" />"><spring:message code="user.pulldown.logout" /></a></li>
</ul></li>
</ul>
......
......@@ -9,13 +9,13 @@
<body>
<h1><spring:message code="page.login" /></h1>
<c:if test="${param['error'] ne null}">
<div class="alert alert-error"><spring:message code="login.invalid-credentials"/></div>
<div class="alert alert-danger"><spring:message code="login.invalid-credentials"/></div>
</c:if>
<form role="form" method="POST" action="/login-attempt" class="form-horizontal">
<div class="form-group">
<label for="j_username" class="col-lg-2 control-label"><spring:message code="login.username"/></label>
<div class="col-lg-3">
<input type="text" id="j_username" name="j_username" class="form-control" />
<input type="text" id="j_username" name="j_username" class="form-control grabfocus" />
</div>
</div>
......
......@@ -4,14 +4,26 @@
<html>
<head>
<title><spring:message code="userprofile.page.title" /></title>
<title><spring:message code="userprofile.update.title" /></title>
</head>
<body>
<h1>
<spring:message code="userprofile.page.title" />
<spring:message code="userprofile.update.title" />
</h1>
<form role="form" class="" action="<c:url value="/profile/update" />" method="post">
<form role="form" class="form-horizontal validate" action="<c:url value="/profile/update" />" method="post">
<div class="form-group">
<label for="name" class="col-lg-2 control-label"><spring:message code="registration.full-name" /></label>
<div class="col-lg-3">
<input type="text" id="name" name="name" class="span3 form-control" value="${user.name}" />
</div>
</div>
<div class="form-group">
<label for="email" class="col-lg-2 control-label"><spring:message code="registration.email" /></label>
<div class="col-lg-3">
<input type="text" id="email" name="email" class="span3 form-control" value="${user.email}" />
</div>
</div>
<div class="form-group">
<label for="password" class="col-lg-2 control-label"><spring:message code="registration.password" /></label>
......@@ -29,7 +41,7 @@
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">