新增注册功能 通过手机号注册账号90%

This commit is contained in:
WangHao 2021-04-18 20:36:23 +08:00
parent af5faf60df
commit 4131d8bdca
17 changed files with 557 additions and 228 deletions

View File

@ -6,9 +6,10 @@ import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus; import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.PhoneCode; import com.ruoyi.common.utils.PhoneCode;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bookmarkhtml.Const; import com.ruoyi.common.utils.bookmarkhtml.Const;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@ -26,7 +27,8 @@ public class RegisterPhoneController extends BaseController
@Autowired @Autowired
private ISqMenuService iSqMenuService; private ISqMenuService iSqMenuService;
@Autowired
private ISysUserService userService;
/** /**
* 发送注册验证码 * 发送注册验证码
*/ */
@ -35,11 +37,23 @@ public class RegisterPhoneController extends BaseController
{ {
AjaxResult ajaxResult = new AjaxResult(); AjaxResult ajaxResult = new AjaxResult();
ajaxResult.put("code", HttpStatus.SUCCESS); ajaxResult.put("code", HttpStatus.SUCCESS);
if (StringUtils.isEmpty(phone)){
ajaxResult.put("msg", "非法手机号,请重新输入!");
return ajaxResult;
}
int phoneCount = userService.countUserByPhone(phone);
if (phoneCount != 0) {
ajaxResult.put("msg", "此手机账号已经被使用,请前往登陆!");
return ajaxResult;
}
Long time = 3600L;//限制规定时间内 访问次数
//防止重复点击 //防止重复点击
boolean phoneCodelFlag = iSqMenuService.countRepetition(Const.PHONE_REGISTER,getAuthUser().getUserId(),3600L,10); //3600秒 最多请求10次验证码 boolean phoneCodelFlag = iSqMenuService.countRepetition(Const.PHONE_REGISTER,Long.valueOf(phone),time,10); //3600秒 最多请求10次验证码
if(!phoneCodelFlag){ if(!phoneCodelFlag){
ajaxResult.put("msg","短时间内发送频繁,请稍后再操作!"); ajaxResult.put("msg","短时间内发送频繁,请过几个小时就再操作!");
return ajaxResult; return ajaxResult;
} }
@ -50,7 +64,8 @@ public class RegisterPhoneController extends BaseController
ajaxResult.put("msg","短信发送成功,请在"+Constants.CAPTCHA_PHONE_EXPIRATION+"分钟内验证。"); ajaxResult.put("msg","短信发送成功,请在"+Constants.CAPTCHA_PHONE_EXPIRATION+"分钟内验证。");
return ajaxResult; return ajaxResult;
}else { }else {
ajaxResult.put("msg","短信发送失败"); ajaxResult.put("code", HttpStatus.ERROR);
ajaxResult.put("msg","系统错误,短信发送失败,请稍后再试!");
return ajaxResult; return ajaxResult;
} }
} }

View File

@ -2,6 +2,11 @@ package com.ruoyi.web.controller.system;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisKey;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@ -39,21 +44,32 @@ public class SysLoginController
@Autowired @Autowired
private TokenService tokenService; private TokenService tokenService;
@Autowired
private ISysUserService userService;
/** /**
* 注册方法 * 注册方法
* *
* @param loginBody 注册信息 * @param registerBody 注册信息
* @return 结果 * @return 结果
*/ */
@PostMapping("/registerUser") @PostMapping("/registerUser")
public AjaxResult registerUser(@RequestBody LoginBody loginBody) public AjaxResult registerUser(@RequestBody RegisterBody registerBody) {
{
AjaxResult ajax = AjaxResult.success(); AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = loginService.registerUser(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), String msg = loginService.registerUser(registerBody.getUsername(), registerBody.getPassword(), registerBody.getPhoneCode(),
loginBody.getUuid(),loginBody.getEmail(),loginBody.getPhone()); registerBody.getUuid(), registerBody.getEmail(), registerBody.getPhone());
ajax.put(Constants.TOKEN, token);
if (Constants.LOGIN_SUCCESS.equals(msg)) {
ajax.put("msg", "注册成功,请前往登陆!");
} else if (Constants.LOGIN_FAIL.equals(msg)) {
ajax.put("code", HttpStatus.ERROR);
ajax.put("msg", "注册失败,系统错误,请稍后再尝试!");
} else {
ajax.put("code", HttpStatus.ERROR);
ajax.put("msg", msg);
}
return ajax; return ajax;
} }

