/* * Copyright 2019-2020 Zheng Jie * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.zhengjie.utils; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import lombok.extern.slf4j.Slf4j; import me.zhengjie.base.QueryPageParams; import me.zhengjie.exception.BadRequestException; import me.zhengjie.utils.enums.DataScopeEnum; import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.text.SimpleDateFormat; import java.util.*; /** * 获取当前登录的用户 * @author Zheng Jie * @date 2019-01-17 */ @Slf4j public class SecurityUtils { /** * 获取当前登录的用户 * @return UserDetails */ public static UserDetails getCurrentUser() { UserDetailsService userDetailsService = SpringContextHolder.getBean(UserDetailsService.class); return userDetailsService.loadUserByUsername(getCurrentUsername()); } /** * 获取系统用户名称 * * @return 系统用户名称 */ public static String getCurrentUsername() { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { throw new BadRequestException(HttpStatus.UNAUTHORIZED, "当前登录状态过期"); } if (authentication.getPrincipal() instanceof UserDetails) { UserDetails userDetails = (UserDetails) authentication.getPrincipal(); return userDetails.getUsername(); } throw new BadRequestException(HttpStatus.UNAUTHORIZED, "找不到当前登录的信息"); } /** * 获取系统用户ID * @return 系统用户ID */ public static String getCurrentUserId() { UserDetails userDetails = getCurrentUser(); return new JSONObject(new JSONObject(userDetails).get("user")).get("id", String.class); } /** * 获取当前用户的数据权限 * @return / */ public static List getCurrentUserDataScope(){ UserDetails userDetails = getCurrentUser(); JSONArray array = JSONUtil.parseArray(new JSONObject(userDetails).get("dataScopes")); return JSONUtil.toList(array,Long.class); } /** * 获取数据权限级别 * @return 级别 */ public static String getDataScopeType() { List dataScopes = getCurrentUserDataScope(); if(dataScopes.size() != 0){ return ""; } return DataScopeEnum.ALL.getValue(); } /** * 验证API访问权限 */ public static void CheckApiAuth(QueryPageParams params) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); if (request != null) { String accesstoken = request.getHeader("X_YT_ACCESS_TOKEN"); String token = "DMERPYT!@#$QWER2021+{:>"; if (params == null || StringUtils.isBlank(params.getTimestamp()) || StringUtils.isBlank(params.getNonce()) || StringUtils.isBlank(accesstoken)) { throw new BadRequestException(HttpStatus.UNAUTHORIZED, "认证失败"); } String[] arr = {token, params.getTimestamp(), params.getNonce()}; Arrays.sort(arr); String str = ""; for (int i = 0; i < arr.length; i++) { str += arr[i]; } String newtoken = EncryptUtils.sha1(str); if (!accesstoken.equals(newtoken)) { throw new BadRequestException(HttpStatus.UNAUTHORIZED, "认证失败"); } } } /** * 根据key获取token */ public static Map getToken(String key){ //获取11位随机数 double rand = Math.random(); String randStr = String.valueOf(rand).replace("0.", ""); String nonce = randStr.substring(0, 11); System.out.println("nonce:"+nonce); //获取当前时间 SimpleDateFormat sdf = new SimpleDateFormat(); sdf.applyPattern("yyyy-MM-dd HH:mm"); Date date = new Date(); String timestamp =sdf.format(date); System.out.println("timestamp:"+timestamp); //排序 String[] arr = {key, timestamp, nonce}; Arrays.sort(arr); //获取token String str = ""; for (int i = 0; i < arr.length; i++) { str += arr[i]; } String token = EncryptUtils.sha1(str); System.out.println("token:"+token); Map data = new HashMap(1) {{ put("nonce", nonce); put("timestamp", timestamp); put("token", token); }}; return data; } }