Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = null;
Set<Role> roles = new HashSet<Role>();
if (!securityService.isEnabled()) {
user = new UserImpl(Security.ADMIN_USER, Security.SYSTEM_CONTEXT, Security.ADMIN_NAME);
roles.add(SystemRole.SYSTEMADMIN);
roles.add(getLocalRole(site, SystemRole.SYSTEMADMIN));
} else if (auth == null) {
logger.debug("No spring security context available, setting current user to anonymous");
String realm = site != null ? site.getIdentifier() : Security.SYSTEM_CONTEXT;
user = new UserImpl(Security.ANONYMOUS_USER, realm, Security.ANONYMOUS_NAME);
roles.add(SystemRole.GUEST);
roles.add(getLocalRole(site, SystemRole.GUEST));
} else {
Object principal = auth.getPrincipal();
if (principal == null) {
logger.warn("No principal found in spring security context, setting current user to anonymous");
user = new Guest(site.getIdentifier());
roles.add(getLocalRole(site, SystemRole.GUEST));
} else if (principal instanceof SpringSecurityUser) {
user = ((SpringSecurityUser) principal).getUser();
logger.debug("Principal was identified as '{}'", user.getLogin());
} else if (principal instanceof UserDetails) {
UserDetails userDetails = (UserDetails) principal;
user = new UserImpl(userDetails.getUsername());
logger.debug("Principal was identified as '{}'", user.getLogin());
Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
if (authorities != null && authorities.size() > 0) {
for (GrantedAuthority ga : authorities) {