Commit 478c3a36 by chamberone

feat: 添加应用ak认证方式,添加超级管理员角色

1 parent 05f7092d
......@@ -9,9 +9,6 @@ import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
......@@ -60,29 +57,49 @@ public class AuthFilter implements GlobalFilter, Ordered {
if (StringUtils.isEmpty(authToken)) {
authToken = exchange.getRequest().getQueryParams().getFirst("token");
}
UserLoginDTO userDTO = null;
if (StringUtils.isNotEmpty(authToken)) {
if (log.isTraceEnabled()) {
log.trace("token is {}", authToken);
}
UserLoginDTO userDTO = null;
if (StringUtils.isNotEmpty(authToken)) {
// 查询token对应的用户
String value = redisService.get(RedisKeyGroup.authToken + ":" + authToken);
if (null != value) {
userDTO = gson.fromJson(value, UserLoginDTO.class);
}
}
// ak登录处理
if (StringUtils.isEmpty(authToken)) {
String ak = exchange.getRequest().getQueryParams().getFirst("ak");
if (log.isTraceEnabled()) {
log.trace("ak is {}", ak);
}
if (StringUtils.isNotEmpty(ak)) {
// 验证ak,设置userDTO
String value = redisService.get(RedisKeyGroup.appKey + ":" + ak);
if (StringUtils.isNotEmpty(value)) {
// 验证成功,设置为管理员
// AppDTO appDTO = gson.fromJson(value, AppDTO.class);
// String secret = appDTO.getSecret();
userDTO = new UserLoginDTO();
userDTO.setId("1");
}
}
}
if (userDTO == null) {
log.info("未授权访问{} ip:{}", url, getRemoteIP(exchange));
} else {
log.info("用户:{} id:{} 访问{}", userDTO.getAccount(), userDTO.getId(), url);
// 获取当前的请求对象信息
// exchange.getRequest().getHeaders().add("userId", userDTO.getId());
ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
// 向header中设置新的key,存储解析好的token对应基本信息
builder.header("userId", userDTO.getId());
// 向下游传递
Authentication authentication = new UsernamePasswordAuthenticationToken(userDTO.getAccount(), null, null);
SecurityContextHolder.getContext().setAuthentication(authentication);
// Authentication authentication = new UsernamePasswordAuthenticationToken(userDTO.getAccount(), null, null);
// SecurityContextHolder.getContext().setAuthentication(authentication);
return chain.filter(exchange.mutate().request(builder.build()).build());
}
......
......@@ -11,7 +11,7 @@ public enum RedisKeyGroup {
authToken,
/**
* 认证ak对应的团队信息
* 认证ak对应的认证信息
*/
appKey;
......
package com.dituhui.pea.pojo;
import lombok.Data;
@Data
public class AppDTO {
/**
* 主键
*/
private String id;
private String name;
private String key;
private String secret;
}
......@@ -22,13 +22,34 @@ import com.dituhui.pea.pojo.WebResult;
@FeignClient(value = "project-user", contextId = "user")
public interface IUser {
/**
* 登录接口
*
* @param user
* @return
*/
@RequestMapping(value = "/pea-user/login", method = RequestMethod.POST)
public Result<UserLoginDTO> userLogin(@RequestBody UserLoginParam user);
/**
* 获取用户信息
*
* @param userId
* @return
*/
@RequestMapping(value = "/pea-user/userInfo", method = RequestMethod.GET)
public Result<UserLoginDTO> getUserInfo(@RequestHeader(name="userId", required = true) String userId);
/**
* 刷新appkey接口<br>
* 初始化系统ak缓存,例如系统上线,新ak入库的时候
*
* @return
*/
@RequestMapping(value = "/pea-user/refreshAppkey", method = RequestMethod.POST)
public Result<Boolean> refreshAppkey(@RequestHeader(name = "userId", required = true) String userId);
/**
* 获取当前登陆用户信息
*
* @param token 登录token
......
......@@ -4,6 +4,7 @@ package com.dituhui.pea.user.controller;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import com.dituhui.pea.common.Result;
......@@ -43,6 +44,11 @@ public class UserController implements IUser {
}
@Override
public Result<Boolean> refreshAppkey(String userId) {
return userService.refreshAppkey(userId);
}
@Override
public WebResult<UserInfo> getCurrentUserInfo(String userToken, Boolean needTeamInfo) {
return null;
}
......
package com.dituhui.pea.user.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import com.dituhui.pea.user.entity.AppEntity;
import com.dituhui.pea.user.entity.ResourceEntity;
/**
* app表 管理ak表的数据库访问层
*
*/
public interface AppDao extends JpaRepository<AppEntity, String>,
JpaSpecificationExecutor<AppEntity>, CrudRepository<AppEntity, String> {
/**
* 查询key信息
*
* @param key
* @return
*/
ResourceEntity findByKey(String key);
}
package com.dituhui.pea.user.entity;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
import java.util.Date;
/**
* 应用ak表 管理不同关联方使用的不同ak
*
*/
@Data
@Entity
@Table(name = "sys_app")
@EntityListeners(AuditingEntityListener.class)
public class AppEntity implements Serializable {
private static final long serialVersionUID = 157258775707540233L;
/**
* 主键
*/
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid")
@Column(name = "ID", unique = true, nullable = false, length = 32)
private String id;
/**
* 名称
*/
@Column(name = "name")
@NotBlank(message = "名称不能为空!")
private String name;
/**
* key
*/
@Column(name = "key")
private String key;
/**
* secret
*/
@Column(name = "secret")
private String secret;
/**
* 创建人
*/
@Column(name = "CREATED_BY")
private String createdBy;
/**
* 创建时间
*/
@Column(name = "CREATED_TIME")
@CreatedDate
private Date createdTime;
/**
* 更新人
*/
@Column(name = "UPDATED_BY")
private String updatedBy;
/**
* 更新时间
*/
@Column(name = "UPDATED_TIME")
@LastModifiedDate
private Date updatedTime;
}
......@@ -23,6 +23,7 @@ import com.dituhui.pea.enums.StatusCodeEnum;
import com.dituhui.pea.enums.ThirdPartyEnum;
import com.dituhui.pea.exception.BusinessException;
import com.dituhui.pea.order.IOrganization;
import com.dituhui.pea.pojo.AppDTO;
import com.dituhui.pea.pojo.OrganizationDTO;
import com.dituhui.pea.pojo.ResourceInfo;
import com.dituhui.pea.pojo.RoleInfo;
......@@ -31,11 +32,13 @@ import com.dituhui.pea.pojo.UserInfo;
import com.dituhui.pea.pojo.UserLoginDTO;
import com.dituhui.pea.user.commom.RedisService;
import com.dituhui.pea.user.constant.TextConstant;
import com.dituhui.pea.user.dao.AppDao;
import com.dituhui.pea.user.dao.ResourceDao;
import com.dituhui.pea.user.dao.RoleDao;
import com.dituhui.pea.user.dao.RoleResourceDao;
import com.dituhui.pea.user.dao.UserDao;
import com.dituhui.pea.user.dao.UserRoleDao;
import com.dituhui.pea.user.entity.AppEntity;
import com.dituhui.pea.user.entity.ResourceEntity;
import com.dituhui.pea.user.entity.RoleEntity;
import com.dituhui.pea.user.entity.RoleResourceEntity;
......@@ -68,6 +71,10 @@ public class UserService {
*/
private static final int LIVE_TIME_MILLIS = 7200000;
private static final Gson gson = new Gson();
/**
* 超管id
*/
private static final String SUPER_ADMIN_ID = "1";
@Autowired
UserDao userDao;
......@@ -93,6 +100,9 @@ public class UserService {
@Autowired
IOrganization organizationService;
@Autowired
AppDao appDao;
public Result<UserLoginDTO> userLogin(String account, String password) {
UserEntity user = userDao.findByAccountAndPassword(account, SecureUtil.md5(password));
log.info("{}/{} login", account, password);
......@@ -121,13 +131,22 @@ public class UserService {
.collect(Collectors.toList()));
// 获取资源
List<ResourceEntity> resources = null;
if (ids.contains(SUPER_ADMIN_ID)) {
// 超管处理,不用配置资源自动拥有所有权限
resources = resourceDao.findAll();
} else {
// 普通用户
List<RoleResourceEntity> roleResources = roleResourceDao.findByRoleIdIn(ids);
log.info("role : {} roleResources:{}", ids, CollectionUtils.isNotEmpty(roleResources));
if (CollectionUtils.isNotEmpty(roleResources)) {
List<String> resourceIds = roleResources.stream().map(r -> r.getResourceId())
.collect(Collectors.toList());
List<ResourceEntity> resources = resourceDao.findAllById(resourceIds);
resources = resourceDao.findAllById(resourceIds);
}
}
if (CollectionUtils.isNotEmpty(resources)) {
// 菜单嵌套处理+菜单排序
List<ResourceInfo> levelOne = resources.stream()
.filter(r -> StringUtils.isEmpty(r.getParentId()) && r.getType() == 1)
......@@ -570,4 +589,33 @@ public class UserService {
}
toUserEntity.setSex(formUserInfo.getSex());
}
public Result<Boolean> refreshAppkey(String userId) {
// 超级管理员才能执行此命令
RoleEntity role = null;
List<UserRoleEntity> userRoles = userRoleDao.findByUserId(userId);
if (CollectionUtils.isNotEmpty(userRoles)) {
List<String> ids = userRoles.stream().map(r -> r.getRoleId()).collect(Collectors.toList());
List<RoleEntity> roles = roleDao.findAllById(ids);
if (CollectionUtils.isNotEmpty(roles)) {
role = roles.stream().filter(r -> StringUtils.equals(r.getId(), SUPER_ADMIN_ID)).findFirst()
.orElse(null);
}
}
if (null == role) {
return Result.failure("超级管理员才能执行此命令");
}
// 缓存所有key
List<AppEntity> keyList = appDao.findAll();
if (CollectionUtils.isNotEmpty(keyList)) {
for (AppEntity appkey : keyList) {
redisService.set(RedisKeyGroup.appKey + ":" + appkey.getKey(),
gson.toJson(BeanUtil.copyProperties(appkey, AppDTO.class)));
}
}
return Result.success(true);
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!