修改用户登录逻辑

This commit is contained in:
阿沐 2022-08-28 00:01:17 +08:00
parent 6c5e9884ba
commit 16f0ba8771
15 changed files with 270 additions and 413 deletions

View File

@ -1,7 +1,7 @@
package net.maku.message.cache;
import lombok.AllArgsConstructor;
import net.maku.framework.common.utils.RedisUtils;
import net.maku.framework.common.cache.RedisCache;
import net.maku.message.sms.config.SmsConfig;
import org.springframework.stereotype.Service;
@ -15,7 +15,7 @@ import java.util.List;
@Service
@AllArgsConstructor
public class SmsPlatformCache {
private final RedisUtils redisUtils;
private final RedisCache redisCache;
/**
* 短信平台轮询KEY
@ -31,18 +31,18 @@ public class SmsPlatformCache {
* 获取短信轮询值
*/
public Long getRoundValue() {
return redisUtils.increment(SMS_ROUND_KEY);
return redisCache.increment(SMS_ROUND_KEY);
}
public List<SmsConfig> list() {
return (List<SmsConfig>)redisUtils.get(SMS_PLATFORM_KEY);
return (List<SmsConfig>) redisCache.get(SMS_PLATFORM_KEY);
}
public void save(List<SmsConfig> list) {
redisUtils.set(SMS_PLATFORM_KEY, list);
redisCache.set(SMS_PLATFORM_KEY, list);
}
public void delete() {
redisUtils.delete(SMS_PLATFORM_KEY);
redisCache.delete(SMS_PLATFORM_KEY);
}
}

View File

@ -0,0 +1,107 @@
package net.maku.system.controller;
import cn.hutool.core.lang.UUID;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import net.maku.framework.common.constant.Constant;
import net.maku.framework.common.utils.Result;
import net.maku.framework.security.cache.TokenStoreCache;
import net.maku.framework.security.user.UserDetail;
import net.maku.framework.security.utils.TokenUtils;
import net.maku.system.enums.LoginOperationEnum;
import net.maku.system.service.SysCaptchaService;
import net.maku.system.service.SysLogLoginService;
import net.maku.system.vo.SysLoginVO;
import net.maku.system.vo.SysTokenVO;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* 认证管理
*
* @author 阿沐 babamu@126.com
*/
@RestController
@RequestMapping("sys/auth")
@Tag(name = "认证管理")
@AllArgsConstructor
public class SysAuthController {
private final SysCaptchaService sysCaptchaService;
private final TokenStoreCache tokenStoreCache;
private final AuthenticationManager authenticationManager;
private final SysLogLoginService sysLogLoginService;
@GetMapping("captcha")
@Operation(summary = "验证码")
public Result<Map<String, Object>> captcha() {
// 生成key
String key = UUID.randomUUID().toString();
// 生成base64验证码
String image = sysCaptchaService.generate(key);
// 封装返回数据
Map<String, Object> data = new HashMap<>();
data.put("key", key);
data.put("image", image);
return Result.ok(data);
}
@PostMapping("login")
@Operation(summary = "登录")
public Result<SysTokenVO> login(@RequestBody SysLoginVO login) {
// 验证码效验
boolean flag = sysCaptchaService.validate(login.getKey(), login.getCaptcha());
if (!flag) {
// 保存登录日志
sysLogLoginService.save(login.getUsername(), Constant.FAIL, LoginOperationEnum.CAPTCHA_FAIL.getValue());
return Result.error("验证码错误");
}
Authentication authentication;
try {
// 用户认证
authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword()));
} catch (BadCredentialsException e) {
return Result.error("用户名密码错误");
}
// 用户信息
UserDetail user = (UserDetail) authentication.getPrincipal();
// 生成 accessToken
String accessToken = TokenUtils.generator();
// 保存用户信息到缓存
tokenStoreCache.saveUser(accessToken, user);
return Result.ok(new SysTokenVO(accessToken));
}
@PostMapping("logout")
@Operation(summary = "退出")
public Result<String> logout(HttpServletRequest request) {
String accessToken = TokenUtils.getAccessToken(request);
// 用户信息
UserDetail user = tokenStoreCache.getUser(accessToken);
// 删除用户信息
tokenStoreCache.deleteUser(accessToken);
// 保存登录日志
sysLogLoginService.save(user.getUsername(), Constant.SUCCESS, LoginOperationEnum.LOGOUT_SUCCESS.getValue());
return Result.ok();
}
}

