Browse Source

用户登录、用户管理、角色管理

chubin
郑楚滨 3 months ago
parent
commit
c0a9eaf576
  1. 8
      .idea/.gitignore
  2. 14
      .idea/compiler.xml
  3. 9
      .idea/encodings.xml
  4. 9
      .idea/excise-demo.iml
  5. 20
      .idea/jarRepositories.xml
  6. 15
      .idea/misc.xml
  7. 8
      .idea/modules.xml
  8. 124
      .idea/uiDesigner.xml
  9. 6
      .idea/vcs.xml
  10. 33
      demo/demo/.gitignore
  11. 121
      demo/demo/pom.xml
  12. 102
      demo/demo/src/main/java/demo/Controller/RoleController.java
  13. 164
      demo/demo/src/main/java/demo/Controller/UserController.java
  14. 13
      demo/demo/src/main/java/demo/DemoApplication.java
  15. 9
      demo/demo/src/main/java/demo/Entity/LoginRequest.java
  16. 64
      demo/demo/src/main/java/demo/Entity/Result.java
  17. 29
      demo/demo/src/main/java/demo/Entity/Role.java
  18. 9
      demo/demo/src/main/java/demo/Entity/RoleVO.java
  19. 32
      demo/demo/src/main/java/demo/Entity/User.java
  20. 13
      demo/demo/src/main/java/demo/Entity/UserVO.java
  21. 31
      demo/demo/src/main/java/demo/Mapper/RoleMapper.java
  22. 32
      demo/demo/src/main/java/demo/Mapper/UserMapper.java
  23. 45
      demo/demo/src/main/java/demo/Service/RoleService.java
  24. 56
      demo/demo/src/main/java/demo/Service/UserService.java
  25. 21
      demo/demo/src/main/resources/application.yml
  26. 6
      demo/demo/src/main/resources/static/index.html
  27. 23
      demo/demo/src/test/java/demo/DemoApplicationTests.java

8
.idea/.gitignore

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

14
.idea/compiler.xml

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="demo" />
</profile>
</annotationProcessing>
</component>
</project>

9
.idea/encodings.xml

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/demo/demo/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/demo/demo/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/demo/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/demo/src/main/resources" charset="UTF-8" />
</component>
</project>

9
.idea/excise-demo.iml

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

20
.idea/jarRepositories.xml

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="http://maven.aliyun.com/nexus/content/repositories/central/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>

15
.idea/misc.xml

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/demo/pom.xml" />
<option value="$PROJECT_DIR$/demo/demo/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
.idea/modules.xml

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/excise-demo.iml" filepath="$PROJECT_DIR$/.idea/excise-demo.iml" />
</modules>
</component>
</project>

124
.idea/uiDesigner.xml

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

6
.idea/vcs.xml

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

33
demo/demo/.gitignore

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

121
demo/demo/pom.xml

@ -0,0 +1,121 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>demo</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.6.13</spring-boot.version>
</properties>
<dependencies>
<!-- MyBatis Spring Boot Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version> <!-- 请根据实际情况选择合适的版本 -->
</dependency>
<!-- MyBatis core library -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version> <!-- 请根据实际情况选择合适的版本 -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version> <!-- 请根据实际情况选择合适的版本 -->
</dependency>
<!-- Bean Validation API -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version> <!-- 请根据实际情况选择合适的版本 -->
</dependency>
<!-- Hibernate Validator (Bean Validation 实现) -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.2.0.Final</version> <!-- 请根据实际情况选择合适的版本 -->
</dependency>
<!-- Spring Boot Starter Data Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>demo.DemoApplication</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

102
demo/demo/src/main/java/demo/Controller/RoleController.java

