package org.example.controller;
|
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import org.example.common.ServerResponse;
|
import org.example.dao.LogMapper;
|
import org.example.pojo.Log;
|
import org.example.pojo.User;
|
import org.example.server.UserService;
|
import org.example.server.impl.UserServiceImpl;
|
import org.example.util.IpAddressUtil;
|
import org.example.util.MD5Util;
|
import org.example.util.RedisUtil;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestParam;
|
import org.springframework.web.bind.annotation.RestController;
|
|
import javax.servlet.http.HttpServletRequest;
|
import java.security.SecureRandom;
|
import java.util.Base64;
|
import java.util.Date;
|
|
/**
|
* @program: demo
|
* @description:
|
* @create: 2024-07-29 11:17
|
**/
|
@RestController
|
@RequestMapping("/login")
|
public class Login {
|
|
@Autowired
|
private UserServiceImpl userService;
|
|
@Autowired
|
private LogMapper logMapper;
|
|
@PostMapping("/login")
|
public ServerResponse saveUser(@RequestParam("account") String account
|
, @RequestParam("password") String password, HttpServletRequest request) {
|
|
User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getAccount, account));
|
if(null == user){
|
return ServerResponse.createBySuccessMsg("用户不存在");
|
}
|
|
if (!MD5Util.verify(password, user.getPassword())) {
|
return ServerResponse.createBySuccessMsg("密码错误");
|
}
|
|
//判断是否锁定
|
if(user.getIsLock() == 1){
|
return ServerResponse.createBySuccessMsg("账号已被锁定");
|
}
|
|
//判断是否到期
|
if(new Date().after(user.getEndTime())){
|
return ServerResponse.createBySuccessMsg("账号已到期");
|
}
|
|
|
String token = generateToken();
|
RedisUtil.set(user.getAccount(),token);
|
|
String ip = IpAddressUtil.getIpAddress(request);
|
String address = null;
|
address = IpAddressUtil.getIpPossessionByFile(ip);
|
if(null == address){
|
address = IpAddressUtil.getIpAddressByOnline(ip);
|
}
|
Log log = new Log();
|
log.setIp(ip);
|
log.setAccount(account);
|
log.setLoginTime(new Date());
|
log.setAddress(address);
|
logMapper.insert(log);
|
|
return ServerResponse.createBySuccess(token);
|
}
|
|
// 生成指定长度的随机 token
|
public static String generateToken() {
|
SecureRandom secureRandom = new SecureRandom();
|
byte[] token = new byte[16];
|
secureRandom.nextBytes(token);
|
return Base64.getUrlEncoder().withoutPadding().encodeToString(token);
|
}
|
}
|