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

Introduced SYS_ADMIN account

parent 8341669a
......@@ -14,7 +14,6 @@
* limitations under the License.
**/
package org.genesys2.server.aspect;
import java.util.Arrays;
......@@ -23,8 +22,12 @@ import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.genesys2.server.model.UserRole;
import org.genesys2.server.model.impl.User;
import org.genesys2.server.security.AuthUserDetails;
import org.genesys2.server.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
......@@ -34,37 +37,63 @@ import org.springframework.stereotype.Component;
@Aspect
@Component
public class AsAdminAspect {
private static final Logger LOG = LoggerFactory.getLogger(AsAdminAspect.class);
protected Logger _logger = LoggerFactory.getLogger(getClass());
@Autowired
private UserService userService;
public static PreAuthenticatedAuthenticationToken ADMIN = new PreAuthenticatedAuthenticationToken(
UserRole.ADMINISTRATOR.getLabel(),
null,
Arrays.asList(new SimpleGrantedAuthority(UserRole.ADMINISTRATOR.getName()))
);
// Our copy of the SYS_ADMIN account
private static Authentication SYS_ADMIN = null;
@Around("org.genesys2.server.aspect.SystemArchitecture.allServices()" +
" && @annotation(org.genesys2.server.aspect.AsAdmin)")
@Around("org.genesys2.server.aspect.SystemArchitecture.allServices()" + " && @annotation(org.genesys2.server.aspect.AsAdmin)")
public Object authenticateAsAdmin(ProceedingJoinPoint pjp) throws Throwable {
//store previous version of auth (if any exists)
loadSystemAdminAccount("SYSTEM");
// store previous version of auth (if any exists)
Authentication prevAuth = SecurityContextHolder.getContext().getAuthentication();
boolean swapped = false;
//check whether it's not ADMIN already
if (prevAuth != ADMIN){
//set new role with admin capabilities
SecurityContextHolder.getContext().setAuthentication(ADMIN);
// check whether it's not SYS_ADMIN already
// FIXME check if prevAuth has ADMIN role
if (prevAuth == null || prevAuth.getName() != SYS_ADMIN.getName()) {
LOG.warn("Granting ADMIN privileges");
swapped = true;
// set new role with admin capabilities
SecurityContextHolder.getContext().setAuthentication(SYS_ADMIN);
}
try {
//invoke actual code
// invoke actual code
return pjp.proceed();
} finally {
//restore previous auth (if it is necessary)
if (prevAuth != ADMIN){
if (swapped) {
LOG.warn("Restoring privileges");
SecurityContextHolder.getContext().setAuthentication(prevAuth);
}
}
}
private synchronized void loadSystemAdminAccount(String string) {
if (SYS_ADMIN == null) {
LOG.warn("SYS_ADMIN not loaded. Loading now.");
User sysUser = userService.getSystemUser("SYSTEM");
if (sysUser == null) {
LOG.warn("Temporary SYS_ADMIN account is being used.");
SYS_ADMIN = new PreAuthenticatedAuthenticationToken("SYS_ADMIN", null, Arrays.asList(new SimpleGrantedAuthority(UserRole.ADMINISTRATOR
.getName())));
} else {
LOG.warn("Got SYS_ADMIN account: " + sysUser);
AuthUserDetails userDetails = new AuthUserDetails(sysUser.getEmail(), "", Arrays.asList(new SimpleGrantedAuthority(UserRole.ADMINISTRATOR
.getName())));
userDetails.setUser(sysUser);
SYS_ADMIN = new PreAuthenticatedAuthenticationToken(userDetails, null, userDetails.getAuthorities());
}
}
}
}
......@@ -35,41 +35,34 @@ public class CreateAdminListener extends RunAsAdminListener {
@Override
public void init() throws Exception {
createDefaultAdminUser();
// createSampleUserAccount();
}
private void createDefaultAdminUser() throws UserException {
_logger.info("Checking for at least one account");
if (userService.getCurrentPage(0, 1).getTotalElements() == 0) {
createDefaultAccounts();
}
if (userService.getSystemUser("SYSTEM") == null) {
createAdmin(true, "SYSTEM", null, "SYSTEM");
}
}
private void createDefaultAccounts() throws UserException {
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 {
User user = new User();
user.setEmail("admin@example.com");
user.setPassword("admin");
user.setName("Sample Admin");
user.setSystemAccount(systemAccount);
user.setEmail(email);
user.setPassword(passwd);
user.setName(name);
Set<UserRole> userRoles = new HashSet<UserRole>();
userRoles.add(UserRole.ADMINISTRATOR);
user.setRoles(userRoles);
// user.setUserGroups(userGroupService.getUserGroupList());
userService.addUser(user);
_logger.info("Sample admin 'admin@example.com' has been added successfully");
}
_logger.warn("Admin account for " + email + " has been successfully added.");
}
// private void createSampleUserAccount() throws UserException {
// _logger.info("Checking for user account");
// if (!userService.exists("user@example.com")) {
// User user = new User();
// user.setEmail("user@example.com");
// user.setPassword("user");
// user.setName("Sample User");
// Set<UserRole> userRoles = new HashSet<UserRole>();
// userRoles.add(UserRole.USER);
// user.setRoles(userRoles);
// // user.setUserGroups(userGroupService.getUserGroupList());
//
// userService.addUser(user);
// _logger.info("Sample user has been added successfully");
// }
// }
}
......@@ -73,6 +73,12 @@ public class User extends BusinessModel {
@Column(name = "user_role")
private Set<UserRole> roles = new HashSet<UserRole>();
/**
* System accounts cannot log in through web or otherwise.
*/
@Column(nullable = false, updatable = false, name = "sys")
private boolean systemAccount;
public String getEmail() {
return email;
}
......@@ -139,4 +145,12 @@ public class User extends BusinessModel {
public String toString() {
return "User id=" + id + " email=" + email;
}
public void setSystemAccount(boolean systemAccount) {
this.systemAccount = systemAccount;
}
public boolean isSystemAccount() {
return systemAccount;
}
}
......@@ -14,16 +14,20 @@
* limitations under the License.
**/
package org.genesys2.server.persistence.domain;
import org.genesys2.server.model.impl.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface UserPersistence extends JpaRepository<User, Long>{
public interface UserPersistence extends JpaRepository<User, Long> {
@Query("select u from User u where u.email = ?1 and u.systemAccount = false")
User findByEmail(String email);
@Query("select u from User u where u.email = ?1 and u.systemAccount = true")
User findSystemUser(String username);
}
......@@ -56,4 +56,6 @@ public interface UserService {
@PreAuthorize("hasRole('ADMINISTRATOR') || principal.user.id == #userId")
User updateData(long userId, String name);
User getSystemUser(String string);
}
......@@ -41,6 +41,11 @@ public class SpringSecurityAuditorAware implements AuditorAware<User> {
return null;
}
if (authentication.getPrincipal() instanceof String) {
LOG.warn("Principal '" + authentication.getPrincipal() + " is not a User object.");
return null;
}
return ((AuthUserDetails) authentication.getPrincipal()).getUser();
}
}
\ No newline at end of file
......@@ -128,19 +128,21 @@ public class UserServiceImpl implements UserService {
}
/**
* @deprecated Use {@link #createAccount(String, String, String)} to add
* users
* @param user
* @throws UserException
*/
@Deprecated
@Override
@PreAuthorize("hasRole('ADMINISTRATOR')")
@Transactional(readOnly = false, rollbackFor = NotUniqueUserException.class)
public void addUser(User user) throws UserException {
try {
if (user.isSystemAccount()) {
user.setPassword("THIS-IS-NOT-A-PASSWORD");
} else {
String rawPassword = user.getPassword();
// encrypt password
user.setPassword(passwordEncoder.encode(rawPassword));
}
// save user
userPersistence.save(user);
......@@ -226,6 +228,11 @@ public class UserServiceImpl implements UserService {
return user;
}
@Override
public User getSystemUser(String username) {
return userPersistence.findSystemUser(username);
}
@Override
public User getUserById(long userId) throws UserException {
try {
......
......@@ -21,8 +21,8 @@
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean name="authUserDetailsService" class="org.genesys2.server.security.AuthUserDetailsService" />
<!-- <bean name="authUserDetailsService" class="org.genesys2.server.service.impl.AuthUserDetailsService" />
-->
<!-- Authentication manager -->
<bean name="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
......
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