View File

@ -4,6 +4,7 @@ import cn.hutool.core.date.DateUtil;
import com.github.wujun234.uid.UidGenerator; import com.github.wujun234.uid.UidGenerator;
import com.ruoyi.bookmark.service.ISqMenuService; import com.ruoyi.bookmark.service.ISqMenuService;
import com.ruoyi.common.core.redis.RedisUtil; import com.ruoyi.common.core.redis.RedisUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bookmarkhtml.Const; import com.ruoyi.common.utils.bookmarkhtml.Const;
import org.junit.Test; import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -25,12 +26,9 @@ public class UIDTest extends BaseSpringBootTest{
private UidGenerator cachedUidGenerator; private UidGenerator cachedUidGenerator;
@Autowired @Autowired
private ISqMenuService iSqMenuService; private ISqMenuService iSqMenuService;
@Autowired
private RedisUtil redisUtil;
@Test @Test
public void testSerialGenerate() { public void testSerialGenerate() {
// Generate UID
long cachedUidGeneratoruid = cachedUidGenerator.getUID(); long cachedUidGeneratoruid = cachedUidGenerator.getUID();
long defaultUidGeneratoruid = defaultUidGenerator.getUID(); //用这个 long defaultUidGeneratoruid = defaultUidGenerator.getUID(); //用这个
@ -38,11 +36,6 @@ public class UIDTest extends BaseSpringBootTest{
System.out.println("cachedUidGeneratoruid解密:"+cachedUidGenerator.parseUID(cachedUidGeneratoruid)); System.out.println("cachedUidGeneratoruid解密:"+cachedUidGenerator.parseUID(cachedUidGeneratoruid));
System.out.println("defaultUidGeneratoruid:"+defaultUidGeneratoruid); System.out.println("defaultUidGeneratoruid:"+defaultUidGeneratoruid);
System.out.println("defaultUidGeneratoruid解密:"+cachedUidGenerator.parseUID(defaultUidGeneratoruid)); System.out.println("defaultUidGeneratoruid解密:"+cachedUidGenerator.parseUID(defaultUidGeneratoruid));
// Parse UID into [Timestamp, WorkerId, Sequence]
// {"UID":"450795408770","timestamp":"2019-02-20 14:55:39","workerId":"27","sequence":"2"}
// System.out.println(cachedUidGenerator.parseUID(uid));
} }
@Test @Test
public void dateTest(){ public void dateTest(){
@ -64,5 +57,27 @@ public class UIDTest extends BaseSpringBootTest{
} }
//密码加密
@Test
public void rest3(){
String newPassword = "admin123";
String password =SecurityUtils.encryptPassword(newPassword);
System.out.println(password);
}
//密码加密对比
@Test
public void rest4(){
String newPassword = "2654430977wh";
if( SecurityUtils.matchesPassword(newPassword, "$2a$10$zAx2lmzBNwmL.nFqfLmps.CsrSblAPtMvy29Ns9fwzeq8hIoKLT72")){ //newPassword 密码 password加密的后密码
System.out.println("密码相同!");
}else{
System.out.println("密码不相同!");
}
}
} }

View File

@ -69,7 +69,7 @@ public class Constants
/** /**
* 手机号验证码有效期分钟 * 手机号验证码有效期分钟
*/ */
public static final Integer CAPTCHA_PHONE_EXPIRATION = 2; public static final Integer CAPTCHA_PHONE_EXPIRATION = 15;
/** /**
* 令牌 * 令牌

View File

@ -17,19 +17,6 @@ public class LoginBody
*/ */
private String password; private String password;
/**
* 邮箱
*/
private String email;
/**
* 手机号
*/
private String phone;
/**
* 手机号验证码
*/
private String phoneCode;
/** /**
* 验证码 * 验证码
*/ */
@ -79,28 +66,4 @@ public class LoginBody
{ {
this.uuid = uuid; this.uuid = uuid;
} }
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhoneCode() {
return phoneCode;
}
public void setPhoneCode(String phoneCode) {
this.phoneCode = phoneCode;
}
} }

