Commit cb89e48e authored by Matija Obreza's avatar Matija Obreza
Browse files

Introducing SecurityContextUtil to getUser()

parent 2acf8143
......@@ -43,6 +43,9 @@ public interface UserService {
@PreAuthorize("hasRole('ADMINISTRATOR') || hasPermission(#user, 'WRITE')")
void removeUserById(long userId) throws UserException;
@PreAuthorize("isAuthenticated()")
User getMe();
User getUserByEmail(String email);
User getUserByUuid(String uuid);
......@@ -61,4 +64,5 @@ public interface UserService {
User getSystemUser(String string);
}
......@@ -19,10 +19,8 @@ package org.genesys2.server.service.audit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.security.AuthUserDetails;
import org.genesys2.spring.SecurityContextUtil;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
@Component("auditorAware")
......@@ -31,21 +29,6 @@ public class SpringSecurityAuditorAware implements AuditorAware<User> {
@Override
public User getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (LOG.isDebugEnabled())
LOG.debug("Got " + authentication);
if (authentication == null || !authentication.isAuthenticated()) {
LOG.info("Not authenticated, returning null as current auditor.");
return null;
}
if (authentication.getPrincipal() instanceof String) {
LOG.warn("Principal '" + authentication.getPrincipal() + " is not a User object.");
return null;
}
return ((AuthUserDetails) authentication.getPrincipal()).getUser();
return SecurityContextUtil.getCurrentUser();
}
}
\ No newline at end of file
......@@ -31,13 +31,12 @@ import org.genesys2.server.persistence.acl.AclSidPersistence;
import org.genesys2.server.security.AuthUserDetails;
import org.genesys2.server.service.AclAssignerService;
import org.genesys2.server.service.UserService;
import org.genesys2.spring.SecurityContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.acls.domain.BasePermission;
import org.springframework.security.acls.model.Permission;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
......@@ -65,10 +64,6 @@ public class AclAssignerServiceImpl implements AclAssignerService {
@Autowired
private AclSidPersistence aclSidPersistence;
protected AuthUserDetails getAuthUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication == null || !(authentication.getPrincipal() instanceof AuthUserDetails) ? null : (AuthUserDetails) authentication.getPrincipal();
}
@Override
public void addCreatorPermissions(AclAwareModel target) {
......@@ -77,13 +72,13 @@ public class AclAssignerServiceImpl implements AclAssignerService {
return;
}
// assume that auth user has already AclSid implemented
AuthUserDetails authUser = getAuthUser();
AuthUserDetails authUser = SecurityContextUtil.getAuthUser();
if (authUser == null) {
LOG.warn("No user in security context, not doing ACL");
return;
}
String uuid = authUser.getUser().getUuid();
String uuid = authUser.getUsername();
// it's ok if it is null
// it can be pre-authorized Admin
......
......@@ -26,16 +26,14 @@ import org.genesys2.server.model.impl.FaoInstitute;
import org.genesys2.server.model.impl.Team;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.persistence.domain.TeamRepository;
import org.genesys2.server.security.AuthUserDetails;
import org.genesys2.server.service.TeamService;
import org.genesys2.server.service.UserService;
import org.genesys2.spring.SecurityContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
......@@ -61,7 +59,7 @@ public class TeamServiceImpl implements TeamService {
@Transactional(readOnly = false)
@PreAuthorize("isAuthenticated()")
public Team addTeam(String name) {
User user = getCurrentUser();
User user = SecurityContextUtil.getCurrentUser();
Team team = new Team();
team.setName(name);
......@@ -114,7 +112,7 @@ public class TeamServiceImpl implements TeamService {
@Transactional(readOnly = false)
@PreAuthorize("isAuthenticated()")
public void removeMe(Team team) {
User user = getCurrentUser();
User user = SecurityContextUtil.getCurrentUser();
boolean removed = team.getMembers().remove(user);
if (removed) {
teamRepository.save(team);
......@@ -123,19 +121,6 @@ public class TeamServiceImpl implements TeamService {
LOG.warn("Could not remove user from team.");
}
private User getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
LOG.warn("No authentication in security context.");
throw new RuntimeException("No authentication object in security context");
}
if (authentication.getPrincipal() instanceof AuthUserDetails) {
return ((AuthUserDetails) authentication.getPrincipal()).getUser();
}
throw new RuntimeException("No User object in security context");
}
@Override
@Transactional(readOnly = false)
......@@ -167,7 +152,7 @@ public class TeamServiceImpl implements TeamService {
@Override
@PreAuthorize("isAuthenticated()")
public List<Team> listMyTeams() {
User user = getCurrentUser();
User user = SecurityContextUtil.getCurrentUser();
return listUserTeams(user);
}
......
......@@ -28,6 +28,7 @@ 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.service.UserService;
import org.genesys2.spring.SecurityContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.EmptyResultDataAccessException;
......@@ -216,6 +217,18 @@ public class UserServiceImpl implements UserService {
}
}
@Override
@PreAuthorize("isAuthenticated()")
public User getMe() {
User user = userPersistence.findByUuid(SecurityContextUtil.getCurrentUser().getUuid());
if (user != null) {
user.getRoles().size();
}
return user;
}
@Override
public User getUserByEmail(String email) {
User user = userPersistence.findByEmail(email);
......@@ -227,7 +240,7 @@ public class UserServiceImpl implements UserService {
user.getRoles().size();
return user;
}
@Override
public User getUserByUuid(String uuid) {
User user = userPersistence.findByUuid(uuid);
......@@ -259,7 +272,7 @@ public class UserServiceImpl implements UserService {
throw new UserException(e);
}
}
@Override
public boolean exists(String username) throws UserException {
return userPersistence.findByEmail(username) != null;
......
......@@ -20,7 +20,6 @@ import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.genesys2.server.security.AuthUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -52,17 +51,6 @@ public abstract class BaseController {
return LocaleContextHolder.getLocale();
}
protected boolean isAuthenticated() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null && !ANONYMOUS_USER.equals(authentication.getName());
}
protected Long getUserId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null && authentication.getPrincipal() instanceof AuthUserDetails ? ((AuthUserDetails) authentication.getPrincipal()).getUser()
.getId() : null;
}
protected boolean hasRole(String role) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
......
......@@ -43,7 +43,7 @@ public class UserProfileController extends BaseController {
@Autowired
private Validator validator;
@Autowired
private TeamService teamService;
......@@ -57,15 +57,10 @@ public class UserProfileController extends BaseController {
private String captchaPublicKey;
@RequestMapping
@PreAuthorize("isAuthenticated()")
public String welcome(ModelMap model) {
User user;
try {
user = userService.getUserById(getUserId());
} catch (UserException e) {
throw new ResourceNotFoundException();
}
return "redirect:/profile/" + user.getEmail();
User user = userService.getMe();
return "redirect:/profile/" + user.getUuid();
}
@RequestMapping("/{uuid:.+}")
......@@ -85,17 +80,15 @@ public class UserProfileController extends BaseController {
@PreAuthorize("hasRole('ADMINISTRATOR') || principal.user.email == #email")
public String edit(ModelMap model, @PathVariable("uuid") String uuid) {
someProfile(model, uuid);
return "/user/edit";
}
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/update", method = { RequestMethod.POST })
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) {
User user = userService.getMe();
if (user == null) {
throw new ResourceNotFoundException();
}
......
......@@ -24,7 +24,6 @@ import java.util.HashMap;
import java.util.Map;
import org.genesys2.server.ServiceEndpoints;
import org.genesys2.server.exception.AuthorizationException;
import org.genesys2.server.exception.NoSuchTokenException;
import org.genesys2.server.servlet.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -63,57 +62,41 @@ public class TokenController extends BaseController {
@RequestMapping(value = ServiceEndpoints.LIST_USER_TOKENS, method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public Collection<OAuth2AccessToken> listTokensForUser(@PathVariable String username) throws Exception {
if (isAuthenticated()) {
OAuth2Authentication principal = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
checkResourceOwner(username, principal);
return enhance(tokenServices.findTokensByUserName(username));
} else {
throw new AuthorizationException(EXCEPTION_NOT_AUTHORIZED);
}
OAuth2Authentication principal = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
checkResourceOwner(username, principal);
return enhance(tokenServices.findTokensByUserName(username));
}
@RequestMapping(value = ServiceEndpoints.REVOKE_USER_TOKEN, method = RequestMethod.DELETE, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public SimpleMessage revokeUserToken(@PathVariable String username, @PathVariable String token) throws Exception {
if (isAuthenticated()) {
OAuth2Authentication principal = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
checkResourceOwner(username, principal);
String tokenValue = getTokenValue(tokenServices.findTokensByUserName(username), token);
if (tokenValue != null && tokenServices.revokeToken(tokenValue)) {
return new SimpleMessage("ok", "user token revoked");
}
throw new NoSuchTokenException("Token not found");
} else {
throw new AuthorizationException(EXCEPTION_NOT_AUTHORIZED);
OAuth2Authentication principal = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
checkResourceOwner(username, principal);
String tokenValue = getTokenValue(tokenServices.findTokensByUserName(username), token);
if (tokenValue != null && tokenServices.revokeToken(tokenValue)) {
return new SimpleMessage("ok", "user token revoked");
}
throw new NoSuchTokenException("Token not found");
}
@RequestMapping(value = ServiceEndpoints.LIST_CLIENT_TOKEN, method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public Collection<OAuth2AccessToken> listTokensForClient(@PathVariable String client) throws Exception {
if (isAuthenticated()) {
OAuth2Authentication principal = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
checkClient(client, principal);
return enhance(tokenServices.findTokensByClientId(client));
} else {
throw new AuthorizationException(EXCEPTION_NOT_AUTHORIZED);
}
OAuth2Authentication principal = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
checkClient(client, principal);
return enhance(tokenServices.findTokensByClientId(client));
}
@RequestMapping(value = ServiceEndpoints.REVOKE_CLIENT_TOKEN, method = RequestMethod.DELETE, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public SimpleMessage revokeClientToken(@PathVariable String client, @PathVariable String token) throws Exception {
if (isAuthenticated()) {
OAuth2Authentication principal = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
checkClient(client, principal);
String tokenValue = getTokenValue(tokenServices.findTokensByClientId(client), token);
if (tokenValue != null && tokenServices.revokeToken(tokenValue)) {
return new SimpleMessage("ok", "client token revoked");
}
throw new NoSuchTokenException("Token not found");
} else {
throw new AuthorizationException(EXCEPTION_NOT_AUTHORIZED);
OAuth2Authentication principal = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
checkClient(client, principal);
String tokenValue = getTokenValue(tokenServices.findTokensByClientId(client), token);
if (tokenValue != null && tokenServices.revokeToken(tokenValue)) {
return new SimpleMessage("ok", "client token revoked");
}
throw new NoSuchTokenException("Token not found");
}
@ExceptionHandler(NoSuchTokenException.class)
......
......@@ -34,7 +34,6 @@ import org.genesys2.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
......@@ -64,9 +63,7 @@ public class UserController extends RestController {
@RequestMapping(value = ServiceEndpoints.ME, method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody
Object getProfile() throws AuthorizationException {
String authenticationName = SecurityContextHolder.getContext().getAuthentication().getName();
LOG.info("OAuth2 request for /me by " + authenticationName);
User user = userService.getUserByEmail(authenticationName);
User user = userService.getMe();
return OAuth2Cleanup.clean(user);
}
......@@ -82,7 +79,6 @@ public class UserController extends RestController {
LOG.info("Creating team " + teamJson);
return OAuth2Cleanup.clean(teamService.addTeam(teamJson.name));
}
@RequestMapping(value = "/me/teams/{teamId}/leave", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
......
package org.genesys2.spring;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.security.AuthUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
public class SecurityContextUtil {
private static final Log LOG = LogFactory.getLog(SecurityContextUtil.class);
public static User getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof AuthUserDetails) {
return ((AuthUserDetails) authentication.getPrincipal()).getUser();
}
LOG.warn("No User in security context.");
return null;
}
public static AuthUserDetails getAuthUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication == null || !(authentication.getPrincipal() instanceof AuthUserDetails) ? null : (AuthUserDetails) authentication.getPrincipal();
}
}
......@@ -19,7 +19,7 @@
<security:authorize ifAllGranted="USER">
<h1><spring:message code="oauth2.confirm-request" /></h1>
<p>
<spring:message code="oauth2.confirm-client" arguments="${user.username},${client.clientId}" htmlEscape="false" />
<spring:message code="oauth2.confirm-client" arguments="${user.user.name},${client.clientId}" htmlEscape="false" />
</p>
<div class="row">
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment