v0.02 LogBack引入

v0.0
bruce 2025-02-12 12:11:30 +08:00
parent ab9b5a29d6
commit 7ef4e49890
17 changed files with 372 additions and 26 deletions

19
pom.xml
View File

@ -89,6 +89,25 @@
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<!-- 日志系统依赖 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.5.16</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.16</version>
</dependency>
<!--日志框架-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.16</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,95 @@
package com.bruce.sams.Config;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bruce.sams.Entity.SysRole;
import com.bruce.sams.Service.SysUserService;
import com.bruce.sams.Entity.SysUser;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
/**
* Spring Secrutiy
*/
@Configuration
public class SecurityConfig {
private final SysUserService userService;
public SecurityConfig(SysUserService userService) {
this.userService = userService;
}
// 配置 AuthenticationManager处理用户登录
@Bean
public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userDetailsService())
.passwordEncoder(passwordEncoder());
return authenticationManagerBuilder.build();
}
// 配置 UserDetailsService用于从数据库加载用户信息
@Bean
public UserDetailsService userDetailsService() {
return username -> {
// 获取用户信息
SysUser user = userService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserName, username));
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
// 获取角色信息
SysRole role = userService.getRoleByUserId(user.getUserId()); // 假设你提供了这个方法来查询角色
if (role == null) {
throw new UsernameNotFoundException("用户角色不存在");
}
// 将角色添加为 ROLE_ 前缀
return org.springframework.security.core.userdetails.User
.withUsername(user.getUserName())
.password(user.getPasswd())
.roles("ROLE_" + role.getRoleKey()) // 根据角色的 role_key 设置角色,确保加上 ROLE_ 前缀
.build();
};
}
// 配置密码加密方式
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
// 配置 HttpSecurity进行权限管理
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authz -> authz
.requestMatchers("/login", "/register").permitAll() // 登录和注册允许匿名访问
.requestMatchers("/admin/**").hasRole("ADMIN") // 只有 ADMIN 角色才能访问 /admin 路径
.requestMatchers("/user/**").hasRole("USER") // 只有 USER 角色才能访问 /user 路径
.anyRequest().authenticated() // 其他请求需要认证
)
.formLogin(form -> form
.loginPage("/login") // 登录页面
.permitAll()
)
.logout(logout -> logout
.permitAll()
);
return http.build();
}
}

View File

@ -1,6 +1,6 @@
package com.bruce.sams.Controller;
import com.bruce.sams.service.SysLoginService;
import com.bruce.sams.Service.SysLoginService;
import com.bruce.sams.Utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@ -15,15 +15,15 @@ public class LoginController {
/**
*
*
* @param username
* @param schoolId
* @param password
* @return AjaxResult token
*/
@PostMapping
public AjaxResult login(@RequestParam String username, @RequestParam String password) {
public AjaxResult login(@RequestParam String schoolId, @RequestParam String password) {
try {
// 调用登录服务生成Token
String token = sysLoginService.login(username, password);
String token = sysLoginService.login(schoolId, password);
// 返回成功的响应并包含生成的Token
return AjaxResult.success("登录成功", token);

View File

@ -1,18 +1,10 @@
package com.bruce.sams.Controller;
import com.bruce.sams.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private SysUserService userService;
public Object addUesr(){
return null;
}
}

View File

@ -0,0 +1,95 @@
package com.bruce.sams.Entity;
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 lombok.Data;
/**
*
* @TableName sys_role
*/
@TableName(value ="sys_role")
@Data
public class SysRole {
/**
*
*/
@TableId(type = IdType.AUTO)
private Long roleId;
/**
*
*/
private String roleName;
/**
*
*/
private String roleKey;
/**
* 1 2 34
*/
private String dataScope;
/**
* 0 1
*/
private String status;
/**
*
*/
private String remark;
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
SysRole other = (SysRole) that;
return (this.getRoleId() == null ? other.getRoleId() == null : this.getRoleId().equals(other.getRoleId()))
&& (this.getRoleName() == null ? other.getRoleName() == null : this.getRoleName().equals(other.getRoleName()))
&& (this.getRoleKey() == null ? other.getRoleKey() == null : this.getRoleKey().equals(other.getRoleKey()))
&& (this.getDataScope() == null ? other.getDataScope() == null : this.getDataScope().equals(other.getDataScope()))
&& (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus()))
&& (this.getRemark() == null ? other.getRemark() == null : this.getRemark().equals(other.getRemark()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getRoleId() == null) ? 0 : getRoleId().hashCode());
result = prime * result + ((getRoleName() == null) ? 0 : getRoleName().hashCode());
result = prime * result + ((getRoleKey() == null) ? 0 : getRoleKey().hashCode());
result = prime * result + ((getDataScope() == null) ? 0 : getDataScope().hashCode());
result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode());
result = prime * result + ((getRemark() == null) ? 0 : getRemark().hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", roleId=").append(roleId);
sb.append(", roleName=").append(roleName);
sb.append(", roleKey=").append(roleKey);
sb.append(", dataScope=").append(dataScope);
sb.append(", status=").append(status);
sb.append(", remark=").append(remark);
sb.append("]");
return sb.toString();
}
}

View File

@ -8,7 +8,6 @@ import lombok.Data;
/**
*
* @TableName sys_user
*/
@TableName(value ="sys_user")
@Data

View File