View File

@ -0,0 +1,106 @@
package com.ruoyi.common.core.domain.model;
/**
* 用户登录对象
*
* @author ruoyi
*/
public class RegisterBody
{
/**
* 用户名
*/
private String username;
/**
* 用户密码
*/
private String password;
/**
* 邮箱
*/
private String email;
/**
* 手机号
*/
private String phone;
/**
* 手机号验证码
*/
private String phoneCode;
/**
* 验证码
*/
private String code;
/**
* 唯一标识
*/
private String uuid = "";
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
public String getUuid()
{
return uuid;
}
public void setUuid(String uuid)
{
this.uuid = uuid;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhoneCode() {
return phoneCode;
}
public void setPhoneCode(String phoneCode) {
this.phoneCode = phoneCode;
}
}

View File

@ -12,4 +12,6 @@ public class RedisKey {
public static final String BOOKMARK ="bookMark:"; public static final String BOOKMARK ="bookMark:";
public static final String CONNECTOR =":"; public static final String CONNECTOR =":";
public static final String REGISTER ="register:";
} }

View File

@ -10,6 +10,7 @@ import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.profile.IClientProfile;
import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisKey;
import com.ruoyi.common.core.redis.RedisUtil; import com.ruoyi.common.core.redis.RedisUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -37,6 +38,7 @@ public class PhoneCode {
*/ */
public static Boolean getPhonemsg(String phone) { public static Boolean getPhonemsg(String phone) {
String key = RedisKey.BOOKMARK + RedisKey.REGISTER + phone;
// 短信验证---阿里 // 短信验证---阿里
// 设置超时时间-可自行调整 // 设置超时时间-可自行调整
System.setProperty(PhoneDeploy.defaultConnectTimeout, PhoneDeploy.Timeout); System.setProperty(PhoneDeploy.defaultConnectTimeout, PhoneDeploy.Timeout);
@ -83,16 +85,16 @@ public class PhoneCode {
if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) { if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
// 请求成功 // 请求成功
RedisUtil redisUtil = new RedisUtil(); RedisUtil redisUtil = new RedisUtil();
redisUtil.setEx(phone,code,Constants.CAPTCHA_PHONE_EXPIRATION, TimeUnit.MINUTES); redisUtil.setEx(key,code,Constants.CAPTCHA_PHONE_EXPIRATION, TimeUnit.MINUTES);
return true; return true;
} else { } else {
// 验证码失败 如果验证码出错会输出错误码告诉你具体原因 // 验证码失败 如果验证码出错会输出错误码告诉你具体原因
logger.info("手机号:" + code + " 时间"+DateUtil.now()+" 发送失败!!错误日志:"+sendSmsResponse.getCode()); logger.info("手机号:" + phone + " 时间"+DateUtil.now()+" 发送失败!!错误日志:"+sendSmsResponse.getCode());
return false; return false;
} }
} catch (ClientException e) { } catch (ClientException e) {
e.printStackTrace(); e.printStackTrace();
logger.info("手机号:" + code + " 时间"+DateUtil.now()+" 发送失败!!"); logger.info("手机号:" + phone + " 时间"+DateUtil.now()+" 发送失败!!");
return false; return false;
} }
} }

