1. code review 后台的短信验证码登陆

2. 解决 SQL Server LIMIT 1 存在报错的问题
pull/2/head
YunaiV 2022-05-02 22:57:45 +08:00
parent 4453ac27ff
commit 7753bd4c44
18 changed files with 1100 additions and 1032 deletions

View File

@ -140,6 +140,10 @@ public class QueryWrapperX<T> extends QueryWrapper<T> {
case ORACLE_12C: case ORACLE_12C:
super.eq("ROWNUM", 1); super.eq("ROWNUM", 1);
break; break;
case SQL_SERVER:
case SQL_SERVER2005:
super.select("TOP 1 *"); // 由于 SQL Server 是通过 SELECT TOP 1 实现限制一条,所以只好使用 * 查询剩余字段
break;
default: default:
super.last("LIMIT 1"); super.last("LIMIT 1");
} }

View File

@ -1,7 +1,6 @@
package cn.iocoder.yudao.module.member.controller.app.auth; package cn.iocoder.yudao.module.member.controller.app.auth;
import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated; import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.member.controller.app.auth.vo.*; import cn.iocoder.yudao.module.member.controller.app.auth.vo.*;
import cn.iocoder.yudao.module.member.service.auth.MemberAuthService; import cn.iocoder.yudao.module.member.service.auth.MemberAuthService;
@ -35,7 +34,6 @@ public class AppAuthController {
@ApiOperation("使用手机 + 密码登录") @ApiOperation("使用手机 + 密码登录")
public CommonResult<AppAuthLoginRespVO> login(@RequestBody @Valid AppAuthLoginReqVO reqVO) { public CommonResult<AppAuthLoginRespVO> login(@RequestBody @Valid AppAuthLoginReqVO reqVO) {
String token = authService.login(reqVO, getClientIP(), getUserAgent()); String token = authService.login(reqVO, getClientIP(), getUserAgent());
// 返回结果
return success(AppAuthLoginRespVO.builder().token(token).build()); return success(AppAuthLoginRespVO.builder().token(token).build());
} }
@ -49,7 +47,7 @@ public class AppAuthController {
@PostMapping("/send-sms-code") @PostMapping("/send-sms-code")
@ApiOperation(value = "发送手机验证码") @ApiOperation(value = "发送手机验证码")
public CommonResult<Boolean> sendSmsCode(@RequestBody @Valid AppAuthSendSmsReqVO reqVO) { public CommonResult<Boolean> sendSmsCode(@RequestBody @Valid AppAuthSmsSendReqVO reqVO) {
authService.sendSmsCode(getLoginUserId(), reqVO); authService.sendSmsCode(getLoginUserId(), reqVO);
return success(true); return success(true);
} }

View File

@ -10,10 +10,10 @@ import lombok.experimental.Accessors;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
@ApiModel("用户 APP - 发送手机验证码 Response VO") @ApiModel("用户 APP - 发送手机验证码 Request VO")
@Data @Data
@Accessors(chain = true) @Accessors(chain = true)
public class AppAuthSendSmsReqVO { public class AppAuthSmsSendReqVO {
@ApiModelProperty(value = "手机号", example = "15601691234") @ApiModelProperty(value = "手机号", example = "15601691234")
@Mobile @Mobile

View File

@ -31,7 +31,7 @@ public interface AuthConvert {
SocialUserBindReqDTO convert(Long userId, Integer userType, AppAuthSocialQuickLoginReqVO reqVO); SocialUserBindReqDTO convert(Long userId, Integer userType, AppAuthSocialQuickLoginReqVO reqVO);
SocialUserUnbindReqDTO convert(Long userId, Integer userType, AppSocialUserUnbindReqVO reqVO); SocialUserUnbindReqDTO convert(Long userId, Integer userType, AppSocialUserUnbindReqVO reqVO);
SmsCodeSendReqDTO convert(AppAuthSendSmsReqVO reqVO); SmsCodeSendReqDTO convert(AppAuthSmsSendReqVO reqVO);
SmsCodeUseReqDTO convert(AppAuthResetPasswordReqVO reqVO, SmsSceneEnum scene, String usedIp); SmsCodeUseReqDTO convert(AppAuthResetPasswordReqVO reqVO, SmsSceneEnum scene, String usedIp);
SmsCodeUseReqDTO convert(AppAuthSmsLoginReqVO reqVO, Integer scene, String usedIp); SmsCodeUseReqDTO convert(AppAuthSmsLoginReqVO reqVO, Integer scene, String usedIp);

View File

@ -2,8 +2,6 @@ package cn.iocoder.yudao.module.member.service.auth;
import cn.iocoder.yudao.framework.security.core.service.SecurityAuthFrameworkService; import cn.iocoder.yudao.framework.security.core.service.SecurityAuthFrameworkService;
import cn.iocoder.yudao.module.member.controller.app.auth.vo.*; import cn.iocoder.yudao.module.member.controller.app.auth.vo.*;
import cn.iocoder.yudao.module.member.controller.app.social.vo.AppSocialUserBindReqVO;
import cn.iocoder.yudao.module.member.controller.app.social.vo.AppSocialUserUnbindReqVO;
import javax.validation.Valid; import javax.validation.Valid;
@ -36,7 +34,6 @@ public interface MemberAuthService extends SecurityAuthFrameworkService {
*/ */
String smsLogin(@Valid AppAuthSmsLoginReqVO reqVO, String userIp, String userAgent); String smsLogin(@Valid AppAuthSmsLoginReqVO reqVO, String userIp, String userAgent);
/** /**
* 使 code * 使 code
* *
@ -85,6 +82,6 @@ public interface MemberAuthService extends SecurityAuthFrameworkService {
* @param userId * @param userId
* @param reqVO * @param reqVO
*/ */
void sendSmsCode(Long userId, AppAuthSendSmsReqVO reqVO); void sendSmsCode(Long userId, AppAuthSmsSendReqVO reqVO);
} }

View File

@ -288,7 +288,7 @@ public class MemberAuthServiceImpl implements MemberAuthService {
} }
@Override @Override
public void sendSmsCode(Long userId, AppAuthSendSmsReqVO reqVO) { public void sendSmsCode(Long userId, AppAuthSmsSendReqVO reqVO) {
// TODO 要根据不同的场景,校验是否有用户 // TODO 要根据不同的场景,校验是否有用户
smsCodeApi.sendSmsCode(AuthConvert.INSTANCE.convert(reqVO).setCreateIp(getClientIP())); smsCodeApi.sendSmsCode(AuthConvert.INSTANCE.convert(reqVO).setCreateIp(getClientIP()));
} }

View File

@ -17,6 +17,7 @@ public interface ErrorCodeConstants {
ErrorCode AUTH_LOGIN_CAPTCHA_CODE_ERROR = new ErrorCode(1002000004, "验证码不正确"); ErrorCode AUTH_LOGIN_CAPTCHA_CODE_ERROR = new ErrorCode(1002000004, "验证码不正确");
ErrorCode AUTH_THIRD_LOGIN_NOT_BIND = new ErrorCode(1002000005, "未绑定账号,需要进行绑定"); ErrorCode AUTH_THIRD_LOGIN_NOT_BIND = new ErrorCode(1002000005, "未绑定账号,需要进行绑定");
ErrorCode AUTH_TOKEN_EXPIRED = new ErrorCode(1002000006, "Token 已经过期"); ErrorCode AUTH_TOKEN_EXPIRED = new ErrorCode(1002000006, "Token 已经过期");
ErrorCode AUTH_MOBILE_NOT_EXISTS = new ErrorCode(1002000007, "手机号不存在");
// ========== 菜单模块 1002001000 ========== // ========== 菜单模块 1002001000 ==========
ErrorCode MENU_NAME_DUPLICATE = new ErrorCode(1002001000, "已经存在该名字的菜单"); ErrorCode MENU_NAME_DUPLICATE = new ErrorCode(1002001000, "已经存在该名字的菜单");

View File

@ -19,8 +19,8 @@ public enum SmsSceneEnum implements IntArrayValuable {
MEMBER_LOGIN(1, "user-sms-login", "会员用户 - 手机号登陆"), MEMBER_LOGIN(1, "user-sms-login", "会员用户 - 手机号登陆"),
MEMBER_UPDATE_MOBILE(2, "user-sms-reset-password", "会员用户 - 修改手机"), MEMBER_UPDATE_MOBILE(2, "user-sms-reset-password", "会员用户 - 修改手机"),
MEMBER_FORGET_PASSWORD(3, "user-sms-update-mobile", "会员用户 - 忘记密码"), MEMBER_FORGET_PASSWORD(3, "user-sms-update-mobile", "会员用户 - 忘记密码"),
ADMIN_MEMBER_LOGIN(21, "admin-sms-login", "后台用户 - 手机号登录"); ADMIN_MEMBER_LOGIN(21, "admin-sms-login", "后台用户 - 手机号登录");
// 如果未来希望管理后台支持手机验证码登陆,可以通过添加 ADMIN_MEMBER_LOGIN 枚举
public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(SmsSceneEnum::getScene).toArray(); public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(SmsSceneEnum::getScene).toArray();

View File

@ -1,7 +1,6 @@
package cn.iocoder.yudao.module.system.controller.admin.auth; package cn.iocoder.yudao.module.system.controller.admin.auth;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.collection.SetUtils; import cn.iocoder.yudao.framework.common.util.collection.SetUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog; import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
@ -61,26 +60,6 @@ public class AuthController {
return success(AuthLoginRespVO.builder().token(token).build()); return success(AuthLoginRespVO.builder().token(token).build());
} }
@PostMapping("/sms-login")
@ApiOperation("使用短信验证码登录")
@OperateLog(enable = false) // 避免 Post 请求被记录操作日志
public CommonResult<AuthLoginRespVO> smsLogin(@RequestBody @Valid AuthSmsLoginReqVO reqVO) {
String token = authService.smsLogin(reqVO, getClientIP(), getUserAgent());
// 返回结果
return success(AuthLoginRespVO.builder().token(token).build());
}
@PostMapping("/send-login-sms-code")
@ApiOperation(value = "发送手机验证码")
@OperateLog(enable = false) // 避免 Post 请求被记录操作日志
public CommonResult<Boolean> sendLoginSmsCode(@RequestBody @Valid AuthSmsSendReqVO reqVO) {
authService.sendSmsCode(getLoginUserId(), reqVO);
return success(true);
}
@GetMapping("/get-permission-info") @GetMapping("/get-permission-info")
@ApiOperation("获取登录用户的权限信息") @ApiOperation("获取登录用户的权限信息")
public CommonResult<AuthPermissionInfoRespVO> getPermissionInfo() { public CommonResult<AuthPermissionInfoRespVO> getPermissionInfo() {
@ -112,6 +91,25 @@ public class AuthController {
return success(AuthConvert.INSTANCE.buildMenuTree(menuList)); return success(AuthConvert.INSTANCE.buildMenuTree(menuList));
} }
// ========== 短信登录相关 ==========
@PostMapping("/sms-login")
@ApiOperation("使用短信验证码登录")
@OperateLog(enable = false) // 避免 Post 请求被记录操作日志
public CommonResult<AuthLoginRespVO> smsLogin(@RequestBody @Valid AuthSmsLoginReqVO reqVO) {
String token = authService.smsLogin(reqVO, getClientIP(), getUserAgent());
// 返回结果
return success(AuthLoginRespVO.builder().token(token).build());
}
@PostMapping("/send-sms-code")
@ApiOperation(value = "发送手机验证码")
@OperateLog(enable = false) // 避免 Post 请求被记录操作日志
public CommonResult<Boolean> sendLoginSmsCode(@RequestBody @Valid AuthSmsSendReqVO reqVO) {
authService.sendSmsCode(reqVO);
return success(true);
}
// ========== 社交登录相关 ========== // ========== 社交登录相关 ==========
@GetMapping("/social-auth-redirect") @GetMapping("/social-auth-redirect")
@ -129,7 +127,7 @@ public class AuthController {
@ApiOperation("社交快捷登录,使用 code 授权码") @ApiOperation("社交快捷登录,使用 code 授权码")
@OperateLog(enable = false) // 避免 Post 请求被记录操作日志 @OperateLog(enable = false) // 避免 Post 请求被记录操作日志
public CommonResult<AuthLoginRespVO> socialQuickLogin(@RequestBody @Valid AuthSocialQuickLoginReqVO reqVO) { public CommonResult<AuthLoginRespVO> socialQuickLogin(@RequestBody @Valid AuthSocialQuickLoginReqVO reqVO) {
String token = authService.socialLogin(reqVO, getClientIP(), getUserAgent()); String token = authService.socialQuickLogin(reqVO, getClientIP(), getUserAgent());
// 返回结果 // 返回结果
return success(AuthLoginRespVO.builder().token(token).build()); return success(AuthLoginRespVO.builder().token(token).build());
} }

View File

@ -1,17 +1,19 @@
package cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth; package cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth;
import cn.iocoder.yudao.framework.common.validation.InEnum;
import cn.iocoder.yudao.framework.common.validation.Mobile;
import cn.iocoder.yudao.module.system.enums.sms.SmsSceneEnum;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern; import javax.validation.constraints.NotNull;
@ApiModel("管理后台 - 短信验证码的呢老姑 Request VO") @ApiModel("管理后台 - 发送手机验证码 Request VO")
@Data @Data
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@ -20,27 +22,12 @@ public class AuthSmsSendReqVO {
@ApiModelProperty(value = "手机号", required = true, example = "yudaoyuanma") @ApiModelProperty(value = "手机号", required = true, example = "yudaoyuanma")
@NotEmpty(message = "手机号不能为空") @NotEmpty(message = "手机号不能为空")
@Length(min = 11, max = 11, message = "手机号格式错误,仅支持大陆手机号") @Mobile
@Pattern(regexp = "^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$", message = "账号格式为数字以及字母")
private String mobile; private String mobile;
@ApiModelProperty(value = "短信验证码", required = true, example = "1024", notes = "验证码开启时,需要传递")
@NotEmpty(message = "验证码不能为空", groups = CodeEnableGroup.class)
private String code;
@ApiModelProperty(value = "短信场景", required = true, example = "1") @ApiModelProperty(value = "短信场景", required = true, example = "1")
@NotEmpty(message = "短信场景", groups = CodeEnableGroup.class) @NotNull(message = "发送场景不能为空")
@InEnum(SmsSceneEnum.class)
private Integer scene; private Integer scene;
@ApiModelProperty(value = "验证码的唯一标识", required = true, example = "9b2ffbc1-7425-4155-9894-9d5c08541d62", notes = "验证码开启时,需要传递")
@NotEmpty(message = "唯一标识不能为空", groups = AuthLoginReqVO.CodeEnableGroup.class)
private String uuid;
/**
* Group
*/
public interface CodeEnableGroup {}
} }

View File

@ -5,6 +5,7 @@ import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser; import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeSendReqDTO; import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeSendReqDTO;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeSendReqDTO; import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeSendReqDTO;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserBindReqDTO; import cn.iocoder.yudao.module.system.api.social.dto.SocialUserBindReqDTO;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserUnbindReqDTO; import cn.iocoder.yudao.module.system.api.social.dto.SocialUserUnbindReqDTO;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth.*; import cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth.*;
@ -75,9 +76,10 @@ public interface AuthConvert {
} }
SocialUserBindReqDTO convert(Long userId, Integer userType, AuthSocialBindLoginReqVO reqVO); SocialUserBindReqDTO convert(Long userId, Integer userType, AuthSocialBindLoginReqVO reqVO);
SocialUserBindReqDTO convert(Long userId, Integer userType, AuthSocialQuickLoginReqVO reqVO); SocialUserBindReqDTO convert(Long userId, Integer userType, AuthSocialQuickLoginReqVO reqVO);
SmsCodeSendReqDTO convert(AuthSmsSendReqVO reqVO); SmsCodeSendReqDTO convert(AuthSmsSendReqVO reqVO);
SmsCodeUseReqDTO convert(AuthSmsLoginReqVO reqVO, Integer scene, String usedIp);
} }

View File

@ -26,7 +26,7 @@ public class SecurityConfiguration {
registry.antMatchers(buildAdminApi("/system/auth/social-bind-login")).permitAll(); registry.antMatchers(buildAdminApi("/system/auth/social-bind-login")).permitAll();
// 登录登录的接口 // 登录登录的接口
registry.antMatchers(buildAdminApi("/system/auth/sms-login")).permitAll(); registry.antMatchers(buildAdminApi("/system/auth/sms-login")).permitAll();
registry.antMatchers(buildAdminApi("/system/auth/send-login-sms-code")).permitAll(); registry.antMatchers(buildAdminApi("/system/auth/send-sms-code")).permitAll();
// 验证码的接口 // 验证码的接口
registry.antMatchers(buildAdminApi("/system/captcha/**")).permitAll(); registry.antMatchers(buildAdminApi("/system/captcha/**")).permitAll();
// 获得租户编号的接口 // 获得租户编号的接口

View File

@ -26,10 +26,10 @@ public interface AdminAuthService extends SecurityAuthFrameworkService {
/** /**
* *
* @param userId *
* @param reqVO * @param reqVO
*/ */
void sendSmsCode(Long userId, AuthSmsSendReqVO reqVO); void sendSmsCode(AuthSmsSendReqVO reqVO);
/** /**
* *
@ -49,7 +49,7 @@ public interface AdminAuthService extends SecurityAuthFrameworkService {
* @param userAgent UA * @param userAgent UA
* @return 使 JWT * @return 使 JWT
*/ */
String socialLogin(@Valid AuthSocialQuickLoginReqVO reqVO, String userIp, String userAgent); String socialQuickLogin(@Valid AuthSocialQuickLoginReqVO reqVO, String userIp, String userAgent);
/** /**
* 使 code + * 使 code +

View File

@ -8,11 +8,7 @@ import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser; import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.authentication.MultiUsernamePasswordAuthenticationToken; import cn.iocoder.yudao.framework.security.core.authentication.MultiUsernamePasswordAuthenticationToken;
import cn.iocoder.yudao.module.system.api.logger.dto.LoginLogCreateReqDTO; import cn.iocoder.yudao.module.system.api.logger.dto.LoginLogCreateReqDTO;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth.AuthLoginReqVO;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth.AuthSocialBindLoginReqVO;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth.AuthSocialQuickLoginReqVO;
import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi; import cn.iocoder.yudao.module.system.api.sms.SmsCodeApi;
import cn.iocoder.yudao.module.system.api.sms.dto.code.SmsCodeUseReqDTO;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth.*; import cn.iocoder.yudao.module.system.controller.admin.auth.vo.auth.*;
import cn.iocoder.yudao.module.system.convert.auth.AuthConvert; import cn.iocoder.yudao.module.system.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO; import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
@ -117,51 +113,27 @@ public class AdminAuthServiceImpl implements AdminAuthService {
} }
@Override @Override
public void sendSmsCode(Long userId, AuthSmsSendReqVO reqVO) { public void sendSmsCode(AuthSmsSendReqVO reqVO) {
// 登录场景,验证是否存在
this.verifyCaptchaSmsSend(reqVO); if (userService.getUserByMobile(reqVO.getMobile()) == null) {
//登录场景,验证是否存在 throw exception(AUTH_MOBILE_NOT_EXISTS);
if(reqVO.getScene().compareTo(SmsSceneEnum.ADMIN_MEMBER_LOGIN.getScene())==0) {
if (userService.getUserByMobile(reqVO.getMobile()) == null) {
throw exception(USER_NOT_EXISTS);
}
} }
// TODO 要根据不同的场景,校验是否有用户 // 发送验证码
smsCodeApi.sendSmsCode(AuthConvert.INSTANCE.convert(reqVO).setCreateIp(getClientIP())); smsCodeApi.sendSmsCode(AuthConvert.INSTANCE.convert(reqVO).setCreateIp(getClientIP()));
} }
/**
*
*/
@Override @Override
public String smsLogin(AuthSmsLoginReqVO reqVO, String userIp, String userAgent) { public String smsLogin(AuthSmsLoginReqVO reqVO, String userIp, String userAgent) {
// 校验验证码
/* 从 Member的AuhtConvert中拷贝出来的没单独写类 */ smsCodeApi.useSmsCode(AuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.ADMIN_MEMBER_LOGIN.getScene(), userIp));
if ( reqVO == null) {
return null;
}
SmsCodeUseReqDTO smsCodeUseReqDTO = new SmsCodeUseReqDTO();
smsCodeUseReqDTO.setMobile( reqVO.getMobile() );
smsCodeUseReqDTO.setCode( reqVO.getCode() );
smsCodeUseReqDTO.setScene( SmsSceneEnum.ADMIN_MEMBER_LOGIN.getScene() );
smsCodeUseReqDTO.setUsedIp(userIp);
smsCodeApi.useSmsCode(smsCodeUseReqDTO);
// 获得用户信息 // 获得用户信息
AdminUserDO user = userService.getUserByMobile(reqVO.getMobile()); AdminUserDO user = userService.getUserByMobile(reqVO.getMobile());
if (user == null) {
throw exception(USER_NOT_EXISTS);
if(user==null)
{
throw exception(USER_NOT_EXISTS);
} }
cn.hutool.core.lang.Assert.notNull(user, "获取用户失败,结果为空"); // 创建 LoginUser 对象
// 执行登陆
this.createLoginLog(user.getMobile(),LoginLogTypeEnum.LOGIN_MOBILE, LoginResultEnum.SUCCESS);
LoginUser loginUser = buildLoginUser(user); LoginUser loginUser = buildLoginUser(user);
// 缓存登陆用户到 Redis 中,返回 sessionId 编号 // 缓存登陆用户到 Redis 中,返回 sessionId 编号
@ -217,33 +189,6 @@ public class AdminAuthServiceImpl implements AdminAuthService {
return (LoginUser) authentication.getPrincipal(); return (LoginUser) authentication.getPrincipal();
} }
/**
*
* @param reqVO
*/
private void verifyCaptchaSmsSend(AuthSmsSendReqVO reqVO) {
// 如果验证码关闭,则不进行校验
if (!captchaService.isCaptchaEnable()) {
return;
}
// 校验验证码
ValidationUtils.validate(validator, reqVO, AuthLoginReqVO.CodeEnableGroup.class);
// 验证码不存在
final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME;
String code = captchaService.getCaptchaCode(reqVO.getUuid());
if (code == null) {
throw exception(AUTH_LOGIN_CAPTCHA_NOT_FOUND);
}
// 验证码不正确
if (!code.equals(reqVO.getCode())) {
// 创建登录失败日志(验证码不正确)
throw exception(AUTH_LOGIN_CAPTCHA_CODE_ERROR);
}
// 正确,所以要删除下验证码
captchaService.deleteCaptchaCode(reqVO.getUuid());
}
private void createLoginLog(String username, LoginLogTypeEnum logTypeEnum, LoginResultEnum loginResult) { private void createLoginLog(String username, LoginLogTypeEnum logTypeEnum, LoginResultEnum loginResult) {
// 获得用户 // 获得用户
AdminUserDO user = userService.getUserByUsername(username); AdminUserDO user = userService.getUserByUsername(username);
@ -277,7 +222,7 @@ public class AdminAuthServiceImpl implements AdminAuthService {
} }
@Override @Override
public String socialLogin(AuthSocialQuickLoginReqVO reqVO, String userIp, String userAgent) { public String socialQuickLogin(AuthSocialQuickLoginReqVO reqVO, String userIp, String userAgent) {
// 使用 code 授权码,进行登录。然后,获得到绑定的用户编号 // 使用 code 授权码,进行登录。然后,获得到绑定的用户编号
Long userId = socialUserService.getBindUserId(UserTypeEnum.ADMIN.getValue(), reqVO.getType(), Long userId = socialUserService.getBindUserId(UserTypeEnum.ADMIN.getValue(), reqVO.getType(),
reqVO.getCode(), reqVO.getState()); reqVO.getCode(), reqVO.getState());

View File

@ -77,24 +77,21 @@ export function socialBindLogin(type, code, state, username, password) {
} }
// 获取登录验证码 // 获取登录验证码
export function sendLoginSmsCode(mobile,scene,uuid,code) { export function sendSmsCode(mobile, scene) {
var datas = {
mobile
,scene
,uuid,
code
};
return request({ return request({
url: '/system/send-login-sms-code', url: '/system/auth/send-sms-code',
method: 'post', method: 'post',
data: datas data: {
mobile,
scene
}
}) })
} }
// 短信验证码登录 // 短信验证码登录
export function smsLogin(mobile, code) { export function smsLogin(mobile, code) {
return request({ return request({
url: '/system/sms-login', url: '/system/auth/sms-login',
method: 'post', method: 'post',
data: { data: {
mobile, mobile,

View File

@ -10,11 +10,11 @@ $buttonH: 50;
// container // container
$containerBgColor: #e6ebf2; $containerBgColor: #e6ebf2;
$containerBgImage: '../assets/images/bg.png'; $containerBgImage: '/assets/images/bg.png';
// container-logo // container-logo
$logoWidth: 417px; $logoWidth: 417px;
$logoHeight: 64px; $logoHeight: 64px;
$logoImage: '../assets/logo/login-logo.png'; $logoImage: '/assets/logo/logo.png';
// container-content // container-content
$contentWidth: round($W / $H * 100) * 1vw; $contentWidth: round($W / $H * 100) * 1vw;
$contentHeight: round($picH / $W * 100) / 100 * $contentWidth; $contentHeight: round($picH / $W * 100) / 100 * $contentWidth;
@ -22,7 +22,7 @@ $contentBgColor: #ffffff;
// container-content-pic // container-content-pic
$picWidth: round($picW / $H * 100) * 1vw; $picWidth: round($picW / $H * 100) * 1vw;
$picHeight: inherit; $picHeight: inherit;
$picImage: '../assets/images/pic.png'; $picImage: '/assets/images/pic.png';
// container-content-field // container-content-field
$fieldWidth: $contentWidth - $picWidth; $fieldWidth: $contentWidth - $picWidth;
$fieldHeight: inherit; $fieldHeight: inherit;
@ -270,7 +270,7 @@ $mobileRowH: 48;
$mobileButtonH: 48; $mobileButtonH: 48;
// container // container
$mobileContainerBgImage: '../assets/images/bg-mobile.png'; $mobileContainerBgImage: '/assets/images/bg-mobile.png';
// container-content // container-content
$mobileContentWidth: round($mobileContentW / $mobileW * 100) * 1vw; $mobileContentWidth: round($mobileContentW / $mobileW * 100) * 1vw;
$mobileContentHeight: round($mobileContentH / $mobileW * 100) / 100 * $mobileContentWidth; $mobileContentHeight: round($mobileContentH / $mobileW * 100) / 100 * $mobileContentWidth;
@ -278,7 +278,7 @@ $mobileContentHeight: round($mobileContentH / $mobileW * 100) / 100 * $mobileCon
$mobileFormWidth: round($mobileFormW / $mobileW *100) * 1vw; $mobileFormWidth: round($mobileFormW / $mobileW *100) * 1vw;
$mobileRowHeight: $mobileRowH * 1px; $mobileRowHeight: $mobileRowH * 1px;
$mobileButtonHeight: $mobileButtonH * 1px; $mobileButtonHeight: $mobileButtonH * 1px;
$iconBgImage: '../assets/images/icon.png'; $iconBgImage: '/assets/images/icon.png';
// - - - - - // - - - - -
@media screen and (max-width: 599px) { @media screen and (max-width: 599px) {
@ -294,7 +294,7 @@ $iconBgImage: '../assets/images/icon.png';
.logo { .logo {
display: none; display: none;
} }
.content { .content {
// //
width: $mobileContentWidth; width: $mobileContentWidth;
@ -383,5 +383,5 @@ $iconBgImage: '../assets/images/icon.png';
bottom: 20px; bottom: 20px;
} }
} }
} }

View File

@ -1,4 +1,3 @@
<template> <template>
<div class="container"> <div class="container">
<div class="logo"></div> <div class="logo"></div>
@ -10,159 +9,141 @@
<div class="field"> <div class="field">
<!-- [移动端]标题 --> <!-- [移动端]标题 -->
<h2 class="mobile-title"> <h2 class="mobile-title">
<h3 class="title">芋道后台管理系统</h3> <h3 class="title">芋道后台管理系统</h3>
</h2> </h2>
<!-- 表单 -->
<!-- 表单 -->
<div class="form-cont">
<el-tabs class="form" v-model="loginForm.loginType" style=" float:none;">
<el-tab-pane label="账号密码登录" name="uname">
</el-tab-pane>
<el-tab-pane label="短信验证码登录" name="sms">
</el-tab-pane>
</el-tabs>
<div>
<el-form ref="loginForm" :model="loginForm" :rules="LoginRules" class="login-form">
<el-form-item prop="tenantName" v-if="tenantEnable">
<el-input v-model="loginForm.tenantName" type="text" auto-complete="off" placeholder='租户'>
<svg-icon slot="prefix" icon-class="tree" class="el-input__icon input-icon" />
</el-input>
</el-form-item>
<el-form-item prop="username" v-if="loginForm.loginType=='uname'">
<el-input
v-model="loginForm.username"
type="text"
auto-complete="off"
placeholder="账号"
>
<svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
</el-input>
</el-form-item>
<el-form-item prop="password" v-if="loginForm.loginType=='uname'">
<el-input
v-model="loginForm.password"
type="password"
auto-complete="off"
placeholder="密码"
@keyup.enter.native="handleLogin"
>
<svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
</el-input>
</el-form-item>
<el-form-item prop="mobile" v-if="loginForm.loginType=='sms'">
<el-input v-model="loginForm.mobile" type="text" auto-complete="off" placeholder="请输入手机号">
<svg-icon slot="prefix" icon-class="phone" class="el-input__icon input-icon" />
</el-input>
</el-form-item>
<el-form-item prop="mobileCode" v-if="loginForm.loginType=='sms'">
<el-input v-model="loginForm.mobileCode" type="text" auto-complete="off" @keyup.enter.native="handleLogin" placeholder="短信验证码">
<template slot="icon">
<svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
</template>
<template slot="append">
<span v-if="mobileCodeTimer<=0" class="getMobileCode" @click="getSmsCode" style="cursor: pointer;"></span>
<span v-if="mobileCodeTimer>0" class="getMobileCode">{{mobileCodeTimer}}</span>
</template>
</el-input>
</el-form-item>
<el-form-item prop="code" v-if="captchaEnable"> <!-- 表单 -->
<el-input <div class="form-cont">
v-model="loginForm.code" <el-tabs class="form" v-model="loginForm.loginType" style=" float:none;">
auto-complete="off" <el-tab-pane label="账号密码登录" name="uname">
placeholder="验证码" </el-tab-pane>
style="width: 63%" <el-tab-pane label="短信验证码登录" name="sms">
@keyup.enter.native="handleLogin" </el-tab-pane>
> </el-tabs>
<svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" /> <div>
<el-form ref="loginForm" :model="loginForm" :rules="LoginRules" class="login-form">
<el-form-item prop="tenantName" v-if="tenantEnable">
<el-input v-model="loginForm.tenantName" type="text" auto-complete="off" placeholder='租户'>
<svg-icon slot="prefix" icon-class="tree" class="el-input__icon input-icon"/>
</el-input> </el-input>
<div class="login-code">
<img :src="codeUrl" @click="getCode" class="login-code-img"/>
</div>
</el-form-item> </el-form-item>
<el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;"></el-checkbox> <!-- 账号密码登录 -->
<div v-if="loginForm.loginType === 'uname'">
<el-form-item prop="username">
<el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
<svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
</el-input>
</el-form-item>
<el-form-item prop="password">
<el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码"
@keyup.enter.native="handleLogin">
<svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
</el-input>
</el-form-item>
<el-form-item prop="code" v-if="captchaEnable">
<el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
@keyup.enter.native="handleLogin">
<svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon"/>
</el-input>
<div class="login-code">
<img :src="codeUrl" @click="getCode" class="login-code-img"/>
</div>
</el-form-item>
<el-checkbox v-model="loginForm.rememberMe" style="margin:0 0 25px 0;"></el-checkbox>
</div>
<!-- 短信验证码登录 -->
<div v-if="loginForm.loginType === 'sms'">
<el-form-item prop="mobile">
<el-input v-model="loginForm.mobile" type="text" auto-complete="off" placeholder="请输入手机号">
<svg-icon slot="prefix" icon-class="phone" class="el-input__icon input-icon"/>
</el-input>
</el-form-item>
<el-form-item prop="mobileCode">
<el-input v-model="loginForm.mobileCode" type="text" auto-complete="off" placeholder="短信验证码"
@keyup.enter.native="handleLogin">
<template slot="icon">
<svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
</template>
<template slot="append">
<span v-if="mobileCodeTimer <= 0" class="getMobileCode" @click="getSmsCode" style="cursor: pointer;"></span>
<span v-if="mobileCodeTimer > 0" class="getMobileCode">{{ mobileCodeTimer }}</span>
</template>
</el-input>
</el-form-item>
</div>
<!-- 下方的登录按钮 -->
<el-form-item style="width:100%;"> <el-form-item style="width:100%;">
<el-button <el-button :loading="loading" size="medium" type="primary" style="width:100%;"
:loading="loading" @click.native.prevent="handleLogin">
size="medium"
type="primary"
style="width:100%;"
@click.native.prevent="handleLogin"
>
<span v-if="!loading"> </span> <span v-if="!loading"> </span>
<span v-else> ...</span> <span v-else> ...</span>
</el-button> </el-button>
</el-form-item> </el-form-item>
</el-form> </el-form>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<!-- footer --> <!-- footer -->
<div class="footer"> <div class="footer">
Copyright © 2020-2021 iocoder.cn All Rights Reserved. Copyright © 2020-2022 iocoder.cn All Rights Reserved.
</div> </div>
</div> </div>
</template> </template>
<script> <script>
import { getCodeImg,socialAuthRedirect ,sendLoginSmsCode} from "@/api/login"; import {getCodeImg, sendSmsCode, socialAuthRedirect} from "@/api/login";
import { getTenantIdByName } from "@/api/system/tenant"; import {getTenantIdByName} from "@/api/system/tenant";
import Cookies from "js-cookie"; import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt' import {decrypt, encrypt} from '@/utils/jsencrypt'
import {SystemUserSocialTypeEnum} from "@/utils/constants"; import {SystemUserSocialTypeEnum} from "@/utils/constants";
import { getTenantEnable } from "@/utils/ruoyi"; import {getTenantEnable} from "@/utils/ruoyi";
export default { export default {
name: "Login", name: "Login",
data() { data() {
return { return {
codeUrl: "", codeUrl: "",
captchaEnable: true, captchaEnable: true,
tenantEnable: true, tenantEnable: true,
mobileCodeTimer:0, mobileCodeTimer: 0,
loginForm: { loginForm: {
loginType:"sms", loginType: "uname",
username: "admin", username: "admin",
password: "admin123", password: "admin123",
mobile:"", mobile: "",
mobileCode:"", mobileCode: "",
rememberMe: false, rememberMe: false,
code: "", code: "",
uuid: "", uuid: "",
tenantName: "芋道源码", tenantName: "芋道源码",
}, },
scene:21, scene: 21,
LoginRules:{ LoginRules: {
username: [ username: [
{required: true, trigger: "blur", message: "用户名不能为空"}
{ required: true, trigger: "blur", message: "用户名不能为空" }
], ],
password: [ password: [
{ required: true, trigger: "blur", message: "密码不能为空" } {required: true, trigger: "blur", message: "密码不能为空"}
], ],
code: [{ required: true, trigger: "change", message: "验证码不能为空" }], code: [{required: true, trigger: "change", message: "验证码不能为空"}],
mobile: [ mobile: [
{required: true, trigger: "blur", message: "手机号不能为空"},
{ required: true, trigger: "blur", message: "手机号不能为空" }, {
{validator: function(rule, value, callback) { validator: function (rule, value, callback) {
if (/^1[34578]\d{9}$/.test(value) == false) { if (/^1[0-9]\d{9}$/.test(value) == false) {
callback(new Error("手机号格式错误")); callback(new Error("手机号格式错误"));
} else { } else {
callback(); callback();
} }
}, trigger: "blur" }, trigger: "blur"
} }
], ],
tenantName:[ tenantName: [
{ required: true, trigger: "blur", message: "租户不能为空" }, {required: true, trigger: "blur", message: "租户不能为空"},
{ {
validator: (rule, value, callback) => { validator: (rule, value, callback) => {
// debugger // debugger
@ -181,9 +162,9 @@ export default {
} }
] ]
}, },
loading: false,
loading: false,
redirect: undefined, redirect: undefined,
// //
SysUserSocialTypeEnum: SystemUserSocialTypeEnum, SysUserSocialTypeEnum: SystemUserSocialTypeEnum,
@ -234,23 +215,21 @@ export default {
password: password === undefined ? this.loginForm.password : decrypt(password), password: password === undefined ? this.loginForm.password : decrypt(password),
rememberMe: rememberMe === undefined ? false : Boolean(rememberMe), rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
tenantName: tenantName === undefined ? this.loginForm.tenantName : tenantName, tenantName: tenantName === undefined ? this.loginForm.tenantName : tenantName,
mobile:mobile === undefined ? this.loginForm.mobile : mobile, mobile: mobile === undefined ? this.loginForm.mobile : mobile,
mobileCode:mobileCode === undefined ? this.loginForm.mobileCode : mobileCode, mobileCode: mobileCode === undefined ? this.loginForm.mobileCode : mobileCode,
loginType:loginType === undefined ? this.loginForm.loginType : loginType, loginType: loginType === undefined ? this.loginForm.loginType : loginType,
}; };
}, },
handleLogin() { handleLogin() {
this.$refs.loginForm.validate(valid => { this.$refs.loginForm.validate(valid => {
if (valid) { if (valid) {
this.loading = true; this.loading = true;
// Cookie // Cookie
if (this.loginForm.rememberMe) { if (this.loginForm.rememberMe) {
Cookies.set("username", this.loginForm.username, { expires: 30 }); Cookies.set("username", this.loginForm.username, {expires: 30});
Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 }); Cookies.set("password", encrypt(this.loginForm.password), {expires: 30});
Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 }); Cookies.set('rememberMe', this.loginForm.rememberMe, {expires: 30});
Cookies.set('tenantName', this.loginForm.tenantName, { expires: 30 }); Cookies.set('tenantName', this.loginForm.tenantName, {expires: 30});
} else { } else {
Cookies.remove("username"); Cookies.remove("username");
Cookies.remove("password"); Cookies.remove("password");
@ -258,9 +237,10 @@ export default {
Cookies.remove('tenantName'); Cookies.remove('tenantName');
} }
// //
console.log("发起登录",this.loginForm); console.log("发起登录", this.loginForm);
this.$store.dispatch(this.loginForm.loginType=="sms"?"SmsLogin":"Login", this.loginForm).then(() => { this.$store.dispatch(this.loginForm.loginType === "sms" ? "SmsLogin" : "Login", this.loginForm).then(() => {
this.$router.push({ path: this.redirect || "/" }).catch(()=>{}); this.$router.push({path: this.redirect || "/"}).catch(() => {
});
}).catch(() => { }).catch(() => {
this.loading = false; this.loading = false;
this.getCode(); this.getCode();
@ -281,32 +261,26 @@ export default {
window.location.href = res.data; window.location.href = res.data;
}); });
}, },
/**以下为升级短信登录 */ /** ========== 以下为升级短信登录 ========== */
getSmsCode() {
changeLoginType(){ if (this.mobileCodeTimer > 0) return;
this.$refs.loginForm.validate(valid => {
}, if (!valid) return;
getSmsCode(){ sendSmsCode(this.loginForm.mobile, this.scene, this.loginForm.uuid, this.loginForm.code).then(res => {
if(this.mobileCodeTimer>0) return;
this.$refs.loginForm.validate(valid => {
if(!valid) return;
var _this=this;
sendLoginSmsCode(this.loginForm.mobile,this.scene,this.loginForm.uuid,this.loginForm.code).then(res => {
this.$modal.msgSuccess("获取验证码成功") this.$modal.msgSuccess("获取验证码成功")
this.mobileCodeTimer=60; this.mobileCodeTimer = 60;
var msgTimer = setInterval(function(){ let msgTimer = setInterval(() => {
_this.mobileCodeTimer=_this.mobileCodeTimer-1; this.mobileCodeTimer = this.mobileCodeTimer - 1;
if(_this.mobileCodeTimer<=0){ if (this.mobileCodeTimer <= 0) {
clearInterval(msgTimer); clearInterval(msgTimer);
} }
}, 1000);
},1000); });
}); });
});
} }
} }
}; };
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@import "~@/assets/styles/login.scss"; @import "~@/assets/styles/login.scss";
</style> </style>

File diff suppressed because it is too large Load Diff