@ -0,0 +1,102 @@
package demo.Controller;
import demo.Entity.*;
import demo.Service.RoleService;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/role")
@Validated
public class RoleController {
@Autowired
private RoleService roleService;
//角色增删改查
/**
* @增
* @param roleVO
* @return
*/
@PostMapping("/insert")
public Result<String> insertRole(@RequestBody RoleVO roleVO) {
// 查询用户名是否被占用
Role role = roleService.findByRoleName(roleVO.getRoleName());
if (role==null){
// 没有占用,新增
// 创建一个LocalDateTime对象
LocalDateTime localDateTime = LocalDateTime.now();
// 将LocalDateTime转换为Instant
Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
// 将Instant转换为Date
Date date = Date.from(instant);
roleService.insert(roleVO.getRoleName(), roleVO.getRoleCode(), date);
return Result.success("添加成功");
}else {
return Result.error(401, "角色已有");
}
}
/**
* @删
* @param roleName
* @return
*/
@DeleteMapping("/delete")
public Result<String> deleteRole(@Valid String roleName) {
Role role = roleService.findByRoleName(roleName);
if (role==null){
return Result.error(401, "角色不存在");
}else {
roleService.deleteByRoleName(roleName);
return Result.success("删除成功");
}
}
@PutMapping("/update")
public Result<String> updateRole(@Valid RoleVO roleVO) {
Role role = roleService.findByRoleName(roleVO.getRoleName());
if (role==null){
return Result.error(401, "角色不存在");
}else {
// 创建一个LocalDateTime对象
LocalDateTime localDateTime = LocalDateTime.now();
// 将LocalDateTime转换为Instant
Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
// 将Instant转换为Date
Date date = Date.from(instant);
roleService.update(roleVO, date);
return Result.success("修改成功");
}
}
@GetMapping("/query")
public Result<List<Role>> queryRole() {
List<Role> roleList = roleService.findAll();
log.info("Retrieved roles: {}", roleList);
return Result.success(roleList);
}
@PostMapping("/queryByRoleCode")
public Result<Role> queryByRoleCode(@Valid String roleCode) {
Role role = roleService.findByRoleCode(roleCode);
if (role==null){
return Result.error(401, "角色不存在");
}
return Result.success(role);
}
}

164
demo/demo/src/main/java/demo/Controller/UserController.java

