Search in sources :

Example 1 with UserEntity

use of org.usermanagement.dao.entity.UserEntity in project open-kilda by telstra.

the class BaseController method isUserLoggedIn.

/**
 * Returns true if user is logged in, false otherwise.
 *
 * @return true, if is user logged in
 */
protected boolean isUserLoggedIn() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (null != authentication) {
        boolean isValid = (authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken));
        if (isValid) {
            UserEntity userEntity = null;
            if (authentication.getCredentials() instanceof SAMLCredential) {
                NameID nameId = (NameID) authentication.getPrincipal();
                userEntity = userRepository.findByUsernameIgnoreCase(nameId.getValue());
            } else {
                userEntity = (UserEntity) authentication.getPrincipal();
                userEntity = userRepository.findByUserId(userEntity.getUserId());
            }
            if (userEntity != null && userEntity.getStatusEntity().getStatusCode().equalsIgnoreCase(Status.ACTIVE.getCode())) {
                isValid = true;
            } else {
                isValid = false;
            }
        }
        return isValid;
    } else {
        return false;
    }
}
Also used : SAMLCredential(org.springframework.security.saml.SAMLCredential) NameID(org.opensaml.saml2.core.NameID) Authentication(org.springframework.security.core.Authentication) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) UserEntity(org.usermanagement.dao.entity.UserEntity)

Example 2 with UserEntity

use of org.usermanagement.dao.entity.UserEntity in project open-kilda by telstra.

the class LoginController method authenticate.

/**
 * Authenticate.
 *
 * @param username the username
 * @param password the password
 * @param request the request
 * @return the model and view
 */