View File

@ -1,75 +0,0 @@
package net.maku.system.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import net.maku.framework.common.page.PageResult;
import net.maku.framework.common.query.Query;
import net.maku.framework.common.utils.Result;
import net.maku.system.convert.SysOauthClientConvert;
import net.maku.system.entity.SysOauthClientEntity;
import net.maku.system.service.SysOauthClientService;
import net.maku.system.vo.SysOauthClientVO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
/**
* 客户端管理
*
* @author 阿沐 babamu@126.com
*/
@RestController
@RequestMapping("sys/client")
@Tag(name="客户端管理")
@AllArgsConstructor
public class SysOauthClientController {
private final SysOauthClientService sysOauthClientService;
@GetMapping("page")
@Operation(summary = "分页")
@PreAuthorize("hasAuthority('sys:client:page')")
public Result<PageResult<SysOauthClientVO>> page(@Valid Query query){
PageResult<SysOauthClientVO> page = sysOauthClientService.page(query);
return Result.ok(page);
}
@GetMapping("{id}")
@Operation(summary = "信息")
@PreAuthorize("hasAuthority('sys:client:info')")
public Result<SysOauthClientVO> get(@PathVariable("id") Long id){
SysOauthClientEntity entity = sysOauthClientService.getById(id);
return Result.ok(SysOauthClientConvert.INSTANCE.convert(entity));
}
@PostMapping
@Operation(summary = "保存")
@PreAuthorize("hasAuthority('sys:client:save')")
public Result<String> save(@RequestBody SysOauthClientVO vo){
sysOauthClientService.save(vo);
return Result.ok();
}
@PutMapping
@Operation(summary = "修改")
@PreAuthorize("hasAuthority('sys:client:update')")
public Result<String> update(@RequestBody @Valid SysOauthClientVO vo){
sysOauthClientService.update(vo);
return Result.ok();
}
@DeleteMapping
@Operation(summary = "删除")
@PreAuthorize("hasAuthority('sys:client:delete')")
public Result<String> delete(@RequestBody List<Long> idList){
sysOauthClientService.delete(idList);
return Result.ok();
}
}

View File

@ -1,65 +0,0 @@
package net.maku.system.controller;
import cn.hutool.core.lang.UUID;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import net.maku.framework.common.utils.Result;
import net.maku.security.service.CaptchaService;
import org.springframework.http.HttpHeaders;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* 认证管理
*
* @author 阿沐 babamu@126.com
*/
@RestController
@RequestMapping("sys/oauth")
@Tag(name="认证管理")
@AllArgsConstructor
public class SysOauthController {
private final CaptchaService captchaService;
private final TokenStore tokenStore;
@GetMapping("captcha")
@Operation(summary = "验证码")
public Result<Map<String, Object>> captcha() {
// 生成key
String key = UUID.randomUUID().toString();
// 生成base64验证码
String image = captchaService.generate(key);
// 封装返回数据
Map<String, Object> data = new HashMap<>();
data.put("key", key);
data.put("image", image);
return Result.ok(data);
}
@PostMapping("logout")
@Operation(summary = "退出")
public Result<String> logout(HttpServletRequest request) {
String access_token = request.getHeader(HttpHeaders.AUTHORIZATION).replace("Bearer ", "");
OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(access_token);
if (oAuth2AccessToken != null) {
tokenStore.removeAccessToken(oAuth2AccessToken);
OAuth2RefreshToken oAuth2RefreshToken = oAuth2AccessToken.getRefreshToken();
tokenStore.removeRefreshToken(oAuth2RefreshToken);
tokenStore.removeAccessTokenUsingRefreshToken(oAuth2RefreshToken);
}
return Result.ok();
}
}

View File

@ -15,7 +15,7 @@ import net.maku.system.service.SysUserPostService;
import net.maku.system.service.SysUserRoleService;
import net.maku.system.service.SysUserService;
import net.maku.system.vo.SysUserPasswordVO;
import net.maku.system.vo.*;
import net.maku.system.vo.SysUserVO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

View File

