¶Ô±ÈÐÂÎļþ |
| | |
| | | package com.ruoyi.common.utils; |
| | | |
| | | import org.springframework.security.core.Authentication; |
| | | import org.springframework.security.core.context.SecurityContextHolder; |
| | | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; |
| | | import com.ruoyi.common.constant.HttpStatus; |
| | | import com.ruoyi.common.core.domain.model.LoginUser; |
| | | import com.ruoyi.common.exception.CustomException; |
| | | |
| | | /** |
| | | * å®å
¨æå¡å·¥å
·ç±» |
| | | * |
| | | * @author ruoyi |
| | | */ |
| | | public class SecurityUtils |
| | | { |
| | | /** |
| | | * è·åç¨æ·è´¦æ· |
| | | **/ |
| | | public static String getUsername() |
| | | { |
| | | try |
| | | { |
| | | return getLoginUser().getUsername(); |
| | | } |
| | | catch (Exception e) |
| | | { |
| | | throw new CustomException("è·åç¨æ·è´¦æ·å¼å¸¸", HttpStatus.UNAUTHORIZED); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * è·åç¨æ· |
| | | **/ |
| | | public static LoginUser getLoginUser() |
| | | { |
| | | try |
| | | { |
| | | return (LoginUser) getAuthentication().getPrincipal(); |
| | | } |
| | | catch (Exception e) |
| | | { |
| | | throw new CustomException("è·åç¨æ·ä¿¡æ¯å¼å¸¸", HttpStatus.UNAUTHORIZED); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * è·å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); |
| | | } |
| | | |
| | | /** |
| | | * 夿å¯ç æ¯å¦ç¸å |
| | | * |
| | | * @param rawPassword çå®å¯ç |
| | | * @param encodedPassword å å¯åå符 |
| | | * @return ç»æ |
| | | */ |
| | | public static boolean matchesPassword(String rawPassword, String encodedPassword) |
| | | { |
| | | BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); |
| | | return passwordEncoder.matches(rawPassword, encodedPassword); |
| | | } |
| | | |
| | | /** |
| | | * æ¯å¦ä¸ºç®¡çå |
| | | * |
| | | * @param userId ç¨æ·ID |
| | | * @return ç»æ |
| | | */ |
| | | public static boolean isAdmin(Long userId) |
| | | { |
| | | return userId != null && 1L == userId; |
| | | } |
| | | } |