Unverified Commit db725ef5 authored by zhu-mingye's avatar zhu-mingye Committed by GitHub

[Feature] Added login log (#2153)

* added login log
parent 3b338b4c
/*
*
* 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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
// log.info("设置跨域");
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
// 允许任何头
corsConfiguration.addAllowedHeader("*");
// 允许任何方法(post、get等)
corsConfiguration.addAllowedMethod("*");
//
corsConfiguration.addExposedHeader("*");
corsConfiguration.addAllowedOriginPattern("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 对接口配置跨域设置
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
...@@ -33,6 +33,10 @@ public class UserInfoContextHolder { ...@@ -33,6 +33,10 @@ public class UserInfoContextHolder {
USER_INFO.put(userId, userInfo); USER_INFO.put(userId, userInfo);
} }
public static void remove(Integer userId) {
USER_INFO.remove(userId);
}
public static UserDTO get(Integer userId) { public static UserDTO get(Integer userId) {
return USER_INFO.get(userId); return USER_INFO.get(userId);
} }
......
/*
*
* 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.controller;
import org.dinky.data.model.LoginLog;
import org.dinky.data.result.Result;
import org.dinky.service.LoginLogService;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping("/api/log")
@RequiredArgsConstructor
public class LogController {
private final LoginLogService loginLogService;
@GetMapping("/loginRecord/{userId}")
public Result<List<LoginLog>> loginRecord(@PathVariable Integer userId) {
return Result.succeed(loginLogService.loginRecord(userId));
}
}
/*
*
* 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.data.model;
import org.dinky.mybatis.annotation.Save;
import java.time.LocalDateTime;
import javax.validation.constraints.NotNull;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.Data;
@Data
@TableName("dinky_sys_login_log")
public class LoginLog {
/** 主键ID */
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@NotNull(
message = "userId cannot be null",
groups = {Save.class})
private Integer userId;
@NotNull(
message = "username cannot be null",
groups = {Save.class})
private String username;
@NotNull(
message = "ip cannot be null",
groups = {Save.class})
private String ip;
private Integer loginType;
private Integer status;
private String msg;
private Boolean isDeleted;
private LocalDateTime accessTime;
@TableField(fill = FieldFill.INSERT)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime updateTime;
}
/*
*
* 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.mapper;
import org.dinky.data.model.LoginLog;
import org.dinky.mybatis.mapper.SuperMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface LoginLogMapper extends SuperMapper<LoginLog> {}
/*
*
* 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.service;
import org.dinky.data.model.LoginLog;
import org.dinky.data.model.User;
import org.dinky.mybatis.service.ISuperService;
import java.util.List;
public interface LoginLogService extends ISuperService<LoginLog> {
void saveLoginLog(User user, Integer status, String ip, String msg);
List<LoginLog> loginRecord(Integer userId);
}
/*
*
* 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.service.impl;
import org.dinky.context.UserInfoContextHolder;
import org.dinky.data.dto.UserDTO;
import org.dinky.data.model.LoginLog;
import org.dinky.data.model.User;
import org.dinky.mapper.LoginLogMapper;
import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.service.LoginLogService;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
@Service
public class LoginLogServiceImpl extends SuperServiceImpl<LoginLogMapper, LoginLog>
implements LoginLogService {
/**
* insert login log record
*
* @param user
* @param status
* @param ip
* @param msg
*/
@Override
public void saveLoginLog(User user, Integer status, String ip, String msg) {
LoginLog loginLog = new LoginLog();
loginLog.setUserId(user.getId());
loginLog.setUsername(user.getUsername());
loginLog.setLoginType(user.getUserType());
loginLog.setAccessTime(LocalDateTime.now());
loginLog.setIp(ip);
loginLog.setStatus(status);
loginLog.setMsg(msg);
saveOrUpdate(loginLog);
}
/**
* @param userId
* @return
*/
@Override
public List<LoginLog> loginRecord(Integer userId) {
UserDTO userDTO = UserInfoContextHolder.get(userId);
List<LoginLog> loginLogList =
getBaseMapper()
.selectList(
new LambdaQueryWrapper<LoginLog>()
.eq(LoginLog::getUserId, userDTO.getUser().getId()));
return loginLogList;
}
}
...@@ -61,6 +61,7 @@ import com.fasterxml.jackson.databind.JsonNode; ...@@ -61,6 +61,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import cn.dev33.satoken.secure.SaSecureUtil; import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil; import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.net.Ipv4Util;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
/** /**
...@@ -86,6 +87,8 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen ...@@ -86,6 +87,8 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
private final LdapServiceImpl ldapService; private final LdapServiceImpl ldapService;
private final LoginLogServiceImpl loginLogService;
@Override @Override
public Result<Void> registerUser(User user) { public Result<Void> registerUser(User user) {
User userByUsername = getUserByUsername(user.getUsername()); User userByUsername = getUserByUsername(user.getUsername());
...@@ -158,17 +161,34 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen ...@@ -158,17 +161,34 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
// Check if the user is enabled // Check if the user is enabled
if (!user.getEnabled()) { if (!user.getEnabled()) {
loginLogService.saveLoginLog(
user,
Status.USER_DISABLED_BY_ADMIN.getCode(),
Ipv4Util.LOCAL_IP,
Status.USER_DISABLED_BY_ADMIN.getMsg());
return Result.failed(Status.USER_DISABLED_BY_ADMIN); return Result.failed(Status.USER_DISABLED_BY_ADMIN);
} }
UserDTO userInfo = refreshUserInfo(user); UserDTO userInfo = refreshUserInfo(user);
if (Asserts.isNullCollection(userInfo.getTenantList())) { if (Asserts.isNullCollection(userInfo.getTenantList())) {
loginLogService.saveLoginLog(
user,
Status.USER_NOT_BINDING_TENANT.getCode(),
Ipv4Util.LOCAL_IP,
Status.USER_NOT_BINDING_TENANT.getMsg());
return Result.failed(Status.USER_NOT_BINDING_TENANT); return Result.failed(Status.USER_NOT_BINDING_TENANT);
} }
// Perform login using StpUtil (Assuming it handles the session management) // Perform login using StpUtil (Assuming it handles the session management)
StpUtil.login(user.getId(), loginDTO.isAutoLogin()); StpUtil.login(user.getId(), loginDTO.isAutoLogin());
// save login log record
loginLogService.saveLoginLog(
user,
Status.LOGIN_SUCCESS.getCode(),
Ipv4Util.LOCAL_IP,
Status.LOGIN_SUCCESS.getMsg());
// Return the user information along with a success status // Return the user information along with a success status
return Result.succeed(userInfo, Status.LOGIN_SUCCESS); return Result.succeed(userInfo, Status.LOGIN_SUCCESS);
} }
...@@ -184,6 +204,11 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen ...@@ -184,6 +204,11 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
String userPassword = user.getPassword(); String userPassword = user.getPassword();
// Check if the provided password is null // Check if the provided password is null
if (Asserts.isNullString(loginDTO.getPassword())) { if (Asserts.isNullString(loginDTO.getPassword())) {
loginLogService.saveLoginLog(
user,
Status.LOGIN_PASSWORD_NOT_NULL.getCode(),
Ipv4Util.LOCAL_IP,
Status.LOGIN_PASSWORD_NOT_NULL.getMsg());
throw new AuthException(Status.LOGIN_PASSWORD_NOT_NULL); throw new AuthException(Status.LOGIN_PASSWORD_NOT_NULL);
} }
...@@ -191,6 +216,11 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen ...@@ -191,6 +216,11 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
if (Asserts.isEquals(SaSecureUtil.md5(loginDTO.getPassword()), userPassword)) { if (Asserts.isEquals(SaSecureUtil.md5(loginDTO.getPassword()), userPassword)) {
return user; return user;
} else { } else {
loginLogService.saveLoginLog(
user,
Status.USER_NAME_PASSWD_ERROR.getCode(),
Ipv4Util.LOCAL_IP,
Status.USER_NAME_PASSWD_ERROR.getMsg());
throw new AuthException(Status.USER_NAME_PASSWD_ERROR); throw new AuthException(Status.USER_NAME_PASSWD_ERROR);
} }
} }
...@@ -205,6 +235,11 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen ...@@ -205,6 +235,11 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
// User doesn't exist locally // User doesn't exist locally
// Check if LDAP user autoload is enabled // Check if LDAP user autoload is enabled
if (!SystemConfiguration.getInstances().getLdapAutoload().getValue()) { if (!SystemConfiguration.getInstances().getLdapAutoload().getValue()) {
loginLogService.saveLoginLog(
userFromLocal,
Status.USER_NAME_PASSWD_ERROR.getCode(),
Ipv4Util.LOCAL_IP,
Status.USER_NAME_PASSWD_ERROR.getMsg());
throw new AuthException(Status.LDAP_USER_AUTOLOAD_FORBAID); throw new AuthException(Status.LDAP_USER_AUTOLOAD_FORBAID);
} }
...@@ -213,6 +248,11 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen ...@@ -213,6 +248,11 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
SystemConfiguration.getInstances().getLdapDefaultTeant().getValue(); SystemConfiguration.getInstances().getLdapDefaultTeant().getValue();
Tenant tenant = tenantService.getTenantByTenantCode(defaultTeantCode); Tenant tenant = tenantService.getTenantByTenantCode(defaultTeantCode);
if (Asserts.isNull(tenant)) { if (Asserts.isNull(tenant)) {
loginLogService.saveLoginLog(
userFromLocal,
Status.LDAP_DEFAULT_TENANT_NOFOUND.getCode(),
Ipv4Util.LOCAL_IP,
Status.LDAP_DEFAULT_TENANT_NOFOUND.getMsg());
throw new AuthException(Status.LDAP_DEFAULT_TENANT_NOFOUND); throw new AuthException(Status.LDAP_DEFAULT_TENANT_NOFOUND);
} }
...@@ -230,6 +270,11 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen ...@@ -230,6 +270,11 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
tenantService.assignUserToTenant(new AssignUserToTenantParams(tenant.getId(), userIds)); tenantService.assignUserToTenant(new AssignUserToTenantParams(tenant.getId(), userIds));
return user; return user;
} else if (userFromLocal.getUserType() != UserType.LDAP.getCode()) { } else if (userFromLocal.getUserType() != UserType.LDAP.getCode()) {
loginLogService.saveLoginLog(
userFromLocal,
Status.LDAP_LOGIN_FORBID.getCode(),
Ipv4Util.LOCAL_IP,
Status.LDAP_LOGIN_FORBID.getMsg());
throw new AuthException(Status.LDAP_LOGIN_FORBID); throw new AuthException(Status.LDAP_LOGIN_FORBID);
} }
......
...@@ -1685,4 +1685,24 @@ CREATE TABLE `dinky_resources` ( ...@@ -1685,4 +1685,24 @@ CREATE TABLE `dinky_resources` (
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'create time', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'create time',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'update time' `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'update time'
) ENGINE = InnoDB; ) ENGINE = InnoDB;
INSERT INTO `dinky_resources` (`id`, `file_name`, `description`, `user_id`, `type`, `size`, `pid`, `full_name`, `is_directory`) VALUES (0, 'Root', 'main folder', 1, 0, 0, -1, '/', 1); INSERT INTO `dinky_resources` (`id`, `file_name`, `description`, `user_id`, `type`, `size`, `pid`, `full_name`, `is_directory`) VALUES (0, 'Root', 'main folder', 1, 0, 0, -1, '/', 1);
\ No newline at end of file
-- ----------------------------
-- Table structure for dinky_sys_login_log
-- ----------------------------
DROP TABLE IF EXISTS dinky_sys_login_log;
CREATE TABLE `dinky_sys_login_log` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'key',
`user_id` int(11) NOT NULL COMMENT 'user id',
`username` varchar(60) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'username',
`login_type` int NOT NULL COMMENT 'login type(0:LOCAL,1:LDAP)',
`ip` varchar(40) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'ip addr',
`status` int NOT NULL COMMENT 'login status',
`msg` text COLLATE utf8mb4_general_ci NOT NULL COMMENT 'status msg',
`create_time` datetime NOT NULL COMMENT 'create time',
`access_time` datetime DEFAULT NULL COMMENT 'access time',
`update_time` datetime NOT NULL,
`is_deleted` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
...@@ -159,11 +159,16 @@ export default { ...@@ -159,11 +159,16 @@ export default {
'user.newpwdPlaceholder': 'Please enter new password', 'user.newpwdPlaceholder': 'Please enter new password',
'user.repeatpwdPlaceholder': 'Please enter repeat new password', 'user.repeatpwdPlaceholder': 'Please enter repeat new password',
'user.oldNewPwdNoMatch': 'The new passwords do not match', 'user.oldNewPwdNoMatch': 'The new passwords do not match',
'user.login.status.code': 'Code',
'user.login.status.msg': 'Message',
'user.login.accesstime': 'Login Time',
'user.login.ip': 'Login IP',
// -- personal info // -- personal info
'user.info': 'Personal Info', 'user.info': 'Personal Info',
'user.tenant': 'Tenant', 'user.tenant': 'Tenant',
'user.role': 'Role', 'user.role': 'Role',
'user.op': 'Operation', 'user.op': 'Operation',
'user.loginlog': 'Login Log',
'user.current.tenant': 'Current Tenant', 'user.current.tenant': 'Current Tenant',
// tenant // tenant
......
...@@ -154,11 +154,17 @@ export default { ...@@ -154,11 +154,17 @@ export default {
'user.newpwdPlaceholder': '请输入新密码', 'user.newpwdPlaceholder': '请输入新密码',
'user.repeatpwdPlaceholder': '请重复输入新密码', 'user.repeatpwdPlaceholder': '请重复输入新密码',
'user.oldNewPwdNoMatch': '两次输入的新密码不一致', 'user.oldNewPwdNoMatch': '两次输入的新密码不一致',
'user.login.status.code': '状态值',
'user.login.status.msg': '信息',
'user.login.accesstime': '登录时间',
'user.login.ip': '登录IP',
// -- personal info // -- personal info
'user.info': '个人信息', 'user.info': '个人信息',
'user.tenant': '租户', 'user.tenant': '租户',
'user.role': '角色', 'user.role': '角色',
'user.op': '操作记录', 'user.op': '操作记录',
'user.loginlog': '登录日志',
'user.current.tenant': '当前登录租户', 'user.current.tenant': '当前登录租户',
// tenant // tenant
......
/*
*
* 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.
*
*/
import {TimelineItemProps} from "antd/es/timeline/TimelineItem";
import {Space, Typography} from "antd";
import {l} from "@/utils/intl";
import React from "react";
import {LoginLog} from "@/types/User/data";
import moment from "moment";
const { Text } = Typography;
export const renderTimeLineItems = (loginRecord: LoginLog[]): TimelineItemProps[] => {
return loginRecord.filter(item => !item.isDeleted).map(item => {
const renderTitle = <Space direction="vertical">
<Text>{l('user.username')}: {item.username}</Text>
<Text type={item.status === 10004 ? 'success' : 'danger'}>{l('user.login.status.code')}: {item.status}</Text>
<Text type={item.status === 10004 ? 'success' : 'danger'}>{l('user.login.status.msg')}: {item.msg}</Text>
</Space>
const renderLabel = <>
<Space direction="vertical">
<Text>{l('user.login.accesstime')}: {moment(item.accessTime).format('YYYY-MM-DD HH:mm:ss')}</Text>
<Text>{l('user.login.ip')}: {item.ip}</Text>
</Space>
</>
return {
key: item.id,
color: item.status === 10004 ? 'green' : 'red',
label: renderLabel,
children: renderTitle,
}
})
}
\ No newline at end of file
/*
*
* 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.
*
*/
import React, {useCallback, useEffect, useState} from "react";
import {queryDataByParams} from "@/services/BusinessCrud";
import {BackTop, Button, Card, Spin, Timeline} from "antd";
import {LoginLog} from "@/types/User/data";
import {l} from "@/utils/intl";
import {renderTimeLineItems} from "@/pages/Other/PersonCenter/LoginLogRecord/function";
type LoginLogRecordProps = {
userId: number
}
const LoginLogRecord: React.FC<LoginLogRecordProps> = (props) => {
const {userId} = props
const [loginRecord, setLoginRecord] = useState<LoginLog[]>([]);
const [refresh, setRefresh] = useState(false);
const queryLoginLog = useCallback(async (id: number) => {
setRefresh(true)
await queryDataByParams(`/api/log/loginRecord/${id}`).then(res => {
setLoginRecord(res)
setRefresh(false)
})
}, [userId])
useEffect(() => {
queryLoginLog(userId)
}, [userId])
return <>
<Card bordered={false} extra={ <Button onClick={() => queryLoginLog(userId)}>{l('button.refresh')}</Button>} size="small" >
<Spin spinning={refresh}>
<Timeline
mode={'alternate'}
reverse
items={renderTimeLineItems(loginRecord)}
/>
</Spin>
</Card>
</>
}
export default LoginLogRecord
\ No newline at end of file
/*
*
* 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.
*
*/
const OperationLogRecord = () => {
return <div>OperationLogRecord</div>;
}
export default OperationLogRecord
\ No newline at end of file
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
import React, {useEffect, useState} from "react"; import React, {useEffect, useState} from "react";
import {useModel} from "@@/exports"; import {useModel} from "@@/exports";
import {Descriptions, Divider, Empty, Form, Space, Tag} from "antd"; import {Descriptions, Divider, Form, Tag} from "antd";
import {PageContainer, PageLoading, ProCard} from "@ant-design/pro-components"; import {PageContainer, PageLoading, ProCard} from "@ant-design/pro-components";
import {UserBaseInfo} from "@/types/User/data"; import {UserBaseInfo} from "@/types/User/data";
import {l} from "@/utils/intl"; import {l} from "@/utils/intl";
...@@ -31,13 +31,15 @@ import {API_CONSTANTS} from "@/services/constants"; ...@@ -31,13 +31,15 @@ import {API_CONSTANTS} from "@/services/constants";
import BaseInfo from "@/pages/Other/PersonCenter/BaseInfo"; import BaseInfo from "@/pages/Other/PersonCenter/BaseInfo";
import Pop from "@/components/Animation/Pop"; import Pop from "@/components/Animation/Pop";
import {flushSync} from "react-dom"; import {flushSync} from "react-dom";
import LoginLogRecord from "@/pages/Other/PersonCenter/LoginLogRecord";
import OperationLogRecord from "@/pages/Other/PersonCenter/OperationLogRecord";
const PersonCenter = () => { const PersonCenter = () => {
const [form] = Form.useForm(); const [form] = Form.useForm();
const { initialState, setInitialState } = useModel('@@initialState'); const { initialState, setInitialState } = useModel('@@initialState');
const [activeKey, setActiveKey] = useState('operation'); const [activeKey, setActiveKey] = useState('loginlog');
const loading = <PageLoading/>; const loading = <PageLoading/>;
const fetchUserInfo = async () => { const fetchUserInfo = async () => {
...@@ -111,10 +113,15 @@ const PersonCenter = () => { ...@@ -111,10 +113,15 @@ const PersonCenter = () => {
* @type {({children: JSX.Element, label: JSX.Element, key: string} | {children: JSX.Element, label: JSX.Element, key: string})[]} * @type {({children: JSX.Element, label: JSX.Element, key: string} | {children: JSX.Element, label: JSX.Element, key: string})[]}
*/ */
const tabList = [ const tabList = [
{
key: 'loginlog',
label: <><LogSvg/>{l('user.loginlog')}</>,
children: <><LoginLogRecord userId={user?.id}/></>,
},
{ {
key: 'operation', key: 'operation',
label: <><LogSvg/>{l('user.op')}</>, label: <><LogSvg/>{l('user.op')}</>,
children: <><Empty description={l('global.stay.tuned')} image={Empty.PRESENTED_IMAGE_DEFAULT}/></>, children: <><OperationLogRecord/></>,
}, },
{ {
key: 'changePassword', key: 'changePassword',
......
...@@ -77,3 +77,18 @@ export type RowPermissions = ExcludeNameAndEnableColumns & { ...@@ -77,3 +77,18 @@ export type RowPermissions = ExcludeNameAndEnableColumns & {
tableName: string; tableName: string;
expression: string; expression: string;
}; };
export type LoginLog = {
id: number;
userId : number;
username: string;
ip: string;
loginType: string;
status: number;
msg: string;
isDeleted: boolean;
accessTime: Date;
createTime: Date;
updateTime: Date;
}
\ No newline at end of file
...@@ -1130,6 +1130,24 @@ CREATE TABLE `dinky_resources` ( ...@@ -1130,6 +1130,24 @@ CREATE TABLE `dinky_resources` (
INSERT INTO `dinky_resources` (`id`, `file_name`, `description`, `user_id`, `type`, `size`, `pid`, `full_name`, `is_directory`) VALUES (0, 'Root', 'main folder', 1, 0, 0, -1, '/', 1); INSERT INTO `dinky_resources` (`id`, `file_name`, `description`, `user_id`, `type`, `size`, `pid`, `full_name`, `is_directory`) VALUES (0, 'Root', 'main folder', 1, 0, 0, -1, '/', 1);
-- ----------------------------
-- Table structure for dinky_sys_login_log
-- ----------------------------
DROP TABLE IF EXISTS dinky_sys_login_log;
CREATE TABLE `dinky_sys_login_log` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'key',
`user_id` int NOT NULL COMMENT 'user id',
`username` varchar(60) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'username',
`login_type` int NOT NULL COMMENT 'login type(0:LOCAL,1:LDAP)',
`ip` varchar(40) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'ip addr',
`status` int NOT NULL COMMENT 'login status',
`msg` text COLLATE utf8mb4_general_ci NOT NULL COMMENT 'status msg',
`create_time` datetime NOT NULL COMMENT 'create time',
`access_time` datetime DEFAULT NULL COMMENT 'access time',
`update_time` datetime NOT NULL,
`is_deleted` tinyint NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='system login log record'
......
...@@ -2123,4 +2123,58 @@ CREATE UNIQUE INDEX "dinky_resources_un" ON "public"."dinky_resources" USING btr ...@@ -2123,4 +2123,58 @@ CREATE UNIQUE INDEX "dinky_resources_un" ON "public"."dinky_resources" USING btr
-- ---------------------------- -- ----------------------------
-- Primary Key structure for table dinky_resources -- Primary Key structure for table dinky_resources
-- ---------------------------- -- ----------------------------
ALTER TABLE "public"."dinky_resources" ADD CONSTRAINT "dinky_resources_pkey" PRIMARY KEY ("id"); ALTER TABLE "public"."dinky_resources" ADD CONSTRAINT "dinky_resources_pkey" PRIMARY KEY ("id");
\ No newline at end of file
create table if not exists public.dinky_sys_login_log
(
id integer,
user_id integer,
username varchar(60),
login_type integer,
ip varchar(40),
status integer,
msg text,
create_time timestamp,
access_time timestamp,
update_time timestamp,
is_deleted smallint
);
comment on table public.dinky_sys_login_log is 'dinky_sys_login_log';
alter table public.dinky_sys_login_log
owner to dinky;
-- ----------------------------
-- Table structure for dinky_sys_login_log
-- ----------------------------
DROP TABLE IF EXISTS "public"."dinky_sys_login_log";
CREATE TABLE "public"."dinky_sys_login_log" (
"id" int4 NOT NULL,
"user_id" int8,
"username" varchar(60) COLLATE "pg_catalog"."default",
"login_type" int2,
"ip" varchar(40) COLLATE "pg_catalog"."default",
"status" int2,
"msg" text COLLATE "pg_catalog"."default",
"create_time" timestamp(6) NOT NULL,
"access_time" timestamp(6) NOT NULL,
"update_time" timestamp(6) NOT NULL,
"is_deleted" int2
)
;
COMMENT ON COLUMN "public"."dinky_sys_login_log"."id" IS 'id';
COMMENT ON COLUMN "public"."dinky_sys_login_log"."user_id" IS 'user id';
COMMENT ON COLUMN "public"."dinky_sys_login_log"."username" IS 'user name';
COMMENT ON COLUMN "public"."dinky_sys_login_log"."login_type" IS 'user type (0:LOCAL,1:LDAP,2)';
COMMENT ON COLUMN "public"."dinky_sys_login_log"."ip" IS 'ip';
COMMENT ON COLUMN "public"."dinky_sys_login_log"."status" IS 'login status code';
COMMENT ON COLUMN "public"."dinky_sys_login_log"."msg" IS 'login status msg';
COMMENT ON COLUMN "public"."dinky_sys_login_log"."create_time" IS 'create time';
COMMENT ON COLUMN "public"."dinky_sys_login_log"."access_time" IS 'access time';
COMMENT ON COLUMN "public"."dinky_sys_login_log"."update_time" IS 'update time';
COMMENT ON COLUMN "public"."dinky_sys_login_log"."is_deleted" IS 'is deleted';
...@@ -136,7 +136,6 @@ CREATE TABLE `dinky_metrics` ( ...@@ -136,7 +136,6 @@ CREATE TABLE `dinky_metrics` (
-- ---------------------------- -- ----------------------------
-- Table structure for dinky_resources -- Table structure for dinky_resources
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS dinky_resources;
CREATE TABLE `dinky_resources` ( CREATE TABLE `dinky_resources` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'key', `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'key',
`file_name` varchar(64) COLLATE utf8_bin DEFAULT NULL COMMENT 'file name', `file_name` varchar(64) COLLATE utf8_bin DEFAULT NULL COMMENT 'file name',
...@@ -154,4 +153,27 @@ CREATE TABLE `dinky_resources` ( ...@@ -154,4 +153,27 @@ CREATE TABLE `dinky_resources` (
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Table structure for dinky_sys_login_log
-- ----------------------------
CREATE TABLE `dinky_sys_login_log` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'key',
`user_id` int NOT NULL COMMENT 'user id',
`username` varchar(60) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'username',
`login_type` int NOT NULL COMMENT 'login type(0:LOCAL,1:LDAP)',
`ip` varchar(40) COLLATE utf8mb4_general_ci NOT NULL COMMENT 'ip addr',
`status` int NOT NULL COMMENT 'login status',
`msg` text COLLATE utf8mb4_general_ci NOT NULL COMMENT 'status msg',
`create_time` datetime NOT NULL COMMENT 'create time',
`access_time` datetime DEFAULT NULL COMMENT 'access time',
`update_time` datetime NOT NULL,
`is_deleted` tinyint NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='system login log record'
SET FOREIGN_KEY_CHECKS = 1; SET FOREIGN_KEY_CHECKS = 1;
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