View File

@ -20,7 +20,7 @@ import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl;
/** /**
* spring security配置 * spring security配置
* *
* @author ruoyi * @author ruoyi
*/ */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@ -31,7 +31,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
*/ */
@Autowired @Autowired
private UserDetailsService userDetailsService; private UserDetailsService userDetailsService;
/** /**
* 认证失败处理类 * 认证失败处理类
*/ */
@ -55,7 +55,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
*/ */
@Autowired @Autowired
private CorsFilter corsFilter; private CorsFilter corsFilter;
/** /**
* 解决 无法直接注入 AuthenticationManager * 解决 无法直接注入 AuthenticationManager
* *
@ -98,6 +98,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
.authorizeRequests() .authorizeRequests()
// 对于登录login 验证码captchaImage 允许匿名访问 // 对于登录login 验证码captchaImage 允许匿名访问
.antMatchers("/login", "/captchaImage").anonymous() .antMatchers("/login", "/captchaImage").anonymous()
// 对于注册账号 手机号验证码 允许匿名访问
.antMatchers("/registerUser", "/registerPhoneCode").anonymous()
.antMatchers( .antMatchers(
HttpMethod.GET, HttpMethod.GET,
"/*.html", "/*.html",
@ -125,7 +127,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter
httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class); httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
} }
/** /**
* 强散列哈希加密实现 * 强散列哈希加密实现
*/ */

View File