@ -1,21 +0,0 @@
package net.maku.system.convert;
import net.maku.system.entity.SysOauthClientEntity;
import net.maku.system.vo.SysOauthClientVO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.List;
@Mapper
public interface SysOauthClientConvert {
SysOauthClientConvert INSTANCE = Mappers.getMapper(SysOauthClientConvert.class);
SysOauthClientVO convert(SysOauthClientEntity entity);
SysOauthClientEntity convert(SysOauthClientVO vo);
List<SysOauthClientVO> convertList(List<SysOauthClientEntity> list);
}

View File

@ -1,19 +0,0 @@
package net.maku.system.dao;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.maku.framework.common.dao.BaseDao;
import net.maku.system.entity.SysOauthClientEntity;
import org.apache.ibatis.annotations.Mapper;
/**
* 客户端管理
*
* @author 阿沐 babamu@126.com
*/
@Mapper
public interface SysOauthClientDao extends BaseDao<SysOauthClientEntity> {
default SysOauthClientEntity getByClientId(String clientId){
return this.selectOne(new LambdaQueryWrapper<SysOauthClientEntity>().eq(SysOauthClientEntity::getClientId, clientId));
}
}

View File

@ -1,64 +0,0 @@
package net.maku.system.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import lombok.Data;
import lombok.EqualsAndHashCode;
import net.maku.framework.common.entity.BaseEntity;
/**
* 客户端管理
*
* @author 阿沐 babamu@126.com
*/
@Data
@EqualsAndHashCode(callSuper=false)
@TableName(value = "sys_oauth_client", autoResultMap = true)
public class SysOauthClientEntity extends BaseEntity {
/**
* 客户端ID
*/
private String clientId;
/**
* 客户端密钥
*/
private String clientSecret;
/**
* 资源ids
*/
private String resourceIds;
/**
* 授权范围
*/
private String scope;
/**
* 授权类型
*/
@TableField(typeHandler = JacksonTypeHandler.class)
private String[] authorizedGrantTypes;
/**
* 回调地址
*/
private String webServerRedirectUri;
/**
* 权限标识
*/
private String authorities;
/**
* 访问令牌有效期
*/
private Integer accessTokenValidity;
/**
* 刷新令牌有效期
*/
private Integer refreshTokenValidity;
/**
* 附加信息
*/
private String additionalInformation;
/**
* 自动授权
*/
private String autoapprove;
}

View File

@ -0,0 +1,25 @@
package net.maku.system.service;
/**
* 验证码
*
* @author 阿沐 babamu@126.com
*/
public interface SysCaptchaService {
/**
* 生成验证码
*
* @param key key
* @return 返回base64图片验证码
*/
String generate(String key);
/**
* 验证码效验
*
* @param key key
* @param code 验证码
* @return true成功 false失败
*/
boolean validate(String key, String code);
}

View File

@ -1,25 +0,0 @@
package net.maku.system.service;
import net.maku.framework.common.page.PageResult;
import net.maku.framework.common.query.Query;
import net.maku.framework.common.service.BaseService;
import net.maku.system.entity.SysOauthClientEntity;
import net.maku.system.vo.SysOauthClientVO;
import java.util.List;
/**
* 客户端管理
*
* @author 阿沐 babamu@126.com
*/
public interface SysOauthClientService extends BaseService<SysOauthClientEntity> {
PageResult<SysOauthClientVO> page(Query query);
void save(SysOauthClientVO vo);
void update(SysOauthClientVO vo);
void delete(List<Long> idList);
}

View File

@ -0,0 +1,63 @@
package net.maku.system.service.impl;
import cn.hutool.core.util.StrUtil;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.AllArgsConstructor;
import net.maku.framework.common.cache.RedisCache;
import net.maku.framework.common.cache.RedisKeys;
import net.maku.system.service.SysCaptchaService;
import org.springframework.stereotype.Service;
/**
* 验证码
*
* @author 阿沐 babamu@126.com
*/
@Service
@AllArgsConstructor
public class SysCaptchaServiceImpl implements SysCaptchaService {
private final RedisCache redisCache;
@Override
public String generate(String key) {
// 生成验证码
SpecCaptcha captcha = new SpecCaptcha(150, 40);
captcha.setLen(5);
captcha.setCharType(Captcha.TYPE_DEFAULT);
// 保存到缓存
key = RedisKeys.getCaptchaKey(key);
redisCache.set(key, captcha.text(), 300);
return captcha.toBase64();
}
@Override
public boolean validate(String key, String code) {
if (StrUtil.isBlank(key) || StrUtil.isBlank(code)) {
return false;
}
// 获取验证码
String captcha = getCache(key);
// 效验成功
if (code.equalsIgnoreCase(captcha)) {
return true;
}
return false;
}
private String getCache(String key) {
key = RedisKeys.getCaptchaKey(key);
String captcha = (String) redisCache.get(key);
// 删除验证码
if (captcha != null) {
redisCache.delete(key);
}
return captcha;
}
}

View File

@ -1,52 +0,0 @@
package net.maku.system.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import net.maku.framework.common.page.PageResult;
import net.maku.framework.common.query.Query;
import net.maku.framework.common.service.impl.BaseServiceImpl;
import net.maku.system.convert.SysOauthClientConvert;
import net.maku.system.dao.SysOauthClientDao;
import net.maku.system.entity.SysOauthClientEntity;
import net.maku.system.service.SysOauthClientService;
import net.maku.system.vo.SysOauthClientVO;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 客户端管理
*
* @author 阿沐 babamu@126.com
*/
@Service
public class SysOauthClientServiceImpl extends BaseServiceImpl<SysOauthClientDao, SysOauthClientEntity>
implements SysOauthClientService {
@Override
public PageResult<SysOauthClientVO> page(Query query) {
IPage<SysOauthClientEntity> page = baseMapper.selectPage(getPage(query), Wrappers.emptyWrapper());
return new PageResult<>(SysOauthClientConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
}
@Override
public void save(SysOauthClientVO vo) {
SysOauthClientEntity entity = SysOauthClientConvert.INSTANCE.convert(vo);
//entity.setAuthorizedGrantTypes(JsonUtils.toJsonString(vo.getAuthorizedGrantTypes()));
baseMapper.insert(entity);
}
@Override
public void update(SysOauthClientVO vo) {
SysOauthClientEntity entity = SysOauthClientConvert.INSTANCE.convert(vo);
updateById(entity);
}
@Override
public void delete(List<Long> idList) {
removeByIds(idList);
}
}

View File

@ -0,0 +1,29 @@
package net.maku.system.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
/**
* 用户登录
*
* @author 阿沐 babamu@126.com
*/
@Data
@Schema(description = "用户登录")
public class SysLoginVO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "用户名")
private String username;
@Schema(description = "密码")
private String password;
@Schema(description = "唯一key")
private String key;
@Schema(description = "验证码")
private String captcha;
}

View File

@ -1,68 +0,0 @@
package net.maku.system.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import net.maku.framework.common.utils.DateUtils;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
import java.util.Date;
/**
* 客户端管理
*
* @author 阿沐 babamu@126.com
*/
@Data
@Schema(description = "客户端管理")
public class SysOauthClientVO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "id", required = true)
private Long id;
@Schema(description = "客户端ID", required = true)
@NotBlank(message = "客户端ID不能为空")
private String clientId;
@Schema(description = "客户端密钥", required = true)
@NotBlank(message = "客户端密钥不能为空")
private String clientSecret;
@Schema(description = "资源ids")
private String resourceIds;
@Schema(description = "授权范围", required = true)
@NotBlank(message = "授权范围不能为空")
private String scope;
@Schema(description = "授权类型")
private String[] authorizedGrantTypes;
@Schema(description = "回调地址")
private String webServerRedirectUri;
@Schema(description = "权限标识")
private String authorities;
@Schema(description = "访问令牌有效期", required = true)
@Min(value = 0, message = "访问令牌有效期不能小于0")
private Integer accessTokenValidity;
@Schema(description = "刷新令牌有效期", required = true)
@Min(value = 0, message = "刷新令牌有效期不能小于0")
private Integer refreshTokenValidity;
@Schema(description = "附加信息")
private String additionalInformation;
@Schema(description = "自动授权", required = true)
@NotBlank(message = "自动授权不能为空")
private String autoapprove;
@Schema(description = "创建时间")
@JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN)
private Date createTime;
}

View File

@ -0,0 +1,22 @@
package net.maku.system.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.Serializable;
/**
* 用户Token
*
* @author 阿沐 babamu@126.com
*/
@Data
@AllArgsConstructor
@Schema(description = "用户登录")
public class SysTokenVO implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "access_token")
private String access_token;
}