package com.gkhy.exam.common.utils;
|
|
import com.gkhy.exam.common.domain.model.LoginUserDetails;
|
import com.gkhy.exam.common.exception.ApiException;
|
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
|
public class SecurityUtils {
|
|
/**
|
* 是否为管理员
|
*
|
* @param userId 用户ID
|
* @return 结果
|
*/
|
public static boolean isAdmin(Long userId)
|
{
|
return userId != null && 1L == userId;
|
}
|
|
public static boolean adminUser(){
|
if(getLoginUser() == null){
|
return false;
|
}
|
if(getLoginUser().getUser().getId() == 1L){
|
return true;
|
}
|
if(getLoginUser().getUser().getUserType() == 0){
|
return true;
|
}
|
return false;
|
}
|
|
/**
|
* 判断密码是否相同
|
* @param rawPasword 真实密码
|
* @param encodePassword 加密后密码
|
* @return
|
*/
|
public static boolean matchesPassword(String rawPasword,String encodePassword){
|
BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
|
return passwordEncoder.matches(rawPasword,encodePassword);
|
}
|
|
/*
|
**
|
* 用户ID
|
**/
|
public static Long getUserId()
|
{
|
try
|
{
|
return getLoginUser().getUser().getId();
|
}
|
catch (Exception e)
|
{
|
throw new ApiException("获取用户ID异常");
|
}
|
}
|
|
|
|
/*
|
**
|
* 用户ID
|
**/
|
public static Long getCompanyId()
|
{
|
try
|
{
|
return getLoginUser().getUser().getCompanyId();
|
}
|
catch (Exception e)
|
{
|
throw new ApiException("获取用户公司异常");
|
}
|
}
|
|
|
|
/**
|
* 获取用户账户
|
**/
|
public static String getUsername()
|
{
|
try
|
{
|
return getLoginUser().getUser().getUsername();
|
}
|
catch (Exception e)
|
{
|
throw new ApiException("获取用户账户异常");
|
}
|
}
|
|
/**
|
* 获取用户
|
**/
|
public static LoginUserDetails getLoginUser()
|
{
|
try
|
{
|
return (LoginUserDetails) getAuthentication().getPrincipal();
|
}
|
catch (Exception e)
|
{
|
throw new ApiException("获取用户信息异常");
|
}
|
}
|
|
|
/**
|
* 获取用户
|
**/
|
public static LoginUserDetails getLoginUserWithoutError()
|
{
|
try
|
{
|
return (LoginUserDetails) getAuthentication().getPrincipal();
|
}
|
catch (Exception e)
|
{
|
return null;
|
}
|
}
|
|
|
|
/**
|
* 获取Authentication
|
*/
|
public static Authentication getAuthentication()
|
{
|
return SecurityContextHolder.getContext().getAuthentication();
|
}
|
|
/**
|
* 生成BCryptPasswordEncoder密码
|
*
|
* @param password 密码
|
* @return 加密字符串
|
*/
|
public static String encryptPassword(String password)
|
{
|
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
return passwordEncoder.encode(password);
|
}
|
|
|
}
|