@ -0,0 +1,164 @@
package demo.Controller;
import demo.Entity.*;
import demo.Service.RoleService;
import demo.Service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
import java.util.Set;
@Slf4j
@RestController
@RequestMapping("/user")
@Validated
public class UserController {
@Autowired
private UserService userService;
@Autowired
private StringRedisTemplate redisTemplate;
private final int MAX_FAILED_ATTEMPTS = 5;
private static final Duration LOCK_TIME = Duration.ofMinutes(1); // 锁定时间1分钟
private String LOGIN_ATTEMPTS_KEY = "login_attempts_";
private static final String LOCKED_KEY = "locked_";
//用户增删改查
/**
* @增
* @param userVO
* @return
*/
@PostMapping("/register")
public Result<String> register(@RequestBody UserVO userVO) {
// 查询用户名是否被占用
User user = userService.findByUserName(userVO.getLoginName());
if (user==null){
// 没有占用,进行注册
userService.register(userVO.getLoginName(), userVO.getUserChnName(), userVO.getPassword());
return Result.success("注册成功");
}else {
return Result.error(401, "用户名已被占用");
}
}
/**
* @删
* @param loginName
* @return
*/
@DeleteMapping("/delete")
public Result<String> delete(@Pattern(regexp = "^\\S{5,16}$") String loginName){
// 查询用户名是否被占用
User user = userService.findByUserName(loginName);
if (user!=null){
// 存在,进行删除
userService.deleteByUserName(loginName);
return Result.success("删除成功");
}else {
return Result.error(401, "用户名不存在");
}
}
/**
* @改
* @param userVo
* @return
*/
@PutMapping("/update")
public Result<String> update(@Valid UserVO userVo){
// 查询用户名是否被占用
User user = userService.findByUserName(userVo.getLoginName());
if (user!=null){
// 存在,进行更新
// 创建一个LocalDateTime对象
LocalDateTime localDateTime = LocalDateTime.now();
// 将LocalDateTime转换为Instant
Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
// 将Instant转换为Date
Date date = Date.from(instant);
userService.updateByUserName(userVo.getLoginName(), userVo.getUserChnName(), date, userVo.getPassword());
return Result.success("更新成功");
}else {
return Result.error(401, "用户名不存在");
}
}
/**
* @查
* @param loginName
* @param password
* @return
*/
@PostMapping("/login")
public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String loginName, @Pattern(regexp = "^\\S{5,16}$") String password){
// 检查用户是否已被锁定
String lockedKey = LOCKED_KEY + loginName;
if (redisTemplate.hasKey(lockedKey)) {
return Result.error(403, "账户已被锁定,请稍后再试。");
}
// 获取当前用户登录尝试次数
String attemptsKey = LOGIN_ATTEMPTS_KEY + loginName;
String attempts = redisTemplate.opsForValue().get(attemptsKey);
int currentAttempts = attempts != null ? Integer.parseInt(attempts) : 0;
// 根据用户名查询用户
User loginUser = userService.findByUserName(loginName);
// 判断用户是否存在
if(loginUser == null){
return Result.error(401,"用户名不存在");
}
// 判断密码是否正确
if (!loginUser.getPassword().equals(password)) {
// 增加登录失败次数
redisTemplate.opsForValue().increment(attemptsKey, 1);
// 如果登录失败次数达到上限,则设置锁定状态
if (currentAttempts + 1 >= MAX_FAILED_ATTEMPTS) {
// 设置锁定状态
redisTemplate.opsForValue().set(lockedKey, "true");
// 设置过期时间
redisTemplate.expire(lockedKey, LOCK_TIME);
// 删除登录失败次数
redisTemplate.delete(attemptsKey);
}
return Result.error(401, "密码错误,已尝试 " + (currentAttempts + 1) + " 次,还剩余 " + (MAX_FAILED_ATTEMPTS - 1 - currentAttempts) + " 次。");
} else {
// 清除登录失败次数
redisTemplate.delete(attemptsKey);
return Result.success("登录成功");
}
}
@GetMapping("/query")
public Result<List<User>> query(){
return Result.success(userService.query());
}
@PostMapping("/queryByUserName")
public Result<User> queryByUserName(@Valid String loginName){
User user = userService.queryByUserName(loginName);
if(user==null){
return Result.error(401, "用户不存在");
}
return Result.success(userService.queryByUserName(loginName));
}
}

13
demo/demo/src/main/java/demo/DemoApplication.java

@ -0,0 +1,13 @@
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//@MapperScan("demo.Mapper") // 指定扫描的包路径
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

9
demo/demo/src/main/java/demo/Entity/LoginRequest.java

@ -0,0 +1,9 @@
package demo.Entity;
import lombok.Data;
@Data
public class LoginRequest {
private String loginName;
private String password;
}

64
demo/demo/src/main/java/demo/Entity/Result.java

@ -0,0 +1,64 @@
package demo.Entity;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 结果状态码
*/
private Integer code;
/**
* 结果消息
*/
private String message;
/**
* 返回的数据
*/
private T data;
/**
* 成功的静态工厂方法
*
* @param data 数据
* @param <T> 泛型类型
* @return Result对象
*/
public static <T> Result<T> success(T data) {
return Result.<T>builder()
.code(200)
.message("Success")
.data(data)
.build();
}
/**
* 失败的静态工厂方法
*
* @param code 状态码
* @param message 错误消息
* @param <T> 泛型类型
* @return Result对象
*/
public static <T> Result<T> error(Integer code, String message) {
return Result.<T>builder()
.code(code)
.message(message)
.build();
}
}

29
demo/demo/src/main/java/demo/Entity/Role.java

