huliguo
2025-05-13 a70919b4f7baab856125f36e5bd41f5ee81be680
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package com.cl.controller;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cl.common.constant.DelFlagConstant;
import com.cl.common.constant.StatusConstant;
import com.cl.common.context.BaseContext;
import com.cl.common.exception.user.LoginErrorException;
import com.cl.common.exception.user.UserException;
import com.cl.common.result.Result;
import com.cl.pojo.dto.*;
import com.cl.pojo.entity.User;
 
import com.cl.pojo.vo.UserVO;
import com.cl.service.UserService;
import com.cl.service.impl.TokenBlacklistService;
import com.cl.util.BCryptPasswordEncoder;
import com.cl.util.JwtUtil;
import com.cl.util.LoginAttemptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
 
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
 
import org.springframework.web.bind.annotation.*;
 
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
 
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户")
public class UserController {
    @Autowired
    private UserService userService;
 
    @Autowired
    private LoginAttemptService loginAttemptService;
 
    @Autowired
    private TokenBlacklistService blacklistService;
 
 
    /**
     * 登录
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<Map<String,String>> login(@RequestBody @Valid LoginDTO dto) {
        //校验该手机号登录失败是否锁定
        boolean locked = loginAttemptService.isLocked(dto.getPhone());
        if (locked) {
            throw new LoginErrorException("连续登录失败,请稍后再试");
        }
        //校验手机号是否存在
        User user = userService.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, dto.getPhone())
                .eq(User::getDelFlag, DelFlagConstant.UNDELETE));
 
        if (user == null) {
            throw new LoginErrorException("用户不存在");
        }
 
        if (!Objects.equals(user.getStatus(), StatusConstant.ENABLE)){
            throw new LoginErrorException("登录失败,当前账号已被冻结");
        }
        //校验密码是否正确
        if (!BCryptPasswordEncoder.matches(dto.getPassword(), user.getPassword())) {
            //失败
            //将手机号加入线程中记录
            loginAttemptService.recordFailedAttempt(dto.getPhone());
            throw new LoginErrorException("登录失败,手机号/密码错误");
        }
        //成功
        loginAttemptService.clearAttempts(dto.getPhone());
        //token加密
        Map<String, Object> claims=new HashMap<>();
        claims.put("phone", dto.getPhone());
        claims.put("id", user.getId());
        String token = JwtUtil.createJWT(claims);
        Map<String,String> map=new HashMap<>();
        map.put("token", token);
        map.put("is_first",user.getIsFirst().toString());
        map.put("name",user.getName());
        map.put("phone",user.getPhone());
        map.put("id", String.valueOf(user.getId()));
        if (1==user.getIsFirst()){
            User user1 = new User();
            user1.setId(user.getId());
            user1.setIsFirst(0);
            userService.updateById(user1);
        }
        return Result.success(map);
    }
    /**
     * 退出登录
     */
    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public Result<String> logout(@RequestHeader("Authorization") String token) {
        // 1. 将令牌加入黑名单
        blacklistService.addToBlacklist(token);
        return Result.success("退出成功");
    }
    /**
     * 修改密码
     */
    @PutMapping("/password")
    @ApiOperation("修改密码")
    public Result<String> password(@RequestBody @Valid PasswordDTO passwordDTO,
                                   @RequestHeader("Authorization") String token) {
        userService.password(passwordDTO,token);
        return Result.success("修改成功");
    }
    /**
     * 修改密码
     */
    @PutMapping("/passwordBeforeLogin")
    @ApiOperation("修改密码(登录前)")
    public Result<String> passwordBeforeLogin(@RequestBody @Valid PasswordBeforeLoginDTO passwordDTO) {
        if (passwordDTO.getPhone().equals("admin")) {
            return Result.error("管理员账号,不可操作");
        }
        return userService.passwordBeforeLogin(passwordDTO);
    }
    /**
     * 添加
     */
    @PostMapping("/addUser")
    @ApiOperation("添加用户")
    public Result<String> addUser(@RequestBody @Valid AddUserDTO addUserDTO) {
        userService.addUser(addUserDTO);
        return Result.success("添加成功");
    }
 
    /**
     * 用户列表查询
     */
    @GetMapping("/pageList")
    @ApiOperation("用户分页查询")
    public Result<IPage<UserVO>>  selectPageUser(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                                                 @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                                                 @RequestParam(value = "name",required = false)String name,
                                                 @RequestParam(value = "phone",required = false)String phone){
        IPage<User> page = new Page<>(pageNum, pageSize);
        IPage<UserVO> iPage=userService.pageList(page,name,phone);
        return Result.success(iPage);
    }
    /**
     * 用户回显
     */
    @GetMapping("/read/{id}")
    @ApiOperation("查看用户(编辑回显)")
    public Result<UserVO> read(@PathVariable("id")Integer id){
        if (id==1){
            throw new UserException("管理员账号,不可操作");
        }
        User user = userService.getById(id);
        UserVO userVO=new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return Result.success(userVO);
    }
    /**
     * 编辑用户
     */
    @PutMapping("/editUser")
    @ApiOperation("编辑用户")
    public Result<String> editUser(@RequestBody @Valid EditUserDTO editUserDTO) {
        if (editUserDTO.getId()==1){
            throw new UserException("管理员账号,不可操作");
        }
        userService.editUser(editUserDTO);
        return Result.success("修改成功");
    }
    /**
     * 冻结/解冻
     */
    @PutMapping("/frozen/{id}")
    @ApiOperation("冻结/解冻")
    public Result<String> frozen(@PathVariable("id") Integer id) {
        if (id==1){
            throw new UserException("管理员账号,不可操作");
        }
        userService.frozen(id);
        return Result.success("修改成功");
    }
 
    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除用户")
    public Result<String> deleteUser(@PathVariable("id")Integer id){
        if (id==1){
            throw new UserException("管理员账号,不可操作");
        }
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,id);
        queryWrapper.eq(User::getDelFlag,DelFlagConstant.UNDELETE);
        User user = userService.getOne(queryWrapper);
        if (null==user){
            throw new UserException("用户不存在");
        }
        user.setDelFlag(DelFlagConstant.DELETE);
        user.setUpdateBy(BaseContext.getCurrentUser().getId());
        user.setUpdateTime(LocalDateTime.now());
        userService.updateById(user);
        return Result.success("删除成功");
    }
    /**
     * 重置密码
     */
    @PutMapping("/resetPassword/{id}")
    @ApiOperation("重置密码")
    public Result<String> resetPassword(@PathVariable("id")Integer id){
        if (id==1){
            throw new UserException("管理员账号,不可操作");
        }
        userService.resetPassword(id);
        return Result.success("删除成功");
    }
 
}