Unverified Commit 9e599960 authored by ZackYoung's avatar ZackYoung Committed by GitHub

[Feature][token]Add token persistent (#2512)

* feature_add_token_persistent * feature_add_token_persistent * feature_add_token_persistent
parent 8dc2431e
......@@ -169,11 +169,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- sa-token 持久化 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-core</artifactId>
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.dinky.configure;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* CacheCoonfigure
*
* @since 2022/09/24 11:23
*/
@Configuration
@ConditionalOnProperty(prefix = "spring.cache", name = "type", havingValue = "REDIS")
public class CacheConfig {
/** 配置Redis缓存注解的value序列化方式 */
@Bean
public RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
// 序列化为json
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()))
.serializeKeysWith(
RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
}
// /**
// * 配置RedisTemplate的序列化方式
// */
// @Bean
// public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
// RedisTemplate redisTemplate = new RedisTemplate();
// redisTemplate.setConnectionFactory(factory);
// // 指定key的序列化方式:string
// redisTemplate.setKeySerializer(RedisSerializer.string());
// // 指定value的序列化方式:json
// redisTemplate.setValueSerializer(RedisSerializer.json());
// return redisTemplate;
// }
}
......@@ -22,14 +22,15 @@ package org.dinky.configure;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.util.SaTokenConsts;
@Configuration
public class SaTokenConfigure {
// Sa-Token 整合 jwt (Simple 简单模式)
@Bean
public StpLogic getStpLogicJwt() {
return new StpLogicJwtForSimple();
// return new StpLogicJwtForSimple();
return new StpLogic(SaTokenConsts.TOKEN_STYLE_RANDOM_32);
}
}
......@@ -42,14 +42,16 @@ import com.fasterxml.jackson.databind.JsonNode;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.hutool.core.lang.UUID;
import cn.dev33.satoken.stp.StpLogic;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/** TokenController */
/**
* TokenController
*/
@Slf4j
@Api(tags = "Token Controller")
@RestController
......@@ -58,6 +60,7 @@ import lombok.extern.slf4j.Slf4j;
public class TokenController {
private final TokenService tokenService;
private final StpLogic stpLogic;
/**
* get udf template list
......@@ -113,12 +116,13 @@ public class TokenController {
/**
* delete Token by id
*
* @return {@link Result} <{@link Void}>
*/
@PostMapping("/buildToken")
@Log(title = "Build Token", businessType = BusinessType.OTHER)
@ApiOperation("Build Token")
public Result<String> buildToken() {
return Result.succeed(UUID.fastUUID().toString(true), Status.SUCCESS);
return Result.succeed(stpLogic.createTokenValue(null, null, 1, null), Status.SUCCESS);
}
}
......@@ -24,6 +24,7 @@ import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
......@@ -39,6 +40,7 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Data
......@@ -154,4 +156,16 @@ public class SysToken implements Serializable {
dataType = "List<LocalDateTime>",
notes = "List of timestamps indicating the time range for token expiration")
private List<LocalDateTime> expireTimeRange;
private Source source;
@Getter
@AllArgsConstructor
public enum Source {
LOGIN(1),
CUSTOM(2);
@EnumValue
private final int type;
}
}
......@@ -33,6 +33,7 @@ import org.dinky.data.model.Menu;
import org.dinky.data.model.Role;
import org.dinky.data.model.RoleMenu;
import org.dinky.data.model.RowPermissions;
import org.dinky.data.model.SysToken;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.data.model.Tenant;
import org.dinky.data.model.User;
......@@ -42,6 +43,7 @@ import org.dinky.data.params.AssignRoleParams;
import org.dinky.data.params.AssignUserToTenantParams;
import org.dinky.data.result.Result;
import org.dinky.data.vo.UserVo;
import org.dinky.mapper.TokenMapper;
import org.dinky.mapper.UserMapper;
import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.service.MenuService;
......@@ -66,6 +68,8 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
......@@ -98,6 +102,8 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
private final RoleMenuService roleMenuService;
private final MenuService menuService;
private final TokenService tokenService;
private final TokenMapper tokenMapper;
@Override
public Result<Void> registerUser(User user) {
......@@ -156,7 +162,7 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
*
* @param loginDTO a user based on the provided login credentials.
* @return a Result object containing the user information if the login is successful, or an
* appropriate error status if the login fails.
* appropriate error status if the login fails.
*/
@Override
public Result<UserDTO> loginUser(LoginDTO loginDTO) {
......@@ -182,15 +188,37 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
}
// Perform login using StpUtil (Assuming it handles the session management)
StpUtil.login(user.getId(), loginDTO.isAutoLogin());
Integer userId = user.getId();
StpUtil.login(userId, loginDTO.isAutoLogin());
// save login log record
loginLogService.saveLoginLog(user, Status.LOGIN_SUCCESS);
insertToken(userInfo);
// Return the user information along with a success status
return Result.succeed(userInfo, Status.LOGIN_SUCCESS);
}
private void insertToken(UserDTO userInfo) {
Integer userId = userInfo.getUser().getId();
SysToken sysToken = new SysToken();
String tokenValue = StpUtil.getTokenValueByLoginId(userId);
sysToken.setTokenValue(tokenValue);
sysToken.setUserId(userId);
// todo 权限和租户暂未接入
sysToken.setRoleId(1);
sysToken.setTenantId(1);
sysToken.setExpireType(3);
DateTime date = DateUtil.date();
sysToken.setExpireStartTime(date);
sysToken.setExpireEndTime(DateUtil.offsetDay(date, 1));
sysToken.setCreator(userId);
sysToken.setUpdator(userId);
sysToken.setSource(SysToken.Source.LOGIN);
tokenMapper.insert(sysToken);
}
private User localLogin(LoginDTO loginDTO) throws AuthException {
// Get user from local database by username
User user = getUserByUsername(loginDTO.getUsername());
......@@ -476,7 +504,7 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
* @param userId
* @return
*/
private UserDTO buildUserInfo(Integer userId) {
public UserDTO buildUserInfo(Integer userId) {
User user = getById(userId);
if (Asserts.isNull(user)) {
......
......@@ -568,6 +568,7 @@ CREATE TABLE `dinky_sys_token` (
`update_time` datetime NOT NULL COMMENT 'modify time',
`creator` bigint DEFAULT NULL COMMENT '创建人',
`updator` bigint DEFAULT NULL COMMENT '修改人',
`source` tinyint(2) DEFAULT NULL COMMENT '1:login 2:custom',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COMMENT='token management';
......
......@@ -4,10 +4,10 @@
<select id="selectForProTable" resultType="org.dinky.data.model.SysToken">
select
a.*,
b.username,
c.role_name,
d.tenant_code
a.*,
b.username,
c.role_name,
d.tenant_code
from
dinky_sys_token a
join dinky_user b on a.user_id = b.id
......@@ -37,6 +37,7 @@
<if test='ew.sqlSegment!=null and ew.sqlSegment!=""'>
${ew.sqlSegment}
</if>
and source=2
</where>
</select>
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
* 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.
* 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.
*
*/
......@@ -41,7 +41,6 @@ export default () => {
const para = { sessionKey: uuidRef.current, topics: topics };
await postAll('api/sse/subscribeTopic', para).catch((e) => ErrorMessage(e));
};
const reconnectSse = () => {
const sseUrl = '/api/sse/connect?sessionKey=' + uuidRef.current;
eventSource?.close();
......
......@@ -372,18 +372,6 @@
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>${sa-token.version}</version>
</dependency>
<!--sa-token redis持久化 start-->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-dao-redis-jackson</artifactId>
<version>${sa-token.version}</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
<!--sa-token redis持久化 end-->
<dependency>
<groupId>org.dinky</groupId>
<artifactId>dinky-core</artifactId>
......
......@@ -1841,29 +1841,6 @@ CREATE TABLE `dinky_sys_role_menu` (
UNIQUE KEY `un_role_menu_inx` (`role_id`,`menu_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
-- ----------------------------
-- Table structure dinky_sys_token
-- ----------------------------
drop table if exists `dinky_sys_token`;
CREATE TABLE `dinky_sys_token` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
`token_value` varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'token value',
`user_id` bigint NOT NULL COMMENT 'user id',
`role_id` bigint NOT NULL COMMENT 'role id',
`tenant_id` bigint NOT NULL COMMENT 'tenant id',
`expire_type` tinyint NOT NULL COMMENT '1: never expire, 2: expire after a period of time, 3: expire at a certain time',
`expire_start_time` datetime DEFAULT NULL COMMENT 'expire start time ,when expire_type = 3 , it is the start time of the period',
`expire_end_time` datetime DEFAULT NULL COMMENT 'expire end time ,when expire_type = 2,3 , it is the end time of the period',
`create_time` datetime NOT NULL COMMENT 'create time',
`update_time` datetime NOT NULL COMMENT 'modify time',
`creator` bigint DEFAULT NULL COMMENT '创建人',
`updator` bigint DEFAULT NULL COMMENT '修改人',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='token management';
-- ----------------------------
-- Table structure dinky_sys_alert
-- ----------------------------
......@@ -1918,9 +1895,7 @@ INSERT INTO dinky_alert_template VALUES (1, 'Default', '
[Go toTask Web](http://${taskUrl})
', 1, null, null);
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
CREATE TABLE `dinky_udf_manage` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL COMMENT 'udf name',
......@@ -1932,4 +1907,30 @@ CREATE TABLE `dinky_udf_manage` (
`update_time` datetime DEFAULT NULL COMMENT 'update time',
PRIMARY KEY (`id`) USING BTREE,
KEY `name,resources_id` (`name`,`resources_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='udf';
\ No newline at end of file
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='udf';
-- ----------------------------
-- Table structure dinky_sys_token
-- ----------------------------
drop table if exists `dinky_sys_token`;
CREATE TABLE `dinky_sys_token` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`token_value` varchar(255) NOT NULL COMMENT 'token value',
`user_id` bigint(20) NOT NULL COMMENT 'user id',
`role_id` bigint(20) NOT NULL COMMENT 'role id',
`tenant_id` bigint(20) NOT NULL COMMENT 'tenant id',
`expire_type` tinyint(4) NOT NULL COMMENT '1: never expire, 2: expire after a period of time, 3: expire at a certain time',
`expire_start_time` datetime DEFAULT NULL COMMENT 'expire start time ,when expire_type = 3 , it is the start time of the period',
`expire_end_time` datetime DEFAULT NULL COMMENT 'expire end time ,when expire_type = 2,3 , it is the end time of the period',
`create_time` datetime NOT NULL COMMENT 'create time',
`update_time` datetime NOT NULL COMMENT 'modify time',
`creator` bigint(20) DEFAULT NULL COMMENT '创建人',
`updator` bigint(20) DEFAULT NULL COMMENT '修改人',
`source` tinyint(2) DEFAULT NULL COMMENT '1:login 2:custom',
PRIMARY KEY (`id`),
UNIQUE KEY `token_value` (`token_value`) USING BTREE,
KEY `source` (`source`) USING HASH
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4 COMMENT='token management';
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;
......@@ -2663,7 +2663,8 @@ create table public.dinky_sys_token (
create_time timestamp without time zone,
update_time timestamp without time zone,
creator bigint,
updator bigint
updator bigint,
source bigint
);
comment on table public.dinky_sys_token is 'token table';
comment on column public.dinky_sys_token.id is 'id';
......@@ -2678,6 +2679,7 @@ comment on column public.dinky_sys_token.create_time is 'create time';
comment on column public.dinky_sys_token.update_time is 'modify time';
comment on column public.dinky_sys_token.creator is 'creat user';
comment on column public.dinky_sys_token.updator is 'modify user';
comment on column public.dinky_sys_token.source is 'source';
-- ----------------------------
......
......@@ -275,20 +275,23 @@ create table if not exists dinky_alert_rules
-- Table structure dinky_sys_token
-- ----------------------------
CREATE TABLE `dinky_sys_token` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
`token_value` varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'token value',
`user_id` bigint NOT NULL COMMENT 'user id',
`role_id` bigint NOT NULL COMMENT 'role id',
`tenant_id` bigint NOT NULL COMMENT 'tenant id',
`expire_type` tinyint NOT NULL COMMENT '1: never expire, 2: expire after a period of time, 3: expire at a certain time',
`expire_start_time` datetime DEFAULT NULL COMMENT 'expire start time ,when expire_type = 3 , it is the start time of the period',
`expire_end_time` datetime DEFAULT NULL COMMENT 'expire end time ,when expire_type = 2,3 , it is the end time of the period',
`create_time` datetime NOT NULL COMMENT 'create time',
`update_time` datetime NOT NULL COMMENT 'modify time',
`creator` bigint DEFAULT NULL COMMENT '创建人',
`updator` bigint DEFAULT NULL COMMENT '修改人',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='token management';
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`token_value` varchar(255) NOT NULL COMMENT 'token value',
`user_id` bigint(20) NOT NULL COMMENT 'user id',
`role_id` bigint(20) NOT NULL COMMENT 'role id',
`tenant_id` bigint(20) NOT NULL COMMENT 'tenant id',
`expire_type` tinyint(4) NOT NULL COMMENT '1: never expire, 2: expire after a period of time, 3: expire at a certain time',
`expire_start_time` datetime DEFAULT NULL COMMENT 'expire start time ,when expire_type = 3 , it is the start time of the period',
`expire_end_time` datetime DEFAULT NULL COMMENT 'expire end time ,when expire_type = 2,3 , it is the end time of the period',
`create_time` datetime NOT NULL COMMENT 'create time',
`update_time` datetime NOT NULL COMMENT 'modify time',
`creator` bigint(20) DEFAULT NULL COMMENT '创建人',
`updator` bigint(20) DEFAULT NULL COMMENT '修改人',
`source` tinyint(2) DEFAULT NULL COMMENT '1:login 2:custom',
PRIMARY KEY (`id`),
UNIQUE KEY `token_value` (`token_value`) USING BTREE,
KEY `source` (`source`) USING HASH
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4 COMMENT='token management';
CREATE TABLE `dinky_udf_manage` (
`id` int(11) NOT NULL AUTO_INCREMENT,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment