Initial project source

这个提交包含在:
apple
2026-11-20 15:32:57 +08:00
当前提交 fb47c07f7c
共修改 8405 个文件,包含 806907 行新增和 0 行删除
+26
查看文件
@@ -0,0 +1,26 @@
# 贝尔实验室 Spring 官方推荐镜像 JDK下载地址 https://bell-sw.com/pages/downloads/
FROM bellsoft/liberica-openjdk-rocky:21.0.12-cds
# FROM bellsoft/liberica-openjdk-rocky:25.0.4-cds
# FROM findepi/graalvm:java21-native
LABEL maintainer="AiXun Technology <343559364@qq.com>"
RUN mkdir -p /aixun-admin/auth/logs \
/aixun-admin/auth/temp \
/aixun-admin/skywalking/agent
WORKDIR /aixun-admin/auth
ENV SERVER_PORT=9210 LANG=C.UTF-8 LC_ALL=C.UTF-8 JAVA_GC_OPTS="-XX:+UseZGC" JAVA_OPTS=""
EXPOSE ${SERVER_PORT}
ADD ./target/aixun-auth.jar ./app.jar
SHELL ["/bin/bash", "-c"]
ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -Dserver.port=${SERVER_PORT} \
#-Dskywalking.agent.service_name=aixun-auth \
#-javaagent:/aixun-admin/skywalking/agent/skywalking-agent.jar \
-XX:+HeapDumpOnOutOfMemoryError ${JAVA_GC_OPTS} ${JAVA_OPTS} \
-jar app.jar
+130
查看文件
@@ -0,0 +1,130 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-admin</artifactId>
<version>${revision}</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>aixun-auth</artifactId>
<description>
aixun-auth 认证授权中心
</description>
<dependencies>
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-nacos</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-captcha</artifactId>
</dependency>
<!-- AiXun Common Security-->
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-security</artifactId>
</dependency>
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-social</artifactId>
</dependency>
<!-- AiXun Common Log -->
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-log</artifactId>
</dependency>
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-doc</artifactId>
</dependency>
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-web</artifactId>
</dependency>
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-redis</artifactId>
</dependency>
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-encrypt</artifactId>
</dependency>
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-dubbo</artifactId>
</dependency>
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-seata</artifactId>
</dependency>
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-common-service-impl</artifactId>
</dependency>
<dependency>
<groupId>cn.aixunkeji</groupId>
<artifactId>aixun-api-resource</artifactId>
</dependency>
<!-- 自定义负载均衡(多团队开发使用) -->
<!-- <dependency>-->
<!-- <groupId>cn.aixunkeji</groupId>-->
<!-- <artifactId>aixun-common-loadbalancer</artifactId>-->
<!-- </dependency>-->
<!-- ELK 日志收集 -->
<!-- <dependency>-->
<!-- <groupId>cn.aixunkeji</groupId>-->
<!-- <artifactId>aixun-common-logstash</artifactId>-->
<!-- </dependency>-->
<!-- skywalking 日志收集 -->
<!-- <dependency>-->
<!-- <groupId>cn.aixunkeji</groupId>-->
<!-- <artifactId>aixun-common-skylog</artifactId>-->
<!-- </dependency>-->
<!-- prometheus 监控 -->
<!-- <dependency>-->
<!-- <groupId>cn.aixunkeji</groupId>-->
<!-- <artifactId>aixun-common-prometheus</artifactId>-->
<!-- </dependency>-->
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,21 @@
package cn.aixunkeji.auth;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
/**
* 认证授权中心
*
*/
@EnableDubbo
@SpringBootApplication
public class AiXunAuthApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(AiXunAuthApplication.class);
application.setApplicationStartup(new BufferingApplicationStartup(2048));
application.run(args);
System.out.println("(♥◠‿◠)ノ゙ 认证授权中心启动成功 ლ(´ڡ`ლ)゙ ");
}
}
@@ -0,0 +1,12 @@
package cn.aixunkeji.auth.config;
import org.springframework.context.annotation.Configuration;
/**
* 验证码配置
*
*/
@Configuration
public class CaptchaConfig {
}
@@ -0,0 +1,196 @@
package cn.aixunkeji.auth.config;
import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.img.GraphicsUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.Serial;
import java.util.concurrent.ThreadLocalRandom;
/**
* 带干扰线、波浪、圆的验证码
*
*/
public class WaveAndCircleCaptcha extends AbstractCaptcha {
@Serial
private static final long serialVersionUID = 1L;
// 构造方法(略,与之前一致)
public WaveAndCircleCaptcha(int width, int height) {
this(width, height, 4);
}
public WaveAndCircleCaptcha(int width, int height, int codeCount) {
this(width, height, codeCount, 6);
}
public WaveAndCircleCaptcha(int width, int height, int codeCount, int interfereCount) {
this(width, height, new RandomGenerator(codeCount), interfereCount);
}
public WaveAndCircleCaptcha(int width, int height, CodeGenerator generator, int interfereCount) {
super(width, height, generator, interfereCount);
}
public WaveAndCircleCaptcha(int width, int height, int codeCount, int interfereCount, float size) {
super(width, height, new RandomGenerator(codeCount), interfereCount, size);
}
@Override
public Image createImage(String code) {
final BufferedImage image = new BufferedImage(
width,
height,
(null == this.background) ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_INT_RGB
);
final Graphics2D g = ImgUtil.createGraphics(image, this.background);
try {
drawString(g, code);
// 扭曲
shear(g, this.width, this.height, ObjectUtil.defaultIfNull(this.background, Color.WHITE));
drawInterfere(g);
} finally {
g.dispose();
}
return image;
}
private void drawString(Graphics2D g, String code) {
// 设置抗锯齿(让字体渲染更清晰)
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
if (this.textAlpha != null) {
g.setComposite(this.textAlpha);
}
GraphicsUtil.drawStringColourful(g, code, this.font, this.width, this.height);
}
protected void drawInterfere(Graphics2D g) {
ThreadLocalRandom random = RandomUtil.getRandom();
int circleCount = Math.max(0, this.interfereCount - 1);
// 圈圈
for (int i = 0; i < circleCount; i++) {
g.setColor(ImgUtil.randomColor(random));
int x = random.nextInt(width);
int y = random.nextInt(height);
int w = random.nextInt(height >> 1);
int h = random.nextInt(height >> 1);
g.drawOval(x, y, w, h);
}
// 仅 1 条平滑波浪线
if (this.interfereCount >= 1) {
g.setColor(getRandomColor(120, 230, random));
drawSmoothWave(g, random);
}
}
private void drawSmoothWave(Graphics2D g, ThreadLocalRandom random) {
int amplitude = random.nextInt(8) + 5; // 波动幅度
int wavelength = random.nextInt(40) + 30; // 波长
double phase = random.nextDouble() * Math.PI * 2;
// ✅ 关键:限制 baseY 在中间区域
int centerY = height / 2;
int verticalJitter = Math.max(5, height / 6); // 至少偏移5像素
int baseY = centerY - verticalJitter + random.nextInt(verticalJitter * 2);
g.setStroke(new BasicStroke(2.5f)); // 线宽
int[] xPoints = new int[width];
int[] yPoints = new int[width];
for (int x = 0; x < width; x++) {
int y = baseY + (int) (amplitude * Math.sin((double) x / wavelength * 2 * Math.PI + phase));
// 限制 y 不要超出图像边界(可选)
y = Math.max(amplitude, Math.min(y, height - amplitude));
xPoints[x] = x;
yPoints[x] = y;
}
g.drawPolyline(xPoints, yPoints, width);
}
private Color getRandomColor(int min, int max, ThreadLocalRandom random) {
int range = max - min;
return new Color(
min + random.nextInt(range),
min + random.nextInt(range),
min + random.nextInt(range)
);
}
/**
* 扭曲
*
* @param g {@link Graphics}
* @param w1 w1
* @param h1 h1
* @param color 颜色
*/
private void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
/**
* X坐标扭曲
*
* @param g {@link Graphics}
* @param w1 宽
* @param h1 高
* @param color 颜色
*/
private void shearX(Graphics g, int w1, int h1, Color color) {
int period = RandomUtil.randomInt(this.width);
int frames = 1;
int phase = RandomUtil.randomInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
/**
* Y坐标扭曲
*
* @param g {@link Graphics}
* @param w1 宽
* @param h1 高
* @param color 颜色
*/
private void shearY(Graphics g, int w1, int h1, Color color) {
int period = RandomUtil.randomInt(this.height >> 1);
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
g.setColor(color);
// 擦除原位置的痕迹
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
@@ -0,0 +1,92 @@
package cn.aixunkeji.auth.controller;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import cn.aixunkeji.auth.config.WaveAndCircleCaptcha;
import cn.aixunkeji.auth.domain.vo.CaptchaVo;
import cn.aixunkeji.auth.properties.CaptchaProperties;
import cn.aixunkeji.common.core.constant.Constants;
import cn.aixunkeji.common.core.constant.GlobalConstants;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.common.core.utils.SpringUtils;
import cn.aixunkeji.common.core.utils.StringUtils;
import cn.aixunkeji.common.redis.annotation.RateLimiter;
import cn.aixunkeji.common.redis.enums.LimitType;
import cn.aixunkeji.common.redis.utils.RedisUtils;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.awt.*;
import java.time.Duration;
/**
* 验证码操作处理
*
*/
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
public class CaptchaController {
private final CaptchaProperties captchaProperties;
/**
* 生成验证码
*/
@GetMapping("/code")
public R<CaptchaVo> getCode() {
CaptchaVo captchaVo = new CaptchaVo();
boolean captchaEnabled = captchaProperties.getEnabled();
if (!captchaEnabled) {
captchaVo.setCaptchaEnabled(false);
return R.ok(captchaVo);
}
return R.ok(SpringUtils.getAopProxy(this).getCodeImpl());
}
/**
* 生成验证码
* 独立方法避免验证码关闭之后仍然走限流
*/
@RateLimiter(time = 60, count = 10, limitType = LimitType.IP)
public CaptchaVo getCodeImpl() {
// 保存验证码信息
String uuid = IdUtil.simpleUUID();
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + uuid;
// 生成验证码
String captchaType = captchaProperties.getType();
CodeGenerator codeGenerator;
if ("math".equals(captchaType)) {
codeGenerator = new MathGenerator(captchaProperties.getNumberLength(), false);
} else {
codeGenerator = new RandomGenerator(captchaProperties.getCharLength());
}
WaveAndCircleCaptcha captcha = new WaveAndCircleCaptcha(160, 60);
// captcha.setBackground(Color.WHITE); // 不设置就是透明底
captcha.setFont(new Font("Arial", Font.BOLD, 45));
captcha.setGenerator(codeGenerator);
captcha.createCode();
// 如果是数学验证码,使用SpEL表达式处理验证码结果
String code = captcha.getCode();
if ("math".equals(captchaType)) {
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(StringUtils.remove(code, "="));
code = exp.getValue(String.class);
}
RedisUtils.setCacheObject(verifyKey, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
CaptchaVo captchaVo = new CaptchaVo();
captchaVo.setUuid(uuid);
captchaVo.setImg(captcha.getImageBase64());
return captchaVo;
}
}
@@ -0,0 +1,162 @@
package cn.aixunkeji.auth.controller;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import cn.aixunkeji.auth.domain.vo.LoginVo;
import cn.aixunkeji.auth.form.RegisterBody;
import cn.aixunkeji.auth.form.SocialLoginBody;
import cn.aixunkeji.auth.service.IAuthStrategy;
import cn.aixunkeji.auth.service.SysLoginService;
import cn.aixunkeji.common.core.constant.SystemConstants;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.common.core.domain.model.LoginBody;
import cn.aixunkeji.common.core.utils.MessageUtils;
import cn.aixunkeji.common.core.utils.StringUtils;
import cn.aixunkeji.common.core.utils.ValidatorUtils;
import cn.aixunkeji.common.encrypt.annotation.ApiEncrypt;
import cn.aixunkeji.common.json.utils.JsonUtils;
import cn.aixunkeji.common.social.config.properties.SocialLoginConfigProperties;
import cn.aixunkeji.common.social.config.properties.SocialProperties;
import cn.aixunkeji.common.social.utils.SocialUtils;
import cn.aixunkeji.system.api.RemoteClientService;
import cn.aixunkeji.system.api.RemoteConfigService;
import cn.aixunkeji.system.api.RemoteSocialService;
import cn.aixunkeji.system.api.domain.vo.RemoteClientVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
/**
* token 控制
*
*/
@Slf4j
@RequiredArgsConstructor
@RestController
public class TokenController {
private final SocialProperties socialProperties;
private final SysLoginService sysLoginService;
@DubboReference
private final RemoteConfigService remoteConfigService;
@DubboReference
private final RemoteClientService remoteClientService;
@DubboReference
private final RemoteSocialService remoteSocialService;
/**
* 登录方法
*
* @param body 登录信息
* @return 结果
*/
@ApiEncrypt
@PostMapping("/login")
public R<LoginVo> login(@RequestBody String body) {
LoginBody loginBody = JsonUtils.parseObject(body, LoginBody.class);
ValidatorUtils.validate(loginBody);
// 授权类型和客户端id
String clientId = loginBody.getClientId();
String grantType = loginBody.getGrantType();
RemoteClientVo clientVo = remoteClientService.queryByClientId(clientId);
// 查询不到 client 或 client 内不包含 grantType
if (ObjectUtil.isNull(clientVo) || !StringUtils.contains(clientVo.getGrantType(), grantType)) {
log.info("客户端id: {} 认证类型:{} 异常!.", clientId, grantType);
return R.fail(MessageUtils.message("auth.grant.type.error"));
} else if (!SystemConstants.NORMAL.equals(clientVo.getStatus())) {
return R.fail(MessageUtils.message("auth.grant.type.blocked"));
}
// 登录
LoginVo loginVo = IAuthStrategy.login(body, clientVo, grantType);
return R.ok(loginVo);
}
/**
* 第三方登录请求
*
* @param source 登录来源
* @return 结果
*/
@GetMapping("/binding/{source}")
public R<String> authBinding(@PathVariable("source") String source,
@RequestParam String domain) {
SocialLoginConfigProperties obj = socialProperties.getType().get(source);
if (ObjectUtil.isNull(obj)) {
return R.fail(source + "平台账号暂不支持");
}
AuthRequest authRequest = SocialUtils.getAuthRequest(source, socialProperties);
Map<String, String> map = new HashMap<>();
map.put("domain", domain);
map.put("state", AuthStateUtils.createState());
String authorizeUrl = authRequest.authorize(Base64.encode(JsonUtils.toJsonString(map), StandardCharsets.UTF_8));
return R.data(authorizeUrl);
}
/**
* 第三方登录回调业务处理 绑定授权
*
* @param loginBody 请求体
* @return 结果
*/
@PostMapping("/social/callback")
public R<Void> socialCallback(@RequestBody SocialLoginBody loginBody) {
// 获取第三方登录信息
AuthResponse<AuthUser> response = SocialUtils.loginAuth(
loginBody.getSource(), loginBody.getSocialCode(),
loginBody.getSocialState(), socialProperties);
AuthUser authUserData = response.getData();
// 判断授权响应是否成功
if (!response.ok()) {
return R.fail(response.getMsg());
}
sysLoginService.socialRegister(authUserData);
return R.ok();
}
/**
* 取消授权
*
* @param socialId socialId
*/
@DeleteMapping(value = "/unlock/{socialId}")
public R<Void> unlockSocial(@PathVariable Long socialId) {
Boolean rows = remoteSocialService.deleteWithValidById(socialId);
return rows ? R.ok() : R.fail("取消授权失败");
}
/**
* 登出方法
*/
@PostMapping("logout")
public R<Void> logout() {
sysLoginService.logout();
return R.ok();
}
/**
* 用户注册
*/
@ApiEncrypt
@PostMapping("register")
public R<Void> register(@RequestBody RegisterBody registerBody) {
if (!remoteConfigService.selectRegisterEnabled()) {
return R.fail("当前系统没有开启注册功能!");
}
// 用户注册
sysLoginService.register(registerBody);
return R.ok();
}
}
@@ -0,0 +1,24 @@
package cn.aixunkeji.auth.domain.vo;
import lombok.Data;
/**
* 验证码信息
*
*/
@Data
public class CaptchaVo {
/**
* 是否开启验证码
*/
private Boolean captchaEnabled = true;
private String uuid;
/**
* 验证码图片
*/
private String img;
}
@@ -0,0 +1,53 @@
package cn.aixunkeji.auth.domain.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* 登录验证信息
*
*/
@Data
public class LoginVo {
/**
* 授权令牌
*/
@JsonProperty("access_token")
private String accessToken;
/**
* 刷新令牌
*/
@JsonProperty("refresh_token")
private String refreshToken;
/**
* 授权令牌 access_token 的有效期
*/
@JsonProperty("expire_in")
private Long expireIn;
/**
* 刷新令牌 refresh_token 的有效期
*/
@JsonProperty("refresh_expire_in")
private Long refreshExpireIn;
/**
* 应用id
*/
@JsonProperty("client_id")
private String clientId;
/**
* 令牌权限
*/
private String scope;
/**
* 用户 openid
*/
private String openid;
}
@@ -0,0 +1,13 @@
package cn.aixunkeji.auth.event;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
/**
* 用户登录成功事件。
*
* @param loginId 登录标识
* @param tokenValue token 值
* @param loginParameter 登录参数
*/
public record UserLoginSuccessEvent(Object loginId, String tokenValue, SaLoginParameter loginParameter) {
}
@@ -0,0 +1,30 @@
package cn.aixunkeji.auth.form;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.EqualsAndHashCode;
import cn.aixunkeji.common.core.domain.model.LoginBody;
/**
* 邮件登录对象
*
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class EmailLoginBody extends LoginBody {
/**
* 邮箱
*/
@NotBlank(message = "{user.email.not.blank}")
@Email(message = "{user.email.not.valid}")
private String email;
/**
* 邮箱code
*/
@NotBlank(message = "{email.code.not.blank}")
private String emailCode;
}
@@ -0,0 +1,32 @@
package cn.aixunkeji.auth.form;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.EqualsAndHashCode;
import cn.aixunkeji.common.core.domain.model.LoginBody;
import org.hibernate.validator.constraints.Length;
/**
* 密码登录对象
*
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class PasswordLoginBody extends LoginBody {
/**
* 用户名
*/
@NotBlank(message = "{user.username.not.blank}")
@Length(min = 2, max = 30, message = "{user.username.length.valid}")
private String username;
/**
* 用户密码
*/
@NotBlank(message = "{user.password.not.blank}")
@Length(min = 5, max = 30, message = "{user.password.length.valid}")
// @Pattern(regexp = RegexConstants.PASSWORD, message = "{user.password.format.valid}")
private String password;
}
@@ -0,0 +1,37 @@
package cn.aixunkeji.auth.form;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.EqualsAndHashCode;
import cn.aixunkeji.common.core.domain.model.LoginBody;
import org.hibernate.validator.constraints.Length;
/**
* 用户注册对象
*
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class RegisterBody extends LoginBody {
/**
* 用户名
*/
@NotBlank(message = "{user.username.not.blank}")
@Length(min = 2, max = 30, message = "{user.username.length.valid}")
private String username;
/**
* 用户密码
*/
@NotBlank(message = "{user.password.not.blank}")
@Length(min = 5, max = 30, message = "{user.password.length.valid}")
// @Pattern(regexp = RegexConstants.PASSWORD, message = "{user.password.format.valid}")
private String password;
/**
* 用户类型
*/
private String userType;
}
@@ -0,0 +1,28 @@
package cn.aixunkeji.auth.form;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.EqualsAndHashCode;
import cn.aixunkeji.common.core.domain.model.LoginBody;
/**
* 短信登录对象
*
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class SmsLoginBody extends LoginBody {
/**
* 手机号
*/
@NotBlank(message = "{user.phonenumber.not.blank}")
private String phoneNumber;
/**
* 短信code
*/
@NotBlank(message = "{sms.code.not.blank}")
private String smsCode;
}
@@ -0,0 +1,34 @@
package cn.aixunkeji.auth.form;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.EqualsAndHashCode;
import cn.aixunkeji.common.core.domain.model.LoginBody;
/**
* 三方登录对象
*
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class SocialLoginBody extends LoginBody {
/**
* 第三方登录平台
*/
@NotBlank(message = "{social.source.not.blank}")
private String source;
/**
* 第三方登录code
*/
@NotBlank(message = "{social.code.not.blank}")
private String socialCode;
/**
* 第三方登录socialState
*/
@NotBlank(message = "{social.state.not.blank}")
private String socialState;
}
@@ -0,0 +1,27 @@
package cn.aixunkeji.auth.form;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.EqualsAndHashCode;
import cn.aixunkeji.common.core.domain.model.LoginBody;
/**
* 三方登录对象
*
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class XcxLoginBody extends LoginBody {
/**
* 小程序id(多个小程序时使用)
*/
private String appid;
/**
* 小程序code
*/
@NotBlank(message = "{xcx.code.not.blank}")
private String xcxCode;
}
@@ -0,0 +1,105 @@
package cn.aixunkeji.auth.listener;
import cn.dev33.satoken.listener.SaTokenListener;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import lombok.extern.slf4j.Slf4j;
import cn.aixunkeji.auth.event.UserLoginSuccessEvent;
import cn.aixunkeji.common.core.constant.CacheNames;
import cn.aixunkeji.common.core.utils.SpringUtils;
import cn.aixunkeji.common.core.utils.StringUtils;
import cn.aixunkeji.common.redis.utils.RedisUtils;
import org.springframework.stereotype.Component;
/**
* 用户行为 侦听器的实现
*
*/
@Component
@Slf4j
public class UserActionListener implements SaTokenListener {
/**
* 每次登录时触发
*/
@Override
public void doLogin(String loginType, Object loginId, String tokenValue, SaLoginParameter loginParameter) {
SpringUtils.context().publishEvent(new UserLoginSuccessEvent(loginId, tokenValue, loginParameter));
}
/**
* 每次注销时触发
*/
@Override
public void doLogout(String loginType, Object loginId, String tokenValue) {
RedisUtils.deleteObject(CacheNames.ONLINE_TOKEN_KEY + tokenValue);
log.info("user doLogout, useId:{}, token:***{}", loginId, StringUtils.right(tokenValue, 8));
}
/**
* 每次被踢下线时触发
*/
@Override
public void doKickout(String loginType, Object loginId, String tokenValue) {
RedisUtils.deleteObject(CacheNames.ONLINE_TOKEN_KEY + tokenValue);
log.info("user doLogoutByLoginId, useId:{}, token:***{}", loginId, StringUtils.right(tokenValue, 8));
}
/**
* 每次被顶下线时触发
*/
@Override
public void doReplaced(String loginType, Object loginId, String tokenValue) {
RedisUtils.deleteObject(CacheNames.ONLINE_TOKEN_KEY + tokenValue);
log.info("user doReplaced, useId:{}, token:***{}", loginId, StringUtils.right(tokenValue, 8));
}
/**
* 每次被封禁时触发
*/
@Override
public void doDisable(String loginType, Object loginId, String service, int level, long disableTime) {
}
/**
* 每次被解封时触发
*/
@Override
public void doUntieDisable(String loginType, Object loginId, String service) {
}
/**
* 每次打开二级认证时触发
*/
@Override
public void doOpenSafe(String loginType, String tokenValue, String service, long safeTime) {
}
/**
* 每次创建Session时触发
*/
@Override
public void doCloseSafe(String loginType, String tokenValue, String service) {
}
/**
* 每次创建Session时触发
*/
@Override
public void doCreateSession(String id) {
}
/**
* 每次注销Session时触发
*/
@Override
public void doLogoutSession(String id) {
}
/**
* 每次Token续期时触发
*/
@Override
public void doRenewTimeout(String loginType, Object loginId, String tokenValue, long timeout) {
}
}
@@ -0,0 +1,77 @@
package cn.aixunkeji.auth.listener;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import cn.aixunkeji.auth.event.UserLoginSuccessEvent;
import cn.aixunkeji.common.core.constant.CacheNames;
import cn.aixunkeji.common.core.constant.Constants;
import cn.aixunkeji.common.core.utils.MessageUtils;
import cn.aixunkeji.common.core.utils.ServletUtils;
import cn.aixunkeji.common.core.utils.SpringUtils;
import cn.aixunkeji.common.core.utils.StringUtils;
import cn.aixunkeji.common.core.utils.ip.AddressUtils;
import cn.aixunkeji.common.log.event.LoginInfoEvent;
import cn.aixunkeji.common.redis.utils.RedisUtils;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.aixunkeji.system.api.RemoteUserService;
import cn.aixunkeji.system.api.domain.SysUserOnline;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import java.time.Duration;
/**
* 用户登录成功监听器。
*
*/
@Component
@Slf4j
public class UserLoginSuccessListener {
@DubboReference
private RemoteUserService remoteUserService;
/**
* 登录成功后记录在线信息、登录日志与最近登录信息。
*
* @param event 用户登录成功事件
*/
@EventListener
public void handleLoginSuccess(UserLoginSuccessEvent event) {
SaLoginParameter loginParameter = event.loginParameter();
UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
String ip = ServletUtils.getClientIP();
String username = (String) loginParameter.getExtra(LoginHelper.USER_NAME_KEY);
String tokenValue = event.tokenValue();
SysUserOnline userOnline = new SysUserOnline();
userOnline.setIpaddr(ip);
userOnline.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
userOnline.setBrowser(userAgent.getBrowser().getName());
userOnline.setOs(userAgent.getOs().getName());
userOnline.setLoginTime(System.currentTimeMillis());
userOnline.setTokenId(tokenValue);
userOnline.setUserName(username);
userOnline.setClientKey((String) loginParameter.getExtra(LoginHelper.CLIENT_KEY));
userOnline.setDeviceType(loginParameter.getDeviceType());
userOnline.setDeptName((String) loginParameter.getExtra(LoginHelper.DEPT_NAME_KEY));
if (loginParameter.getTimeout() == -1) {
RedisUtils.setCacheObject(CacheNames.ONLINE_TOKEN_KEY + tokenValue, userOnline);
} else {
RedisUtils.setCacheObject(CacheNames.ONLINE_TOKEN_KEY + tokenValue, userOnline, Duration.ofSeconds(loginParameter.getTimeout()));
}
LoginInfoEvent loginInfoEvent = new LoginInfoEvent();
loginInfoEvent.setUsername(username);
loginInfoEvent.setStatus(Constants.LOGIN_SUCCESS);
loginInfoEvent.setMessage(MessageUtils.message("user.login.success"));
SpringUtils.context().publishEvent(loginInfoEvent);
remoteUserService.recordLoginInfo((Long) loginParameter.getExtra(LoginHelper.USER_KEY), ip);
log.info("user doLogin, userId:{}, token:***{}", event.loginId(), StringUtils.right(tokenValue, 8));
}
}
@@ -0,0 +1,38 @@
package cn.aixunkeji.auth.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
/**
* 验证码配置
*
*/
@Data
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "security.captcha")
public class CaptchaProperties {
/**
* 验证码类型
*/
private String type;
/**
* 数字验证码位数
*/
private Integer numberLength;
/**
* 字符验证码长度
*/
private Integer charLength;
/**
* 验证码开关
*/
private Boolean enabled;
}
@@ -0,0 +1,28 @@
package cn.aixunkeji.auth.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
/**
* 用户密码配置
*
*/
@Data
@Configuration
@RefreshScope
@ConfigurationProperties(prefix = "user.password")
public class UserPasswordProperties {
/**
* 密码最大错误次数
*/
private Integer maxRetryCount;
/**
* 密码锁定时间(默认10分钟)
*/
private Integer lockTime;
}
@@ -0,0 +1,72 @@
package cn.aixunkeji.auth.service;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.util.ObjectUtil;
import cn.aixunkeji.auth.domain.vo.LoginVo;
import cn.aixunkeji.common.core.exception.ServiceException;
import cn.aixunkeji.common.core.utils.SpringUtils;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.aixunkeji.system.api.domain.vo.RemoteClientVo;
import java.util.function.Consumer;
/**
* 授权策略
*
*/
public interface IAuthStrategy {
String BASE_NAME = "AuthStrategy";
/**
* 登录
*
* @param body 登录对象
* @param client 授权管理视图对象
* @param grantType 授权类型
* @return 登录验证信息
*/
static LoginVo login(String body, RemoteClientVo client, String grantType) {
// 授权类型和客户端id
String beanName = grantType + BASE_NAME;
if (!SpringUtils.containsBean(beanName)) {
throw new ServiceException("授权类型不正确!");
}
IAuthStrategy instance = SpringUtils.getBean(beanName);
return instance.login(body, client);
}
/**
* 按客户端配置构建统一登录参数。
*/
static SaLoginParameter buildLoginParameter(RemoteClientVo client) {
return buildLoginParameter(client, null);
}
/**
* 按客户端配置构建统一登录参数,并预留自定义扩展入口。
*/
static SaLoginParameter buildLoginParameter(RemoteClientVo client, Consumer<SaLoginParameter> customizer) {
SaLoginParameter model = new SaLoginParameter();
model.setDeviceType(client.getDeviceType());
model.setTimeout(client.getTimeout());
model.setActiveTimeout(client.getActiveTimeout());
model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
model.setExtra(LoginHelper.CLIENT_ACCESS_PATH_KEY, client.getAccessPath());
model.setExtra(LoginHelper.CLIENT_IP_WHITELIST_KEY, client.getIpWhitelist());
if (ObjectUtil.isNotNull(customizer)) {
customizer.accept(model);
}
return model;
}
/**
* 登录
*
* @param body 登录对象
* @param client 授权管理视图对象
* @return 登录验证信息
*/
LoginVo login(String body, RemoteClientVo client);
}
@@ -0,0 +1,223 @@
package cn.aixunkeji.auth.service;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.lock.annotation.Lock4j;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthUser;
import org.apache.dubbo.config.annotation.DubboReference;
import cn.aixunkeji.auth.form.RegisterBody;
import cn.aixunkeji.auth.properties.CaptchaProperties;
import cn.aixunkeji.auth.properties.UserPasswordProperties;
import cn.aixunkeji.common.core.constant.CacheNames;
import cn.aixunkeji.common.core.constant.Constants;
import cn.aixunkeji.common.core.constant.GlobalConstants;
import cn.aixunkeji.common.core.enums.LoginType;
import cn.aixunkeji.common.core.enums.UserType;
import cn.aixunkeji.common.core.exception.ServiceException;
import cn.aixunkeji.common.core.exception.user.CaptchaException;
import cn.aixunkeji.common.core.exception.user.CaptchaExpireException;
import cn.aixunkeji.common.core.exception.user.UserException;
import cn.aixunkeji.common.core.utils.MessageUtils;
import cn.aixunkeji.common.core.utils.SpringUtils;
import cn.aixunkeji.common.core.utils.StringUtils;
import cn.aixunkeji.common.log.event.LoginInfoEvent;
import cn.aixunkeji.common.redis.utils.RedisUtils;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.aixunkeji.system.api.RemoteSocialService;
import cn.aixunkeji.system.api.RemoteUserService;
import cn.aixunkeji.system.api.domain.bo.RemoteSocialBo;
import cn.aixunkeji.system.api.domain.bo.RemoteUserBo;
import cn.aixunkeji.system.api.domain.vo.RemoteSocialVo;
import cn.aixunkeji.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.List;
import java.util.function.Supplier;
/**
* 登录校验方法
*
*/
@RequiredArgsConstructor
@Service
@Slf4j
public class SysLoginService {
@DubboReference
private RemoteUserService remoteUserService;
@DubboReference
private RemoteSocialService remoteSocialService;
@Autowired
private UserPasswordProperties userPasswordProperties;
@Autowired
private final CaptchaProperties captchaProperties;
/**
* 绑定第三方用户
*
* @param authUserData 授权响应实体
*/
@Lock4j
public void socialRegister(AuthUser authUserData) {
String authId = authUserData.getSource() + authUserData.getUuid();
// 第三方用户信息
RemoteSocialBo bo = BeanUtil.toBean(authUserData, RemoteSocialBo.class);
BeanUtil.copyProperties(authUserData.getToken(), bo);
Long userId = LoginHelper.getUserId();
bo.setUserId(userId);
bo.setAuthId(authId);
bo.setOpenId(authUserData.getUuid());
bo.setUserName(authUserData.getUsername());
bo.setNickName(authUserData.getNickname());
List<RemoteSocialVo> checkList = remoteSocialService.selectByAuthId(authId);
if (CollUtil.isNotEmpty(checkList)) {
throw new ServiceException("此三方账号已经被绑定!");
}
// 查询是否已经绑定用户
RemoteSocialBo params = new RemoteSocialBo();
params.setUserId(userId);
params.setSource(bo.getSource());
List<RemoteSocialVo> list = remoteSocialService.queryList(params);
if (CollUtil.isEmpty(list)) {
// 没有绑定用户, 新增用户信息
remoteSocialService.insertByBo(bo);
} else {
// 更新用户信息
bo.setId(list.getFirst().getId());
remoteSocialService.updateByBo(bo);
// 如果要绑定的平台账号已经被绑定过了 是否抛异常自行决断
// throw new ServiceException("此平台账号已经被绑定!");
}
}
/**
* 退出登录
*/
public void logout() {
try {
LoginUser loginUser = LoginHelper.getLoginUser();
if (ObjectUtil.isNull(loginUser)) {
return;
}
recordLoginInfo(loginUser.getUsername(), Constants.LOGOUT, MessageUtils.message("user.logout.success"));
} catch (NotLoginException ignored) {
} finally {
try {
StpUtil.logout();
} catch (NotLoginException ignored) {
}
}
}
/**
* 注册
*/
public void register(RegisterBody registerBody) {
String username = registerBody.getUsername();
String password = registerBody.getPassword();
// 校验用户类型是否存在
String userType = UserType.getUserType(registerBody.getUserType()).getUserType();
boolean captchaEnabled = captchaProperties.getEnabled();
// 验证码开关
if (captchaEnabled) {
validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
}
// 注册用户信息
RemoteUserBo remoteUserBo = new RemoteUserBo();
remoteUserBo.setUserName(username);
remoteUserBo.setNickName(username);
remoteUserBo.setPassword(BCrypt.hashpw(password));
remoteUserBo.setUserType(userType);
boolean regFlag = remoteUserService.registerUserInfo(remoteUserBo);
if (!regFlag) {
throw new UserException("user.register.error");
}
recordLoginInfo(username, Constants.REGISTER, MessageUtils.message("user.register.success"));
}
/**
* 校验验证码
*
* @param username 用户名
* @param code 验证码
* @param uuid 唯一标识
*/
public void validateCaptcha(String username, String code, String uuid) {
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.blankToDefault(uuid, "");
String captcha = RedisUtils.getCacheObject(verifyKey);
RedisUtils.deleteObject(verifyKey);
if (captcha == null) {
recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
throw new CaptchaExpireException();
}
if (!StringUtils.equalsIgnoreCase(code, captcha)) {
recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"));
throw new CaptchaException();
}
}
/**
* 记录登录信息
*
* @param username 用户名
* @param status 状态
* @param message 消息内容
* @return
*/
public void recordLoginInfo(String username, String status, String message) {
// 封装对象
LoginInfoEvent loginInfoEvent = new LoginInfoEvent();
loginInfoEvent.setUsername(username);
loginInfoEvent.setStatus(status);
loginInfoEvent.setMessage(message);
SpringUtils.context().publishEvent(loginInfoEvent);
}
/**
* 登录校验
*/
public void checkLogin(LoginType loginType, String username, Supplier<Boolean> supplier) {
String errorKey = CacheNames.PWD_ERR_CNT_KEY + username;
String loginFail = Constants.LOGIN_FAIL;
Integer maxRetryCount = userPasswordProperties.getMaxRetryCount();
Integer lockTime = userPasswordProperties.getLockTime();
// 获取用户登录错误次数,默认为0 (可自定义限制策略 例如: key + username + ip)
int errorNumber = ObjectUtil.defaultIfNull(RedisUtils.getCacheObject(errorKey), 0);
// 锁定时间内登录 则踢出
if (errorNumber >= maxRetryCount) {
recordLoginInfo(username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
}
if (supplier.get()) {
// 错误次数递增
errorNumber++;
RedisUtils.setCacheObject(errorKey, errorNumber, Duration.ofMinutes(lockTime));
// 达到规定错误次数 则锁定登录
if (errorNumber >= maxRetryCount) {
recordLoginInfo(username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
} else {
// 未达到规定错误次数
recordLoginInfo(username, loginFail, MessageUtils.message(loginType.getRetryLimitCount(), errorNumber));
throw new UserException(loginType.getRetryLimitCount(), errorNumber);
}
}
// 登录成功 清空错误次数
RedisUtils.deleteObject(errorKey);
}
}
@@ -0,0 +1,74 @@
package cn.aixunkeji.auth.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import cn.aixunkeji.auth.domain.vo.LoginVo;
import cn.aixunkeji.auth.form.EmailLoginBody;
import cn.aixunkeji.auth.service.IAuthStrategy;
import cn.aixunkeji.auth.service.SysLoginService;
import cn.aixunkeji.common.core.constant.Constants;
import cn.aixunkeji.common.core.constant.GlobalConstants;
import cn.aixunkeji.common.core.enums.LoginType;
import cn.aixunkeji.common.core.exception.user.CaptchaExpireException;
import cn.aixunkeji.common.core.utils.MessageUtils;
import cn.aixunkeji.common.core.utils.StringUtils;
import cn.aixunkeji.common.core.utils.ValidatorUtils;
import cn.aixunkeji.common.json.utils.JsonUtils;
import cn.aixunkeji.common.redis.utils.RedisUtils;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.aixunkeji.system.api.RemoteUserService;
import cn.aixunkeji.system.api.domain.vo.RemoteClientVo;
import cn.aixunkeji.system.api.model.LoginUser;
import org.springframework.stereotype.Service;
/**
* 邮件认证策略
*
*/
@Slf4j
@Service("email" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class EmailAuthStrategy implements IAuthStrategy {
private final SysLoginService loginService;
@DubboReference
private RemoteUserService remoteUserService;
@Override
public LoginVo login(String body, RemoteClientVo client) {
EmailLoginBody loginBody = JsonUtils.parseObject(body, EmailLoginBody.class);
ValidatorUtils.validate(loginBody);
String email = loginBody.getEmail();
String emailCode = loginBody.getEmailCode();
LoginUser loginUser = remoteUserService.getUserInfoByEmail(email);
loginService.checkLogin(LoginType.EMAIL, loginUser.getUsername(), () -> !validateEmailCode(email, emailCode));
loginUser.setClientKey(client.getClientKey());
loginUser.setDeviceType(client.getDeviceType());
SaLoginParameter model = IAuthStrategy.buildLoginParameter(client);
// 生成token
LoginHelper.login(loginUser, model);
LoginVo loginVo = new LoginVo();
loginVo.setAccessToken(StpUtil.getTokenValue());
loginVo.setExpireIn(StpUtil.getTokenTimeout());
loginVo.setClientId(client.getClientId());
return loginVo;
}
/**
* 校验邮箱验证码
*/
private boolean validateEmailCode(String email, String emailCode) {
String code = RedisUtils.getCacheObject(GlobalConstants.CAPTCHA_CODE_KEY + email);
if (StringUtils.isBlank(code)) {
loginService.recordLoginInfo(email, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
throw new CaptchaExpireException();
}
return code.equals(emailCode);
}
}
@@ -0,0 +1,95 @@
package cn.aixunkeji.auth.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.crypto.digest.BCrypt;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import cn.aixunkeji.auth.domain.vo.LoginVo;
import cn.aixunkeji.auth.form.PasswordLoginBody;
import cn.aixunkeji.auth.properties.CaptchaProperties;
import cn.aixunkeji.auth.service.IAuthStrategy;
import cn.aixunkeji.auth.service.SysLoginService;
import cn.aixunkeji.common.core.constant.Constants;
import cn.aixunkeji.common.core.constant.GlobalConstants;
import cn.aixunkeji.common.core.enums.LoginType;
import cn.aixunkeji.common.core.exception.user.CaptchaException;
import cn.aixunkeji.common.core.exception.user.CaptchaExpireException;
import cn.aixunkeji.common.core.utils.MessageUtils;
import cn.aixunkeji.common.core.utils.StringUtils;
import cn.aixunkeji.common.core.utils.ValidatorUtils;
import cn.aixunkeji.common.json.utils.JsonUtils;
import cn.aixunkeji.common.redis.utils.RedisUtils;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.aixunkeji.system.api.RemoteUserService;
import cn.aixunkeji.system.api.domain.vo.RemoteClientVo;
import cn.aixunkeji.system.api.model.LoginUser;
import org.springframework.stereotype.Service;
/**
* 密码认证策略
*
*/
@Slf4j
@Service("password" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class PasswordAuthStrategy implements IAuthStrategy {
private final CaptchaProperties captchaProperties;
private final SysLoginService loginService;
@DubboReference
private RemoteUserService remoteUserService;
@Override
public LoginVo login(String body, RemoteClientVo client) {
PasswordLoginBody loginBody = JsonUtils.parseObject(body, PasswordLoginBody.class);
ValidatorUtils.validate(loginBody);
String username = loginBody.getUsername();
String password = loginBody.getPassword();
String code = loginBody.getCode();
String uuid = loginBody.getUuid();
// 验证码开关
if (captchaProperties.getEnabled()) {
validateCaptcha(username, code, uuid);
}
LoginUser loginUser = remoteUserService.getUserInfo(username);
loginService.checkLogin(LoginType.PASSWORD, username, () -> !BCrypt.checkpw(password, loginUser.getPassword()));
loginUser.setClientKey(client.getClientKey());
loginUser.setDeviceType(client.getDeviceType());
SaLoginParameter model = IAuthStrategy.buildLoginParameter(client);
// 生成token
LoginHelper.login(loginUser, model);
LoginVo loginVo = new LoginVo();
loginVo.setAccessToken(StpUtil.getTokenValue());
loginVo.setExpireIn(StpUtil.getTokenTimeout());
loginVo.setClientId(client.getClientId());
return loginVo;
}
/**
* 校验验证码
*
* @param username 用户名
* @param code 验证码
* @param uuid 唯一标识
*/
private void validateCaptcha(String username, String code, String uuid) {
String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.blankToDefault(uuid, "");
String captcha = RedisUtils.getCacheObject(verifyKey);
RedisUtils.deleteObject(verifyKey);
if (captcha == null) {
loginService.recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
throw new CaptchaExpireException();
}
if (!StringUtils.equalsIgnoreCase(code, captcha)) {
loginService.recordLoginInfo(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"));
throw new CaptchaException();
}
}
}
@@ -0,0 +1,74 @@
package cn.aixunkeji.auth.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import cn.aixunkeji.auth.domain.vo.LoginVo;
import cn.aixunkeji.auth.form.SmsLoginBody;
import cn.aixunkeji.auth.service.IAuthStrategy;
import cn.aixunkeji.auth.service.SysLoginService;
import cn.aixunkeji.common.core.constant.Constants;
import cn.aixunkeji.common.core.constant.GlobalConstants;
import cn.aixunkeji.common.core.enums.LoginType;
import cn.aixunkeji.common.core.exception.user.CaptchaExpireException;
import cn.aixunkeji.common.core.utils.MessageUtils;
import cn.aixunkeji.common.core.utils.StringUtils;
import cn.aixunkeji.common.core.utils.ValidatorUtils;
import cn.aixunkeji.common.json.utils.JsonUtils;
import cn.aixunkeji.common.redis.utils.RedisUtils;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.aixunkeji.system.api.RemoteUserService;
import cn.aixunkeji.system.api.domain.vo.RemoteClientVo;
import cn.aixunkeji.system.api.model.LoginUser;
import org.springframework.stereotype.Service;
/**
* 短信认证策略
*
*/
@Slf4j
@Service("sms" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class SmsAuthStrategy implements IAuthStrategy {
private final SysLoginService loginService;
@DubboReference
private RemoteUserService remoteUserService;
@Override
public LoginVo login(String body, RemoteClientVo client) {
SmsLoginBody loginBody = JsonUtils.parseObject(body, SmsLoginBody.class);
ValidatorUtils.validate(loginBody);
String phoneNumber = loginBody.getPhoneNumber();
String smsCode = loginBody.getSmsCode();
LoginUser loginUser = remoteUserService.getUserInfoByPhoneNumber(phoneNumber);
loginService.checkLogin(LoginType.SMS, loginUser.getUsername(), () -> !validateSmsCode(phoneNumber, smsCode));
loginUser.setClientKey(client.getClientKey());
loginUser.setDeviceType(client.getDeviceType());
SaLoginParameter model = IAuthStrategy.buildLoginParameter(client);
// 生成token
LoginHelper.login(loginUser, model);
LoginVo loginVo = new LoginVo();
loginVo.setAccessToken(StpUtil.getTokenValue());
loginVo.setExpireIn(StpUtil.getTokenTimeout());
loginVo.setClientId(client.getClientId());
return loginVo;
}
/**
* 校验短信验证码
*/
private boolean validateSmsCode(String phoneNumber, String smsCode) {
String code = RedisUtils.getCacheObject(GlobalConstants.CAPTCHA_CODE_KEY + phoneNumber);
if (StringUtils.isBlank(code)) {
loginService.recordLoginInfo(phoneNumber, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
throw new CaptchaExpireException();
}
return code.equals(smsCode);
}
}
@@ -0,0 +1,83 @@
package cn.aixunkeji.auth.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import org.apache.dubbo.config.annotation.DubboReference;
import cn.aixunkeji.auth.domain.vo.LoginVo;
import cn.aixunkeji.auth.form.SocialLoginBody;
import cn.aixunkeji.auth.service.IAuthStrategy;
import cn.aixunkeji.common.core.exception.ServiceException;
import cn.aixunkeji.common.core.utils.ValidatorUtils;
import cn.aixunkeji.common.json.utils.JsonUtils;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.aixunkeji.common.social.config.properties.SocialProperties;
import cn.aixunkeji.common.social.utils.SocialUtils;
import cn.aixunkeji.system.api.RemoteSocialService;
import cn.aixunkeji.system.api.RemoteUserService;
import cn.aixunkeji.system.api.domain.vo.RemoteClientVo;
import cn.aixunkeji.system.api.domain.vo.RemoteSocialVo;
import cn.aixunkeji.system.api.model.LoginUser;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 第三方授权策略
*
*/
@Slf4j
@Service("social" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class SocialAuthStrategy implements IAuthStrategy {
private final SocialProperties socialProperties;
@DubboReference
private RemoteSocialService remoteSocialService;
@DubboReference
private RemoteUserService remoteUserService;
/**
* 登录-第三方授权登录
*
* @param body 登录信息
* @param client 客户端信息
*/
@Override
public LoginVo login(String body, RemoteClientVo client) {
SocialLoginBody loginBody = JsonUtils.parseObject(body, SocialLoginBody.class);
ValidatorUtils.validate(loginBody);
AuthResponse<AuthUser> response = SocialUtils.loginAuth(
loginBody.getSource(), loginBody.getSocialCode(),
loginBody.getSocialState(), socialProperties);
if (!response.ok()) {
throw new ServiceException(response.getMsg());
}
AuthUser authUserData = response.getData();
List<RemoteSocialVo> list = remoteSocialService.selectByAuthId(authUserData.getSource() + authUserData.getUuid());
if (CollUtil.isEmpty(list)) {
throw new ServiceException("你还没有绑定第三方账号,绑定后才可以登录!");
}
RemoteSocialVo socialVo = list.getFirst();
LoginUser loginUser = remoteUserService.getUserInfo(socialVo.getUserId());
loginUser.setClientKey(client.getClientKey());
loginUser.setDeviceType(client.getDeviceType());
SaLoginParameter model = IAuthStrategy.buildLoginParameter(client);
// 生成token
LoginHelper.login(loginUser, model);
LoginVo loginVo = new LoginVo();
loginVo.setAccessToken(StpUtil.getTokenValue());
loginVo.setExpireIn(StpUtil.getTokenTimeout());
loginVo.setClientId(client.getClientId());
return loginVo;
}
}
@@ -0,0 +1,84 @@
package cn.aixunkeji.auth.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.request.AuthWechatMiniProgramRequest;
import org.apache.dubbo.config.annotation.DubboReference;
import cn.aixunkeji.auth.domain.vo.LoginVo;
import cn.aixunkeji.auth.form.XcxLoginBody;
import cn.aixunkeji.auth.service.IAuthStrategy;
import cn.aixunkeji.auth.service.SysLoginService;
import cn.aixunkeji.common.core.exception.ServiceException;
import cn.aixunkeji.common.core.utils.ValidatorUtils;
import cn.aixunkeji.common.json.utils.JsonUtils;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.aixunkeji.system.api.RemoteUserService;
import cn.aixunkeji.system.api.domain.vo.RemoteClientVo;
import cn.aixunkeji.system.api.model.XcxLoginUser;
import org.springframework.stereotype.Service;
/**
* 邮件认证策略
*
*/
@Slf4j
@Service("xcx" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class XcxAuthStrategy implements IAuthStrategy {
private final SysLoginService loginService;
@DubboReference
private RemoteUserService remoteUserService;
@Override
public LoginVo login(String body, RemoteClientVo client) {
XcxLoginBody loginBody = JsonUtils.parseObject(body, XcxLoginBody.class);
ValidatorUtils.validate(loginBody);
// xcxCode 为 小程序调用 wx.login 授权后获取
String xcxCode = loginBody.getXcxCode();
// 多个小程序识别使用
String appid = loginBody.getAppid();
// 校验 appid + appsrcret + xcxCode 调用登录凭证校验接口 获取 session_key 与 openid
AuthRequest authRequest = new AuthWechatMiniProgramRequest(AuthConfig.builder()
.clientId(appid).clientSecret("自行填写密钥 可根据不同appid填入不同密钥")
.ignoreCheckRedirectUri(true).ignoreCheckState(true).build());
AuthCallback authCallback = new AuthCallback();
authCallback.setCode(xcxCode);
AuthResponse<AuthUser> resp = authRequest.login(authCallback);
String openid, unionId;
if (resp.ok()) {
AuthToken token = resp.getData().getToken();
openid = token.getOpenId();
// 微信小程序只有关联到微信开放平台下之后才能获取到 unionId,因此unionId不一定能返回。
unionId = token.getUnionId();
} else {
throw new ServiceException(resp.getMsg());
}
// todo getUserInfoByOpenid 方法内部查询逻辑需要自行根据业务实现
XcxLoginUser loginUser = remoteUserService.getUserInfoByOpenid(openid);
loginUser.setClientKey(client.getClientKey());
loginUser.setDeviceType(client.getDeviceType());
SaLoginParameter model = IAuthStrategy.buildLoginParameter(client);
// 生成token
LoginHelper.login(loginUser, model);
LoginVo loginVo = new LoginVo();
loginVo.setAccessToken(StpUtil.getTokenValue());
loginVo.setExpireIn(StpUtil.getTokenTimeout());
loginVo.setClientId(client.getClientId());
loginVo.setOpenid(openid);
return loginVo;
}
}
@@ -0,0 +1,33 @@
# Tomcat
server:
port: 9210
# Spring
spring:
application:
# 应用名称
name: aixun-auth
profiles:
# 环境配置
active: @profiles.active@
--- # nacos 配置
spring:
cloud:
nacos:
# nacos 服务地址
server-addr: @nacos.server@
username: @nacos.username@
password: @nacos.password@
discovery:
# 注册组
group: DEFAULT_GROUP
namespace: public
config:
# 配置组
group: DEFAULT_GROUP
namespace: public
config:
import:
- optional:nacos:application-common.yml
- optional:nacos:${spring.application.name}.yml
+10
查看文件
@@ -0,0 +1,10 @@
Spring Boot Version: ${spring-boot.version}
Spring Application Name: ${spring.application.name}
_ _ _
(_) | | | |
_ __ _ _ ___ _ _ _ ______ __ _ _ _ | |_ | |__
| '__|| | | | / _ \ | | | || ||______| / _` || | | || __|| '_ \
| | | |_| || (_) || |_| || | | (_| || |_| || |_ | | | |
|_| \__,_| \___/ \__, ||_| \__,_| \__,_| \__||_| |_|
__/ |
|___/
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 日志存放路径 -->
<property name="log.path" value="logs/${project.artifactId}"/>
<!-- 日志输出格式 -->
<property name="console.log.pattern"
value="%cyan(%d{yyyy-MM-dd HH:mm:ss}) %green([%thread]) %highlight(%-5level) %boldMagenta(%logger{36}%n) - %msg%n"/>
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${console.log.pattern}</pattern>
<charset>utf-8</charset>
</encoder>
</appender>
<include resource="logback-common.xml" />
<include resource="logback-logstash.xml" />
<!-- 开启 skywalking 日志收集 -->
<include resource="logback-skylog.xml" />
<!--系统操作日志-->
<root level="info">
<appender-ref ref="console"/>
</root>
</configuration>