@RequestMapping(value = "/authenticate", method = RequestMethod.POST)
public ModelAndView authenticate(@RequestParam("username") String username, @RequestParam("password") final String password, final HttpServletRequest request, RedirectAttributes redir) {
    ModelAndView modelAndView = new ModelAndView(IConstants.View.LOGIN);
    String error = null;
    username = username != null ? username.toLowerCase() : null;
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
    CustomWebAuthenticationDetails customWebAuthenticationDetails = new CustomWebAuthenticationDetails(request);
    token.setDetails(customWebAuthenticationDetails);
    try {
        HttpSession sessionOld = request.getSession(false);
        if (sessionOld != null && !sessionOld.isNew()) {
            sessionOld.invalidate();
        }
        Authentication authenticate = authenticationManager.authenticate(token);
        if (authenticate.isAuthenticated()) {
            modelAndView.setViewName(IConstants.View.REDIRECT_HOME);
            UserInfo userInfo = getLoggedInUser(request);
            userService.populateUserInfo(userInfo, username);
            request.getSession(true).setAttribute(IConstants.SESSION_OBJECT, userInfo);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            userService.updateLoginDetail(username);
        } else {
            error = "Login failed; Invalid email or password.";
            LOGGER.warn("Authentication failure for user: '" + username + "'");
            modelAndView.setViewName(IConstants.View.REDIRECT_LOGIN);
        }
    } catch (TwoFaKeyNotSetException e) {
        LOGGER.warn("2 FA Key not set for user: '" + username + "'");
        modelAndView.addObject("username", username);
        modelAndView.addObject("password", password);
        String secretKey = TwoFactorUtility.getBase32EncryptedKey();
        modelAndView.addObject("key", secretKey);
        userService.updateUser2FaKey(username, secretKey);
        modelAndView.addObject("applicationName", applicationName);
        modelAndView.setViewName(IConstants.View.TWO_FA_GENERATOR);
    } catch (OtpRequiredException e) {
        LOGGER.warn("OTP required for user: '" + username + "'");
        modelAndView.addObject("username", username);
        modelAndView.addObject("password", password);
        modelAndView.addObject("applicationName", applicationName);
        modelAndView.setViewName(IConstants.View.OTP);
    } catch (InvalidOtpException e) {
        LOGGER.warn("Authentication code is invalid for user: '" + username + "'");
        error = "Authentication code is invalid";
        modelAndView.addObject("username", username);
        modelAndView.addObject("password", password);
        modelAndView.addObject("applicationName", applicationName);
        if (customWebAuthenticationDetails.isConfigure2Fa()) {
            UserEntity userInfo = userService.getUserByUsername(username);
            modelAndView.addObject("key", userInfo.getTwoFaKey());
            modelAndView.setViewName(IConstants.View.TWO_FA_GENERATOR);
        } else {
            modelAndView.setViewName(IConstants.View.OTP);
        }
    } catch (BadCredentialsException e) {
        LOGGER.warn("Authentication failure", e);
        error = e.getMessage();
        modelAndView.setViewName(IConstants.View.REDIRECT_LOGIN);
    } catch (LockedException e) {
        error = e.getMessage();
        modelAndView.setViewName(IConstants.View.REDIRECT_LOGIN);
    } catch (Exception e) {
        LOGGER.warn("Authentication failure", e);
        error = "Login Failed. Error: " + e.getMessage() + ".";
        modelAndView.setViewName(IConstants.View.REDIRECT_LOGIN);
    }
    if (error != null) {
        redir.addFlashAttribute("error", error);
    }
    return modelAndView;
}
Also used : LockedException(org.springframework.security.authentication.LockedException) CustomWebAuthenticationDetails(org.openkilda.security.CustomWebAuthenticationDetails) HttpSession(javax.servlet.http.HttpSession) ModelAndView(org.springframework.web.servlet.ModelAndView) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) UserInfo(org.usermanagement.model.UserInfo) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) TwoFaKeyNotSetException(org.openkilda.exception.TwoFaKeyNotSetException) OtpRequiredException(org.openkilda.exception.OtpRequiredException) UserEntity(org.usermanagement.dao.entity.UserEntity) OtpRequiredException(org.openkilda.exception.OtpRequiredException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) LockedException(org.springframework.security.authentication.LockedException) InvalidOtpException(org.openkilda.exception.InvalidOtpException) TwoFaKeyNotSetException(org.openkilda.exception.TwoFaKeyNotSetException) Authentication(org.springframework.security.core.Authentication) InvalidOtpException(org.openkilda.exception.InvalidOtpException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with UserEntity

use of org.usermanagement.dao.entity.UserEntity in project open-kilda by telstra.

the class RequestInterceptor method availablePermissions.

private Set<String> availablePermissions(final UserInfo userInfo) {
    Set<String> availablePermissions = new HashSet<>();
    UserEntity userEntity = userRepository.findByUserId(userInfo.getUserId());
    if (userInfo.getUserId() != 1 && userEntity != null && Status.ACTIVE.getStatusEntity().equals(userEntity.getStatusEntity())) {
        Set<String> roles = userInfo.getRoles();
        if (roles != null && roles.size() > 0) {
            List<Role> roleList = roleService.getRoleByName(roles);
            for (Role role : roleList) {
                if (Status.ACTIVE.getStatusEntity().getStatus().equalsIgnoreCase(role.getStatus()) && role.getPermissions() != null) {
                    for (Permission permission : role.getPermissions()) {
                        if (Status.ACTIVE.getStatusEntity().getStatus().equalsIgnoreCase(permission.getStatus())) {
                            availablePermissions.add(permission.getName());
                        }
                    }
                }
            }
        }
    } else {
        List<Permission> permissions = permissionService.getAllPermission(userInfo.getUserId());
        for (Permission permission : permissions) {
            availablePermissions.add(permission.getName());
        }
    }
    userInfo.setPermissions(availablePermissions);
    return availablePermissions;
}
Also used : Role(org.usermanagement.model.Role) Permission(org.usermanagement.model.Permission) UserEntity(org.usermanagement.dao.entity.UserEntity) HashSet(java.util.HashSet)

Example 4 with UserEntity

use of org.usermanagement.dao.entity.UserEntity in project open-kilda by telstra.

the class UserActivityLogService method getActivityLog.

/**
 * Gets the activity log.
 *
 * @param users the users
 * @param activities the activities
 * @param start the start
 * @param end the end
 * @return the activity log
 */
public List<LogInfo> getActivityLog(final List<Long> users, final List<String> activities, final String start, final String end) {
    List<LogInfo> logs = userActivityService.getLogs(users, activities, start, end);
    List<LogInfo> appAdminlogs = new ArrayList<LogInfo>();
    if (!ValidatorUtil.isNull(logs)) {
        Set<Long> userIds = new HashSet<Long>();
        for (LogInfo log : logs) {
            if (serverContext.getRequestContext().getUserId() != 1 && log.getUserId() == 1) {
                appAdminlogs.add(log);
            }
            userIds.add(log.getUserId());
        }
        logs.removeAll(appAdminlogs);
        List<UserEntity> usersList = userRepository.findByUserIdIn(userIds);
        for (int i = 0; i < logs.size(); i++) {
            UserEntity userEntity = getUser(logs.get(i).getUserId(), usersList);
            if (userEntity != null) {
                logs.get(i).setUsername(userEntity.getUsername());
            } else {
                logs.get(i).setUsername(String.valueOf(logs.get(i).getUserId()));
            }
        }
    }
    return logs;
}
Also used : LogInfo(org.openkilda.log.model.LogInfo) ArrayList(java.util.ArrayList) UserEntity(org.usermanagement.dao.entity.UserEntity) HashSet(java.util.HashSet)

Example 5 with UserEntity

use of org.usermanagement.dao.entity.UserEntity in project open-kilda by telstra.

the class UserService method loadUserByUsername.

/*
     * (non-Javadoc)
     *
     * @see org.springframework.security.core.userdetails.UserDetailsService#
     * loadUserByUsername(java. lang.String)
     */
@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
    UserEntity user = userRepository.findByUsernameIgnoreCase(username);
    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(0);
    if (user == null) {
        LOGGER.warn("User with username '" + username + "' not found.");
        throw new UsernameNotFoundException(username);
    }
    return new org.springframework.security.core.userdetails.User(username, user.getPassword(), authorities);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UserEntity(org.usermanagement.dao.entity.UserEntity) HashSet(java.util.HashSet)

Aggregations

UserEntity (org.usermanagement.dao.entity.UserEntity)21 Transactional (org.springframework.transaction.annotation.Transactional)10 RequestValidationException (org.usermanagement.exception.RequestValidationException)8 InvalidOtpException (org.openkilda.exception.InvalidOtpException)6 OtpRequiredException (org.openkilda.exception.OtpRequiredException)6 TwoFaKeyNotSetException (org.openkilda.exception.TwoFaKeyNotSetException)6 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)5 RoleEntity (org.usermanagement.dao.entity.RoleEntity)5 AccessDeniedException (java.nio.file.AccessDeniedException)4 HashMap (java.util.HashMap)4 HashSet (java.util.HashSet)4 UserInfo (org.usermanagement.model.UserInfo)4 Timestamp (java.sql.Timestamp)3 Authentication (org.springframework.security.core.Authentication)3 ArrayList (java.util.ArrayList)2 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)2 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)2 PermissionEntity (org.usermanagement.dao.entity.PermissionEntity)2 StatusEntity (org.usermanagement.dao.entity.StatusEntity)2 Permission (org.usermanagement.model.Permission)2