@ -0,0 +1,20 @@
package com.bruce.sams.Mapper;
import com.bruce.sams.Entity.SysRole;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* @author bruce
* @description sys_role()Mapper
* @createDate 2025-02-10 17:48:11
* @Entity com.bruce.sams.Entity.SysRole
*/
@Mapper
public interface SysRoleMapper extends BaseMapper<SysRole> {
}

View File

@ -1,4 +1,4 @@
package com.bruce.sams.mapper;
package com.bruce.sams.Mapper;
import com.bruce.sams.Entity.SysUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

View File

@ -1,11 +1,11 @@
package com.bruce.sams.service;
package com.bruce.sams.Service;
public interface SysLoginService {
/**
*
* @param username
* @param schoolId
* @param password
* @return token
*/
public String login(String username, String password);
String login(String schoolId, String password);
}

View File

@ -0,0 +1,13 @@
package com.bruce.sams.Service;
import com.bruce.sams.Entity.SysRole;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author bruce
* @description sys_role()Service
* @createDate 2025-02-10 17:48:11
*/
public interface SysRoleService extends IService<SysRole> {
}

View File

@ -1,5 +1,6 @@
package com.bruce.sams.service;
package com.bruce.sams.Service;
import com.bruce.sams.Entity.SysRole;
import com.bruce.sams.Entity.SysUser;
import com.baomidou.mybatisplus.extension.service.IService;
@ -16,5 +17,12 @@ public interface SysUserService extends IService<SysUser> {
* @param newPassword
* @return T F
*/
public boolean changePassword(Long userId, String newPassword);
boolean changePassword(Long userId, String newPassword);
/**
* ID
* @param userId id
* @return
*/
SysRole getRoleByUserId(Long userId);
}

View File

@ -1,4 +1,4 @@
package com.bruce.sams.service.impl;
package com.bruce.sams.Service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@ -7,8 +7,8 @@ import com.bruce.sams.Exception.User.IncorrectPasswordException;
import com.bruce.sams.Exception.User.UserNotFoundException;
import com.bruce.sams.Utils.PasswordEncoder;
import com.bruce.sams.Utils.TokenUtil;
import com.bruce.sams.mapper.SysUserMapper;
import com.bruce.sams.service.SysLoginService;
import com.bruce.sams.Mapper.SysUserMapper;
import com.bruce.sams.Service.SysLoginService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

View File

@ -0,0 +1,22 @@
package com.bruce.sams.Service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bruce.sams.Entity.SysRole;
import com.bruce.sams.Service.SysRoleService;
import com.bruce.sams.Mapper.SysRoleMapper;
import org.springframework.stereotype.Service;
/**
* @author bruce
* @description sys_role()Service
* @createDate 2025-02-10 17:48:11
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
implements SysRoleService{
}

View File

@ -1,12 +1,14 @@
package com.bruce.sams.service.impl;
package com.bruce.sams.Service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bruce.sams.Entity.SysRole;
import com.bruce.sams.Entity.SysUser;
import com.bruce.sams.Mapper.SysRoleMapper;
import com.bruce.sams.Utils.PasswordEncoder;
import com.bruce.sams.service.SysUserService;
import com.bruce.sams.mapper.SysUserMapper;
import com.bruce.sams.Service.SysUserService;
import com.bruce.sams.Mapper.SysUserMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
@ -21,6 +23,12 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
@Resource
private PasswordEncoder passwordEncoder;
@Autowired
private SysUserMapper userMapper;
@Autowired
private SysRoleMapper roleMapper;
/**
*
* @param entity
@ -68,4 +76,16 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
return this.updateById(user); // 更新用户信息
}
/**
* ID
* @param userId id
* @return
*/
public SysRole getRoleByUserId(Long userId){
//todo
Long roleId =userMapper.selectById(userId).getRoleId();
return roleMapper.selectById(roleId);
}
}

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bruce.sams.mapper.SysRoleMapper">
<resultMap id="BaseResultMap" type="com.bruce.sams.Entity.SysRole">
<id property="roleId" column="role_id" />
<result property="roleName" column="role_name" />
<result property="roleKey" column="role_key" />
<result property="dataScope" column="data_scope" />
<result property="status" column="status" />
<result property="remark" column="remark" />
</resultMap>
<sql id="Base_Column_List">
role_id,role_name,role_key,data_scope,status,remark
</sql>
</mapper>

View File

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--
CONSOLE :表示当前的日志信息是可以输出到控制台的。
-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!--输出流对象 默认 System.out 改为 System.err-->
<target>System.out</target>
<encoder>
<!--格式化输出:%d表示日期%thread表示线程名%-5level级别从左显示5个字符宽度
%msg日志消息%n是换行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] %c [%thread] : %msg%n</pattern>
</encoder>
</appender>
<!-- File是输出的方向通向文件的 -->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
<charset>utf-8</charset>
</encoder>
<!--日志输出路径-->
<file>/log/itheima-data.log</file>
<!--指定日志文件拆分和压缩规则-->
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--通过指定压缩文件名称,来确定分割文件方式-->
<fileNamePattern>/log/itheima-data2-%d{yyyy-MMdd}.log%i.gz</fileNamePattern>
<!--文件拆分大小-->
<maxFileSize>1MB</maxFileSize>
</rollingPolicy>
</appender>
<!--
level:用来设置打印级别大小写无关TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
默认debug
<root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
-->
<root level="ALL">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="FILE" />
</root>
</configuration>