@ -0,0 +1,29 @@
package demo.Entity;
import lombok.Data;
import javax.persistence.*;
import java.util.Date;
@Entity
@Data
@Table(name = "role")
public class Role {
@Id
@Column(length = 32, nullable = false)
private int id;
@Column(length = 50)
private String roleName;
@Column(length = 50)
private String roleCode;
@Temporal(TemporalType.TIMESTAMP)
@Column()
private Date createTime;
@Temporal(TemporalType.TIMESTAMP)
@Column()
private Date updateTime;
}

9
demo/demo/src/main/java/demo/Entity/RoleVO.java

@ -0,0 +1,9 @@
package demo.Entity;
import lombok.Data;
@Data
public class RoleVO {
private String roleName;
private String roleCode;
}

32
demo/demo/src/main/java/demo/Entity/User.java

@ -0,0 +1,32 @@
package demo.Entity;
import lombok.Data;
import javax.persistence.*;
import java.util.Date;
@Entity
@Data
@Table(name = "user")
public class User {
@Id
@Column(length = 32, nullable = false)
private int id;
@Column(length = 50)
private String loginName;
@Column(length = 50)
private String userChnName;
@Temporal(TemporalType.TIMESTAMP)
@Column()
private Date createTime;
@Temporal(TemporalType.TIMESTAMP)
@Column()
private Date updateTime;
@Column(length = 16)
private String password;
}

13
demo/demo/src/main/java/demo/Entity/UserVO.java

@ -0,0 +1,13 @@
package demo.Entity;
import lombok.Data;
@Data
public class UserVO {
private String loginName;
private String userChnName;
private String password;
}

31
demo/demo/src/main/java/demo/Mapper/RoleMapper.java

@ -0,0 +1,31 @@
package demo.Mapper;
import demo.Entity.Role;
import demo.Entity.RoleVO;
import demo.Entity.User;
import org.apache.ibatis.annotations.*;
import java.util.Date;
import java.util.List;
@Mapper
public interface RoleMapper {
@Insert("insert into role(ROLE_NAME, ROLE_CODE, CREATE_TIME, UPDATE_TIME) values(#{roleName}, #{roleCode}, #{date}, #{date})")
void insert(@Param("roleName") String roleName, @Param("roleCode") String roleCode, @Param("date") Date date);
@Select("select * from role where ROLE_NAME = #{roleName}")
Role findByRoleName(@Param("roleName") String roleName);
@Delete("delete from role where ROLE_NAME = #{roleName}")
void deleteByRoleName(@Param("roleName") String roleName);
@Update("update role set ROLE_NAME = #{roleName}, ROLE_CODE = #{roleCode}, UPDATE_TIME = #{date} where ROLE_NAME = #{roleName}")
void update(@Param("roleName") String roleName, @Param("roleCode") String roleCode, @Param("date") Date date);
@Select("select * from role")
List<Role> findAll();
@Select("select * from role where ROLE_CODE = #{roleCode}")
Role findByRoleCode(@Param("roleCode") String roleCode);
}

32
demo/demo/src/main/java/demo/Mapper/UserMapper.java

@ -0,0 +1,32 @@
package demo.Mapper;
import demo.Entity.User;
import org.apache.ibatis.annotations.*;
import java.util.Date;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE LOGIN_NAME = #{loginName} and PASSWORD = #{password}")
User findByMessage(String loginName, String password);
@Insert("INSERT INTO user (ID, LOGIN_NAME, USER_CHN_NAME, CREATE_TIME, UPDATE_TIME, PASSWORD) VALUES (NULL, #{loginName}, #{userChnName}, #{date}, #{date}, #{password})")
void register(@Param("loginName") String loginName, @Param("userChnName") String userChnName, @Param("date") Date date, @Param("password") String password);
@Select("SELECT * FROM user WHERE LOGIN_NAME = #{loginName}")
User findByUsername(String loginName);
@Delete("DELETE FROM user WHERE LOGIN_NAME = #{loginName}")
void deleteByUserName(String loginName);
@Update("UPDATE user SET USER_CHN_NAME = #{userChnName}, UPDATE_TIME = #{updateTime}, PASSWORD = #{password} WHERE LOGIN_NAME = #{loginName}")
void updateByUserName(@Param("loginName") String loginName, @Param("userChnName") String userChnName, @Param("updateTime") Date updateTime, @Param("password") String password);
@Select("SELECT * FROM user")
List<User> findAll();
@Select("SELECT * FROM user WHERE LOGIN_NAME = #{loginName}")
User queryByUserName(@Param("loginName")String loginName);
}