@ -4,6 +4,10 @@ import javax.annotation.Resource;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisKey;
import com.ruoyi.common.core.redis.RedisUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService; import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
@ -40,6 +44,9 @@ public class SysLoginService
@Autowired @Autowired
private RedisCache redisCache; private RedisCache redisCache;
@Autowired
private RedisUtil redisUtil;
@Autowired @Autowired
private ISysUserService sysUserService; private ISysUserService sysUserService;
@ -101,36 +108,42 @@ public class SysLoginService
* *
* @param username 用户名 * @param username 用户名
* @param password 密码 * @param password 密码
* @param code 验证码 * @param phone 手机号
* @param phoneCode 手机号验证码
* @param uuid 唯一标识 * @param uuid 唯一标识
* @param email 邮箱 * @param email 邮箱
* @param phone 手机号
* @return 结果 * @return 结果
*/ */
public String registerUser(String username, String password, String code, String uuid, String email, String phone) { public String registerUser(String username, String password, String phoneCode, String uuid, String email, String phone) {
int usernameCount = sysUserService.countUserByUserName(username); int usernameCount = sysUserService.countUserByUserName(username);
if (usernameCount != 0) { if (usernameCount != 0) {
return username + "登陆账号已经存在,请更换!"; return username + "登陆账号已经被使用,请更换!";
} }
int phoneCount = sysUserService.countUserByPhone(phone); int phoneCount = sysUserService.countUserByPhone(phone);
if (phoneCount != 0) { if (phoneCount != 0) {
return phone + "手机账号已经存在,请更换!"; return phone + "手机账号已经被使用,请更换!";
} }
// String key = RedisKey.BOOKMARK + RedisKey.REGISTER + phone;
//验证传入的手机号和验证码是否匹配 // //验证传入的手机号和验证码是否匹配
// String redisPhoneCode = redisUtil.get(key);
// if (StringUtils.isEmpty(redisPhoneCode)){
// return "验证码已经过期!";
// }
// if (!redisPhoneCode.equals(phoneCode)){
// return "验证码错误!";
// }else {
// //验证码正确 删除验证码 不可重复使用
// redisUtil.delete(key);
// }
//加密信息存入数据库 //加密信息存入数据库
SysUser user = new SysUser(); SysUser user = new SysUser();
user.setUserName(username); user.setUserName(username);
user.setPassword(password); user.setPassword(SecurityUtils.encryptPassword(password));
user.setDeptId(100L); user.setDeptId(100L);
user.setNickName(username); user.setNickName(username);
user.setPhonenumber(phone);
user.setCreateTime(DateUtil.date(System.currentTimeMillis())); user.setCreateTime(DateUtil.date(System.currentTimeMillis()));
user.setUpdateBy("admin"); user.setUpdateBy("admin");
return sysUserService.insertUser(user)!=0?Constants.LOGIN_SUCCESS:Constants.LOGIN_FAIL; return sysUserService.insertUser(user)!=0?Constants.LOGIN_SUCCESS:Constants.LOGIN_FAIL;

View File

@ -117,7 +117,7 @@ public interface SysUserMapper
*/ */
public int selectUserByEmail(String email); public int selectUserByEmail(String email);
/** /**
* 查询登陆名称是否唯一 * 查询登陆账号是否唯一
* *
* @param userName 用户名 * @param userName 用户名
* @return 用户对象信息 * @return 用户对象信息

View File

@ -87,16 +87,16 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</select> </select>
<select id="selectUserByEmail" parameterType="String" resultType="int"> <select id="selectUserByEmail" parameterType="String" resultType="int">
SELECT count(*) where email = #{email} SELECT count(*) from sys_user where email = #{email}
</select> </select>
<select id="countUserByUserName" parameterType="String" resultType="int"> <select id="countUserByUserName" parameterType="String" resultType="int">
SELECT count(*) where user_name = #{userName} SELECT count(*) from sys_user where user_name = #{userName}
</select> </select>
<select id="countUserByPhone" parameterType="String" resultType="int"> <select id="countUserByPhone" parameterType="String" resultType="int">
SELECT count(*) where phonenumber = #{phone} SELECT count(*) from sys_user where phonenumber = #{phone}
</select> </select>

View File

@ -1,40 +1,69 @@
import request from '@/utils/request' import request from '@/utils/request'
// 登录方法 // 登录方法
export function login(username, password, code, uuid) { export function login(username, password, code, uuid) {
const data = { const data = {
username, username,
password, password,
code, code,
uuid uuid
} }
return request({ return request({
url: '/login', url: '/login',
method: 'post', method: 'post',
data: data data: data
}) })
} }
// 获取用户详细信息 // 获取用户详细信息
export function getInfo() { export function getInfo() {
return request({ return request({
url: '/getInfo', url: '/getInfo',
method: 'get' method: 'get'
}) })
} }
// 退出方法 // 退出方法
export function logout() { export function logout() {
return request({ return request({
url: '/logout', url: '/logout',
method: 'post' method: 'post'
}) })
} }
// 获取验证码 // 获取验证码
export function getCodeImg() { export function getCodeImg() {
return request({ return request({
url: '/captchaImage', url: '/captchaImage',
method: 'get' method: 'get'
}) })
} }
// 注册账号方法
export function registerUser(username, password, phone, phoneCode) {
const data = {
username,
password,
phone,
phoneCode
}
return request({
url: '/registerUser',
method: 'post',
data: data
})
}
// 获取手机号验证码注册
export function getregisterUser(phone) {
var query={
phone:phone
}
return request({
url: '/registerPhoneCode',
method: 'get',
params:query
})
}

View File

@ -1,96 +1,112 @@
import { login, logout, getInfo } from '@/api/login' import { login, logout, getInfo,registerUser } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth' import { getToken, setToken, removeToken } from '@/utils/auth'
const user = { const user = {
state: { state: {
token: getToken(), token: getToken(),
name: '', name: '',
avatar: '', avatar: '',
roles: [], roles: [],
permissions: [] permissions: []
}, },
mutations: { mutations: {
SET_TOKEN: (state, token) => { SET_TOKEN: (state, token) => {
state.token = token state.token = token
}, },
SET_NAME: (state, name) => { SET_NAME: (state, name) => {
state.name = name state.name = name
}, },
SET_AVATAR: (state, avatar) => { SET_AVATAR: (state, avatar) => {
state.avatar = avatar state.avatar = avatar
}, },
SET_ROLES: (state, roles) => { SET_ROLES: (state, roles) => {
state.roles = roles state.roles = roles
}, },
SET_PERMISSIONS: (state, permissions) => { SET_PERMISSIONS: (state, permissions) => {
state.permissions = permissions state.permissions = permissions
} }
}, },
actions: { actions: {
// 登录 // 登录
Login({ commit }, userInfo) { Login({ commit }, userInfo) {
const username = userInfo.username.trim() const username = userInfo.username.trim()
const password = userInfo.password const password = userInfo.password
const code = userInfo.code const code = userInfo.code
const uuid = userInfo.uuid const uuid = userInfo.uuid
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
login(username, password, code, uuid).then(res => { login(username, password, code, uuid).then(res => {
setToken(res.token) setToken(res.token)
commit('SET_TOKEN', res.token) commit('SET_TOKEN', res.token)
resolve() resolve()
}).catch(error => { }).catch(error => {
reject(error) reject(error)
}) })
}) })
}, },
// 注册
// 获取用户信息 register({ commit }, userInfo) {
GetInfo({ commit, state }) { var that = this;
return new Promise((resolve, reject) => { const username = userInfo.username.trim()
getInfo(state.token).then(res => { const password = userInfo.password
const user = res.user const phone = userInfo.phone
const avatar = user.avatar == "" ? require("@/assets/image/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar; const phoneCode = userInfo.phoneCode
if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组 return new Promise((resolve, reject) => {
commit('SET_ROLES', res.roles) registerUser(username, password, phone, phoneCode).then(res => {
commit('SET_PERMISSIONS', res.permissions)
} else { resolve(res)
commit('SET_ROLES', ['ROLE_DEFAULT']) }).catch(error => {
} reject(error)
commit('SET_NAME', user.userName) })
commit('SET_AVATAR', avatar) })
resolve(res) },
}).catch(error => {
reject(error) // 获取用户信息
}) GetInfo({ commit, state }) {
}) return new Promise((resolve, reject) => {
}, getInfo(state.token).then(res => {
const user = res.user
// 退出系统 const avatar = user.avatar == "" ? require("@/assets/image/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
LogOut({ commit, state }) { if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
return new Promise((resolve, reject) => { commit('SET_ROLES', res.roles)
logout(state.token).then(() => { commit('SET_PERMISSIONS', res.permissions)
commit('SET_TOKEN', '') } else {
commit('SET_ROLES', []) commit('SET_ROLES', ['ROLE_DEFAULT'])
commit('SET_PERMISSIONS', []) }
removeToken() commit('SET_NAME', user.userName)
resolve() commit('SET_AVATAR', avatar)
}).catch(error => { resolve(res)
reject(error) }).catch(error => {
}) reject(error)
}) })
}, })
},
// 前端 登出
FedLogOut({ commit }) { // 退出系统
return new Promise(resolve => { LogOut({ commit, state }) {
commit('SET_TOKEN', '') return new Promise((resolve, reject) => {
removeToken() logout(state.token).then(() => {
resolve() commit('SET_TOKEN', '')
}) commit('SET_ROLES', [])
} commit('SET_PERMISSIONS', [])
} removeToken()
} resolve()
}).catch(error => {
export default user reject(error)
})
})
},
// 前端 登出
FedLogOut({ commit }) {
return new Promise(resolve => {
commit('SET_TOKEN', '')
removeToken()
resolve()
})
}
}
}
export default user

View File

@ -1,7 +1,7 @@
<template> <template>
<div class="login"> <div class="login">
<el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form"> <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
<h3 class="title">藏趣云</h3> <h3 class="title">{{h3}}</h3>
<el-form-item prop="username"> <el-form-item prop="username">
<el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号"> <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" /> <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
@ -18,7 +18,40 @@
<svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" /> <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
</el-input> </el-input>
</el-form-item> </el-form-item>
<el-form-item prop="code">
<el-form-item prop="phone" v-if="!loginFlag">
<el-input
v-model="loginForm.phone"
auto-complete="off"
placeholder="手机号码"
style="width: 100%"
@keyup.enter.native="handleLogin"
>
<svg-icon slot="prefix" icon-class="phone" class="el-input__icon input-icon" />
</el-input>
</el-form-item>
<el-form-item prop="phoneCode" v-if="!loginFlag">
<el-input
v-model="loginForm.phoneCode"
type="text"
auto-complete="off"
placeholder="验证码"
style="width: 65%"
@keyup.enter.native="handleLogin"
>
<svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
</el-input>
<el-button v-show="verShow" @click="handleClick()">获取验证码</el-button>
<el-button :disabled="!verShow" style="width: 30%" v-show="!verShow" @click="handleClick()">{{timer}}</el-button>
</el-form-item>
<el-form-item prop="code" v-if="loginFlag">
<el-input <el-input
v-model="loginForm.code" v-model="loginForm.code"
auto-complete="off" auto-complete="off"
@ -33,6 +66,7 @@
</div> </div>
</el-form-item> </el-form-item>
<el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox> <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
<a class="register" @click="switchLogin">{{switchLoginText}}>></a>
<el-form-item style="width:100%;"> <el-form-item style="width:100%;">
<el-button <el-button
:loading="loading" :loading="loading"
@ -41,8 +75,8 @@
style="width:100%;" style="width:100%;"
@click.native.prevent="handleLogin" @click.native.prevent="handleLogin"
> >
<span v-if="!loading"> </span> <span v-if="!loading">{{loginButton}}</span>
<span v-else> 中...</span> <span v-else>{{loginButtonMeg}}</span>
</el-button> </el-button>
</el-form-item> </el-form-item>
</el-form> </el-form>
@ -54,7 +88,7 @@
</template> </template>
<script> <script>
import { getCodeImg } from "@/api/login"; import { getCodeImg,getregisterUser } from "@/api/login";
import Cookies from "js-cookie"; import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt' import { encrypt, decrypt } from '@/utils/jsencrypt'
@ -62,12 +96,21 @@ export default {
name: "Login", name: "Login",
data() { data() {
return { return {
loginFlag:true,//
h3: "藏趣云",
loginButton:"登 录",
loginButtonMeg:"登 录 中...",
switchLoginText:"前往注册",
codeUrl: "", codeUrl: "",
cookiePassword: "", cookiePassword: "",
verShow:true,//
timer:60, //
loginForm: { loginForm: {
username: "", username: "",
password: "", password: "",
rememberMe: false, rememberMe: false,
phone:"",
phoneCode:"",
code: "", code: "",
uuid: "" uuid: ""
}, },
@ -80,6 +123,20 @@ export default {
], ],
code: [{ required: true, trigger: "change", message: "验证码不能为空" }] code: [{ required: true, trigger: "change", message: "验证码不能为空" }]
}, },
registerRules: {
username: [
{ required: true, trigger: "blur", message: "用户名不能为空" }
],
password: [
{ required: true, trigger: "blur", message: "密码不能为空" }
],
phone: [
{required: true, trigger: "blur", message: "手机号不能为空"}
],
phoneCode: [
{required: true, trigger: "change", message: "手机验证码不能为空"}
]
},
loading: false, loading: false,
redirect: undefined redirect: undefined
}; };
@ -103,6 +160,41 @@ export default {
this.loginForm.uuid = res.uuid; this.loginForm.uuid = res.uuid;
}); });
}, },
//
handleClick(){
var phone=this.loginForm.phone;
if (phone==null||phone==undefined||phone==''||phone.length!=11||!(/^1[34578]\d{9}$/.test(phone))){
this.$message.error('手机号格式错误,请重填!');
return false;
}
//
this.getPhoneCode();
var _this=this;
_this.verShow = false;
var auth_timer = setInterval(()=>{
_this.timer--;
if(this.timer<=0){
_this.verShow = true;
_this.timer=60
clearInterval(auth_timer)
}
},1000)
},
getPhoneCode() {
var phone=this.loginForm.phone;
getregisterUser(phone).then(res => {
if (res.code==200){
this.$message({
message: res.msg,
type: 'success'
});
}if (res.code==500) {
this.$message.error(res.msg);
}else{
this.$message.error('系统错误,短信发送失败,请稍后再试!');
}
}).catch((e) => {});;
},
getCookie() { getCookie() {
const username = Cookies.get("username"); const username = Cookies.get("username");
const password = Cookies.get("password"); const password = Cookies.get("password");
@ -114,6 +206,16 @@ export default {
}; };
}, },
handleLogin() { handleLogin() {
if (this.loginFlag){
this.loginUser();
} else{
this.register();
}
},
//
loginUser() {
this.$refs.loginForm.validate(valid => { this.$refs.loginForm.validate(valid => {
if (valid) { if (valid) {
this.loading = true; this.loading = true;
@ -137,12 +239,60 @@ export default {
}); });
} }
}); });
},
//
register(){
this.$refs.loginForm.validate(valid => {
if (valid) {
this.loading = true;
this.$store
.dispatch("register", this.loginForm)
.then(res => {
if(res.code == 200){
this.$message({
message: res.msg,
type: 'success'
});
}else {
this.$message.error(res.msg);
}
this.loading = false;//...
})
.catch(() => {
this.loading = false;
});
}
});
},
//
switchLogin(){
this.loginFlag=this.loginFlag?false:true;
this.h3 = this.loginFlag?"藏趣云":"用户注册";
this.loginButton = this.loginFlag?"登 录":"注册";
this.loginButtonMeg = this.loginFlag?"登 录 中...":"注 册 中...";
this.switchLoginText = this.loginFlag?"前往注册":"返回登陆";
this.$message({
message: this.loginFlag?"返回登陆":"前往注册",
type: 'warning'
});
} }
} }
}; };
</script> </script>
<style rel="stylesheet/scss" lang="scss"> <style rel="stylesheet/scss" lang="scss">
.register{
float: right;color: #6a6a6a;
font-size: 14px;
}
.register:hover{
color: #7a6df0;
font-weight: 600;
}
.login { .login {
display: flex; display: flex;
justify-content: center; justify-content: center;

View File

@ -186,13 +186,13 @@ public interface ISqMenuService
/** /**
* *
* 显示l时间内 只能访问i次 * 通用 工具类 显示l时间内 只能访问i次
* *
* @param phoneRegister 功能标识符 * @param phoneRegister 功能标识符
* @param userId 用户id * @param flag 用户id或者uid 等唯一标识符
* @param time 时间单位秒 * @param time 时间单位秒
* @param i 次数 * @param i 次数
* @return * @return
*/ */
Boolean countRepetition(String phoneRegister, Long userId, long time, int i); Boolean countRepetition(String phoneRegister, Long flag, long time, int i);
} }

View File

@ -335,9 +335,9 @@ public class SqMenuServiceImpl implements ISqMenuService
@Override @Override
public Boolean countRepetition(String state, Long userId, long time, int i) { public Boolean countRepetition(String state, Long flag, long time, int i) {
String key = RedisKey.BOOKMARK + state + RedisKey.CONNECTOR + userId.toString(); String key = RedisKey.BOOKMARK + state + RedisKey.CONNECTOR + flag.toString();
Long count = redisUtil.lLen(key); Long count = redisUtil.lLen(key);
if (count.intValue() < i) { if (count.intValue() < i) {
//插入到尾部 //插入到尾部