用户登录问题修改

This commit is contained in:
jiang 2024-11-05 14:44:39 +08:00
parent c21bed507d
commit 6561e01856
18 changed files with 100 additions and 91 deletions

View File

@ -1,19 +1,17 @@
package com.bonus.system.api;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.system.api.domain.SysDept;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.bonus.common.core.constant.SecurityConstants;
import com.bonus.common.core.constant.ServiceNameConstants;
import com.bonus.common.core.domain.R;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.system.api.domain.SysDept;
import com.bonus.system.api.domain.SysUser;
import com.bonus.system.api.factory.RemoteUserFallbackFactory;
import com.bonus.system.api.model.LoginUser;
import java.util.List;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* 用户服务
@ -51,7 +49,7 @@ public interface RemoteUserService {
* @param source 请求来源
* @return 结果
*/
@GetMapping("/user//infoPhoto/{phone}")
@GetMapping("/user/infoPhoto/{phone}")
public R<LoginUser> getUserInfoByPhone(@PathVariable("phone") String phone, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);

View File

@ -1,17 +1,19 @@
package com.bonus.system.api.domain;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.*;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.bonus.common.core.annotation.Excel;
import com.bonus.common.core.annotation.Excel.ColumnType;
import com.bonus.common.core.annotation.Excel.Type;
import com.bonus.common.core.annotation.Excels;
import com.bonus.common.core.web.domain.BaseEntity;
import com.bonus.common.core.xss.Xss;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.List;
/**
* 用户对象 sys_user
@ -136,6 +138,10 @@ public class SysUser extends BaseEntity {
* 审批状态
*/
private String approvalStatus;
/**
* 长期和临时用户标识
*/
private String isPermanent;
public SysUser() {
@ -322,6 +328,14 @@ public class SysUser extends BaseEntity {
this.approvalStatus = approvalStatus;
}
public String getIsPermanent() {
return isPermanent;
}
public void setIsPermanent(String isPermanent) {
this.isPermanent = isPermanent;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)

View File

@ -1,5 +1,6 @@
package com.bonus.auth.controller;
import com.bonus.auth.config.LoginType;
import com.bonus.auth.factory.LoginStrategyFactory;
import com.bonus.auth.form.LoginBody;
import com.bonus.auth.form.RegisterBody;
@ -90,6 +91,9 @@ public class TokenController {
if (strategy == null) {
return R.fail("不支持的登录方式");
}
if (form.getLoginType()== LoginType.EMAIL_OTP || form.getLoginType()== LoginType.PHONE_OTP ){
form.setPassword(form.getVerificationCode());
}
LoginUser login = strategy.login(form.getUsername(), form.getPassword());
return R.ok(tokenService.isLogin(String.valueOf(login.getSysUser().getUserId())));
}
@ -101,6 +105,9 @@ public class TokenController {
if (strategy == null) {
return R.fail("不支持的登录方式");
}
if (form.getLoginType()== LoginType.EMAIL_OTP || form.getLoginType()== LoginType.PHONE_OTP ){
form.setPassword(form.getVerificationCode());
}
LoginUser login = strategy.login(form.getUsername(), form.getPassword());
return R.ok(tokenService.createToken(login));
@ -174,12 +181,7 @@ public class TokenController {
*/
@PostMapping("register")
public R<?> register(@RequestBody RegisterBody registerBody) {
try {
sysLoginService.register(registerBody);
return R.ok();
} catch (Exception e) {
log.error("注册失败: {}", e.getMessage(), e);
return R.fail("注册失败");
}
}
}

View File

@ -29,13 +29,12 @@ public class EmailOtpLoginStrategy implements LoginStrategy {
if (!systemConfig.getLoginConfig().isPhoneCode()) {
throw new ServiceException("用户不存在/密码错误");
}
passwordValidatorService.checkPhoneCaptcha(email, otp);
R<LoginUser> userResult = remoteUserService.getUserInfoByEmail(email, SecurityConstants.INNER);
LoginUser userInfo = userResult.getData();
SysUser user = userInfo.getSysUser();
//验证用户是否存在
passwordValidatorService.validateUserResult(email, userResult);
// 验证用户查询结果
passwordValidatorService.validateUserResult(email, userResult);
LoginUser userInfo = userResult.getData();
SysUser user = userInfo.getSysUser();
passwordValidatorService.validateApprovalStatus(email, user);
// 验证用户状态
passwordValidatorService.validateUserStatus(email, user);

View File

@ -40,13 +40,13 @@ public class LoginVerificationCodeSender implements VerificationCodeStrategy {
* @return 验证码发送的结果
*/
@Override
public String sendVerificationCode(String contactInfo) {
public void sendVerificationCode(String contactInfo) {
if (isEmail(contactInfo)) {
return emailService.sendSimpleEmail(contactInfo);
emailService.sendSimpleEmail(contactInfo);
} else if (isPhone(contactInfo)) {
return smsService.sendSimplePhone(contactInfo);
smsService.sendSimplePhone(contactInfo);
} else {
return handleUsernameLogin(contactInfo);
handleUsernameLogin(contactInfo);
}
}
@ -76,7 +76,7 @@ public class LoginVerificationCodeSender implements VerificationCodeStrategy {
* @param username 用户名
* @return 验证码发送的结果
*/
private String handleUsernameLogin(String username) {
private void handleUsernameLogin(String username) {
R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
if (userResult == null || userResult.getData() == null || R.FAIL == userResult.getCode()) {
throw new ServiceException("用户名/密码错误");
@ -87,7 +87,7 @@ public class LoginVerificationCodeSender implements VerificationCodeStrategy {
if (StringUtils.isEmpty(user.getSysUser().getPhonenumber())) {
throw new ServiceException("此账号未绑定手机号,请先绑定手机号");
}
return smsService.sendSimplePhone(user.getSysUser().getPhonenumber());
smsService.sendSimplePhone(user.getSysUser().getPhonenumber());
} else {
throw new ServiceException("不支持的登录方式");
}

View File

@ -288,7 +288,7 @@ public class PasswordValidatorService {
/**
* 校验手机验证码
*/
public void checkPhoneCaptcha(String code, String phone) throws CaptchaException {
public void checkPhoneCaptcha(String phone, String code) throws CaptchaException {
if (StringUtils.isEmpty(code)) {
throw new CaptchaException("手机验证码不能为空");
}
@ -300,9 +300,11 @@ public class PasswordValidatorService {
if (captcha == null) {
throw new CaptchaException("手机验证码已失效");
}
redisService.deleteObject(verifyKey);
if (!code.equalsIgnoreCase(captcha)) {
throw new CaptchaException("手机验证码错误");
}else {
redisService.deleteObject(verifyKey);
}
}

View File

@ -25,21 +25,18 @@ public class PhoneOtpLoginStrategy implements LoginStrategy {
@Resource
private PasswordValidatorService passwordValidatorService;
@Resource
private SysPasswordService passwordService;
@Override
public LoginUser login(String phone, String otp) {
if (!systemConfig.getLoginConfig().isPhoneCode()) {
throw new ServiceException("用户不存在/码错误");
throw new ServiceException("用户不存在/验证码错误");
}
passwordValidatorService.checkPhoneCaptcha(phone, otp);
R<LoginUser> userResult = remoteUserService.getUserInfoByPhone(phone, SecurityConstants.INNER);
LoginUser userInfo = userResult.getData();
SysUser user = userInfo.getSysUser();
//验证用户是否存在
passwordValidatorService.validateUserResult(phone, userResult);
// 验证用户查询结果
passwordValidatorService.validateUserResult(phone, userResult);
LoginUser userInfo = userResult.getData();
SysUser user = userInfo.getSysUser();
passwordValidatorService.validateApprovalStatus(phone, user);
// 验证用户状态
passwordValidatorService.validateUserStatus(phone, user);

View File

@ -38,7 +38,7 @@ public class RegisterVerificationCodeSender implements VerificationCodeStrategy
* @return 验证码发送的结果
*/
@Override
public String sendVerificationCode(String contactInfo) {
public void sendVerificationCode(String contactInfo) {
if (isEmail(contactInfo)) {
if (!systemConfig.getRegistersConfig().isEmailRegisters()) {
throw new ServiceException("请输入正确的联系方式");
@ -47,7 +47,7 @@ public class RegisterVerificationCodeSender implements VerificationCodeStrategy
if (userResult.getData() != null) {
throw new ServiceException("联系方式已经注册账号");
}
return emailService.sendSimpleEmail(contactInfo);
emailService.sendSimpleEmail(contactInfo);
} else if (isPhone(contactInfo)) {
if (!systemConfig.getRegistersConfig().isPhoneRegisters()) {
throw new ServiceException("请输入正确的联系方式");
@ -56,7 +56,7 @@ public class RegisterVerificationCodeSender implements VerificationCodeStrategy
if (userResult.getData() != null) {
throw new ServiceException("联系方式已经注册账号");
}
return smsService.sendSimplePhone(contactInfo);
smsService.sendSimplePhone(contactInfo);
} else {
throw new ServiceException("请输入正确的联系方式");
}

View File

@ -11,6 +11,7 @@ import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.config.SystemConfig;
import com.bonus.system.api.RemoteUserService;
import com.bonus.system.api.domain.SysUser;
import com.hankcs.hanlp.HanLP;
@ -38,6 +39,8 @@ public class SysLoginService {
@Resource
private VerificationCodeStrategyFactory verificationCodeStrategyFactory;
@Autowired
private SystemConfig systemConfig;
/**
* 获取验证码
@ -52,7 +55,8 @@ public class SysLoginService {
if (strategyFactory == null) {
return R.fail("不支持的方式");
}
return R.ok(strategyFactory.sendVerificationCode(username));
strategyFactory.sendVerificationCode(username);
return R.ok();
}
/**
@ -79,13 +83,15 @@ public class SysLoginService {
long startTime = System.currentTimeMillis(); // 记录开始时间
String result = convertAndAppend(registerBody.getNickName(), registerBody.getMobile());
registerBody.setUsername(result);
if (StringUtils.isAnyBlank(registerBody.getUsername(), registerBody.getPassword()) ||
registerBody.getUsername().length() < UserConstants.USERNAME_MIN_LENGTH ||
registerBody.getUsername().length() > UserConstants.USERNAME_MAX_LENGTH) {
recordLogService.saveLogs(registerBody.getUsername(), startTime, "注册参数无效", "账户或密码长度不符合要求", null, "失败");
throw new ServiceException("账户或密码长度不符合要求");
}
if (systemConfig.getRegistersConfig().isVerificationCode()){
passwordValidatorService.checkPhoneCaptcha(registerBody.getMobile(),registerBody.getVerificationCode());
}
AjaxResult ajaxResult = passwordValidatorService.validatePassword(registerBody.getUsername(), registerBody.getPassword());
if (ajaxResult.isError()) {
throw new ServiceException((String) ajaxResult.get("msg"));
@ -93,8 +99,14 @@ public class SysLoginService {
SysUser sysUser = new SysUser();
sysUser.setUserName(registerBody.getUsername());
sysUser.setNickName(registerBody.getNickName());
sysUser.setStatus("1");
sysUser.setApprovalStatus("0");
if (systemConfig.getRegistersConfig().isApprovalStatus()){
sysUser.setApprovalStatus("0");
sysUser.setStatus("1");
}else {
sysUser.setApprovalStatus("1");
sysUser.setStatus("0");
}
//有要求另加
sysUser.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
if (getContactType(registerBody.getMobile()) == 1) {

View File

@ -4,5 +4,5 @@ public interface VerificationCodeStrategy {
/**
* @param contactInfo 可以是邮箱地址或手机号码
*/
String sendVerificationCode(String contactInfo);
void sendVerificationCode(String contactInfo);
}

View File

@ -76,6 +76,14 @@ public class SystemConfig {
* 邮箱注册
*/
private boolean emailRegisters;
/**
* 是否开启手机验证码
*/
private boolean verificationCode;
/**
* 注册是否审核
*/
private boolean approvalStatus;
}
@Data

View File

@ -30,7 +30,7 @@ public class SmsService {
* @return AjaxResult
* @throws CaptchaException 自定义captcha 异常
*/
public String sendSimplePhone(String to) {
public void sendSimplePhone(String to) {
if (StringUtils.isEmpty(to)) {
throw new CaptchaException("手机号不能为空");
}
@ -40,10 +40,8 @@ public class SmsService {
String s = SmsUtils.smsToken(to, str, "");
if (StringUtils.isNotEmpty(s)) {
if (s.contains("ok")) {
String uuid = StringUtils.randomUUID();
String verifyKey = CacheConstants.VERIFICATION_CODE + uuid;
String verifyKey = CacheConstants.VERIFICATION_CODE + StringUtils.nvl(to, "");
redisService.setCacheObject(verifyKey, code, verificationCodeConfig.getTime(), TimeUnit.MINUTES);
return uuid;
} else {
throw new CaptchaException("获取短信失败");
}

View File

@ -73,6 +73,7 @@ public class TokenService {
Map<String, Object> rspMap = new HashMap<String, Object>(16);
rspMap.put("access_token", accessToken);
rspMap.put("expires_in", EXPIRETIME);
rspMap.put("isLogin", isLogin(String.valueOf(userId)));
//对token进行存储
redisService.setCacheObject(LOGIN_USER_KEY + userId, token, systemConfig.getTokenTime(), TimeUnit.MINUTES);
return rspMap;

View File

@ -7,7 +7,6 @@ import com.bonus.common.core.utils.ServletUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.gateway.config.properties.CaptchaProperties;
import com.bonus.gateway.service.ValidateCodeService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
@ -49,20 +48,18 @@ public class ValidateCodeFilter extends AbstractGatewayFilterFactory<Object> {
if (!StringUtils.equalsAnyIgnoreCase(request.getURI().getPath(), VALIDATE_URL)) {
return chain.filter(exchange);
}
if (!captchaProperties.getEnabled()) {
return chain.filter(exchange);
}
try {
String rspStr = resolveBodyFromRequest(request);
if (StringUtils.isEmpty(rspStr)) {
throw new CaptchaException("请求参数异常");
}
JSONObject obj = JSON.parseObject(rspStr);
if (ObjectUtils.isNotEmpty(obj) && ObjectUtils.isNotEmpty(obj.getString("phoneUuid")) && ObjectUtils.isNotEmpty(obj.getString("verificationCode"))) {
validateCodeService.checkPhoneCaptcha(obj.getString("verificationCode"), obj.getString("phoneUuid"));
} else {
if (!captchaProperties.getEnabled()) {
return chain.filter(exchange);
}
validateCodeService.checkCaptcha(obj.getString(CODE), obj.getString(UUID));
}
validateCodeService.checkCaptcha(obj.getString(CODE), obj.getString(UUID));
} catch (Exception e) {
return ServletUtils.webFluxResponseWriter(exchange.getResponse(), e.getMessage());

View File

@ -1,10 +1,10 @@
package com.bonus.gateway.service;
import java.io.IOException;
import com.bonus.common.core.exception.CaptchaException;
import com.bonus.common.core.web.domain.AjaxResult;
import java.io.IOException;
/**
* 验证码处理
*
@ -29,6 +29,4 @@ public interface ValidateCodeService {
*/
public void checkCaptcha(String key, String value) throws CaptchaException;
public void checkPhoneCaptcha(String code, String phone) throws CaptchaException;
}

View File

@ -107,25 +107,4 @@ public class ValidateCodeServiceImpl implements ValidateCodeService {
}
}
/**
* 校验手机验证码
*/
@Override
public void checkPhoneCaptcha(String code, String uuid) throws CaptchaException {
if (StringUtils.isEmpty(code)) {
throw new ServiceException("验证码不能为空");
}
String verifyKey = CacheConstants.VERIFICATION_CODE + StringUtils.nvl(uuid, "");
String captcha = redisService.getCacheObject(verifyKey);
if (captcha == null) {
throw new ServiceException("验证码已失效");
}
redisService.deleteObject(verifyKey);
if (!code.equalsIgnoreCase(captcha)) {
throw new ServiceException("验证码错误");
}
}
}

View File

@ -7,7 +7,6 @@ import com.bonus.common.core.utils.SpringUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.utils.bean.BeanValidators;
import com.bonus.common.core.utils.sms.SmsUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.domain.BaseEntity;
import com.bonus.common.datascope.annotation.DataScope;
import com.bonus.common.datascope.utils.CommonDataPermissionInfo;
@ -151,7 +150,7 @@ public class SysUserServiceImpl implements ISysUserService {
*/
@Override
public SysUser selectUserByPhotoNumber(String photoNumber) {
return userMapper.selectUserByUserName(photoNumber);
return userMapper.selectUserByPhoneNumber(photoNumber);
}
/**
@ -162,7 +161,7 @@ public class SysUserServiceImpl implements ISysUserService {
*/
@Override
public SysUser selectUserByEmail(String email) {
return userMapper.selectUserByUserName(email);
return userMapper.selectUserByEmail(email);
}
/**

View File

@ -25,6 +25,7 @@
<result property="remark" column="remark"/>
<result property="loginType" column="login_type"/>
<result property="approvalStatus" column="approval_status"/>
<result property="isPermanent" column="is_permanent"/>
<association property="dept" javaType="SysDept" resultMap="deptResult"/>
<collection property="roles" javaType="java.util.List" resultMap="RoleResult"/>
@ -67,6 +68,7 @@
u.create_time,
u.remark,
u.approval_status,
u.is_permanent,
d.dept_id,
d.parent_id,
d.ancestors,
@ -89,7 +91,7 @@
<select id="selectUserList" parameterType="SysUser" resultMap="SysUserResult">
select u.user_id, u.dept_id, u.nick_name, u.user_name, u.email, u.avatar, INSERT(u.phonenumber,4,4,'****') as phonenumber,u.sex, u.status,
u.del_flag, u.login_ip, u.login_date, u.create_by, u.create_time, u.remark,u.approval_status, d.dept_name,
u.del_flag, u.login_ip, u.login_date, u.create_by, u.create_time, u.remark,u.approval_status,u.is_permanent, d.dept_name,
d.leader from sys_user
u
left join sys_dept d on u.dept_id = d.dept_id
@ -160,11 +162,11 @@
<include refid="selectUserVo"/>
where u.del_flag = '0'AND u.user_name = #{userName}
</select>
<select id="selectUserByPhoneNumber" resultType="com.bonus.system.api.domain.SysUser">
<select id="selectUserByPhoneNumber" resultMap="SysUserResult">
<include refid="selectUserVo"/>
where u.del_flag = '0'AND u.phonenumber = #{phoneNumber}
</select>
<select id="selectUserByEmail" resultType="com.bonus.system.api.domain.SysUser">
<select id="selectUserByEmail" resultMap="SysUserResult">
<include refid="selectUserVo"/>
where u.del_flag = '0'AND u.email = #{email}
</select>
@ -218,6 +220,7 @@
<if test="remark != null and remark != ''">remark,</if>
<if test="loginType != null and loginType!=''">login_type,</if>
<if test="approvalStatus != null and approvalStatus!=''">approval_status,</if>
<if test="isPermanent != null and isPermanent!=''">is_permanent,</if>
create_time
)values(
<if test="userId != null and userId != ''">#{userId},</if>
@ -234,6 +237,7 @@
<if test="remark != null and remark != ''">#{remark},</if>
<if test="loginType != null and loginType!=''">#{loginType},</if>
<if test="approvalStatus != null and approvalStatus!=''">#{approvalStatus},</if>
<if test="isPermanent != null and isPermanent!=''">#{isPermanent},</if>
sysdate()
)
</insert>
@ -255,6 +259,7 @@
<if test="updateBy != null and updateBy != ''">update_by = #{updateBy},</if>
<if test="remark != null">remark = #{remark},</if>
<if test="loginType != null and loginType!=''">login_type = #{loginType},</if>
<if test="isPermanent != null and isPermanent!=''">is_permanent = #{isPermanent},</if>
update_time = sysdate()
</set>
where user_id = #{userId}