45
demo/demo/src/main/java/demo/Service/RoleService.java

@ -0,0 +1,45 @@
package demo.Service;
import demo.Entity.Role;
import demo.Entity.RoleVO;
import demo.Entity.User;
import demo.Mapper.RoleMapper;
import demo.Mapper.UserMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class RoleService {
@Autowired
private RoleMapper roleMapper;
public void insert(String roleName, String roleCode, Date date){
roleMapper.insert(roleName, roleCode, date);
}
public Role findByRoleName(String roleName){
return roleMapper.findByRoleName(roleName);
}
public void deleteByRoleName(String roleName){
roleMapper.deleteByRoleName(roleName);
}
public void update(RoleVO roleVO, Date date){
roleMapper.update(roleVO.getRoleName(), roleVO.getRoleCode(), date);
}
public List<Role> findAll(){
return roleMapper.findAll();
}
public Role findByRoleCode(String roleCode){
return roleMapper.findByRoleCode(roleCode);
}
}

56
demo/demo/src/main/java/demo/Service/UserService.java

@ -0,0 +1,56 @@
package demo.Service;
import demo.Entity.Role;
import demo.Entity.User;
import demo.Mapper.UserMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User findByMessage(String loginName, String password){
return userMapper.findByMessage(loginName, password);
}
public void register(String loginName, String UserChnName, String password){
// 创建一个LocalDateTime对象
LocalDateTime localDateTime = LocalDateTime.now();
// 将LocalDateTime转换为Instant
Instant instant = localDateTime.toInstant(ZoneOffset.UTC);
// 将Instant转换为Date
Date date = Date.from(instant);
userMapper.register(loginName, UserChnName, date, password);
}
public User findByUserName(String loginName){
return userMapper.findByUsername(loginName);
}
public void deleteByUserName(String loginName){
userMapper.deleteByUserName(loginName);
}
public void updateByUserName(String loginName, String userChnName, Date updateTime, String password){
userMapper.updateByUserName(loginName, userChnName, updateTime, password);
}
public List<User> query(){
return userMapper.findAll();
}
public User queryByUserName(String loginName){
return userMapper.queryByUserName(loginName);
}
}

21
demo/demo/src/main/resources/application.yml

@ -0,0 +1,21 @@
server:
port: 8080
spring:
datasource:
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test_repo
redis:
host: localhost
port: 6379
password: 123456 # 如果没有密码,可以省略
database: 0 # 默认数据库索引
timeout: 5000ms # 连接超时时间
mybatis:
configuration:
#开启驼峰命名转换
map-underscore-to-camel-case: true
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.demo.entity

6
demo/demo/src/main/resources/static/index.html

@ -0,0 +1,6 @@
<html>
<body>
<h1>hello word!!!</h1>
<p>this is a html page</p>
</body>
</html>

23
demo/demo/src/test/java/demo/DemoApplicationTests.java

@ -0,0 +1,23 @@
package demo;
import demo.Mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
@SpringBootTest
class DemoApplicationTests {
@Autowired
private DataSource dataSource;
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() throws Exception {
System.out.println(dataSource.getConnection());
}
}
Loading…
Cancel
Save