add spring security's authentication

This commit is contained in:
myh 2023-12-03 23:49:24 +08:00
parent cc0c1359bd
commit 31505cf70b

View File

@ -3,9 +3,10 @@ package com.example.springdemo.controller;
import com.example.springdemo.entities.Users;
import com.example.springdemo.entities.password.UsersPassword;
import com.example.springdemo.service.UsersService;
import com.example.springdemo.utils.RoleVerificationAnnotation;
import jakarta.annotation.Resource;
import lombok.Data;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@ -19,9 +20,9 @@ public class UsersController {
private UsersService usersService;
//添加新用户
@RoleVerificationAnnotation(UserIDList = {1})
@PreAuthorize("hasRole('管理员') or hasAuthority('添加用户')")
@PostMapping("/add")
public Users addUsers(@RequestBody wrapperUserAndPassword wrapperUserAndPassword) {
public Users addUsers(@RequestBody @NotNull wrapperUserAndPassword wrapperUserAndPassword) {
return usersService.addUser(
wrapperUserAndPassword.user,
wrapperUserAndPassword.userPassword);
@ -34,49 +35,49 @@ public class UsersController {
}
//通过ID删除用户
@RoleVerificationAnnotation(UserIDList = {1})
@PreAuthorize("hasRole('管理员') or hasAuthority('删除用户')")
@DeleteMapping("/delete/id")
public void deleteUserById(@RequestParam(name = "id") Long userId) {
usersService.deleteUserById(userId);
}
//通过姓名删除用户
@RoleVerificationAnnotation(UserIDList = {1})
@PreAuthorize("hasAnyRole('管理员','用户') or hasAuthority('删除用户')")
@DeleteMapping("/delete/name")
public void deleteUserByName(@RequestParam(name = "name") String name) {
usersService.deleteUserByName(name);
}
//更新用户信息
@RoleVerificationAnnotation(RoleIDList = {1, 3}, UserIDList = {1})
@PreAuthorize("hasAnyRole('管理员','用户') or hasAuthority('修改用户基本信息')")
@PutMapping("/update/info")
public Users updateUser(@RequestBody Users user) {
return usersService.updateUser(user);
}
//查找全部用户
@RoleVerificationAnnotation(UserIDList = {1})
@PreAuthorize("hasRole('管理员')")
@GetMapping("/find/all")
public List<Users> getUsers() {
return usersService.findAllUsers();
}
//根据姓名查找用户
@RoleVerificationAnnotation(UserIDList = {1})
@PreAuthorize("hasRole('管理员')")
@GetMapping("/find/name")
public Optional<Users> getUsersByName(@RequestParam(name = "name") String name) {
return usersService.findByName(name);
}
//根据ID查找用户
@RoleVerificationAnnotation(UserIDList = {1})
@PreAuthorize("hasRole('管理员')")
@GetMapping("/find/id")
public Optional<Users> getUsersById(@RequestParam(name = "id") Long userId) {
return usersService.findById(userId);
}
//更新用户密码
@RoleVerificationAnnotation(RoleIDList = {1, 3}, UserIDList = {1})
@PreAuthorize("hasAnyRole('管理员','用户') or hasAuthority('修改用户密码')")
@PutMapping("/update/password")
public int updatePassword(@RequestParam(name = "password") String password,
@RequestParam(name = "userId") Long userId) {