样式:
前端:
login.vue
<template>
<view class="normal-login-container">
<view class="login-form-content">
<view class="input-item flex align-center">
<view class="iconfont icon-user icon"></view>
<input v-model="loginForm.username" class="input" type="text" placeholder="请输入账号" maxlength="30" />
</view>
<view class="input-item flex align-center">
<view class="iconfont icon-password icon"></view>
<input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" />
</view>
<view class="input-item flex align-center" style="width: 60%;margin: 0px;" v-if="captchaEnabled">
<view class="iconfont icon-code icon"></view>
<input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" />
<view class="login-code">
<image :src="codeUrl" @click="getCode" class="login-code-img"></image>
</view>
</view>
<view class="action-btn">
<button @click="handleLogin" class="login-btn cu-btn block bg-blue lg round">登录</button>
</view>
</view>
</view>
</template>
<script>
import { getCodeImg } from '@/api/login'
export default {
data() {
return {
codeUrl: "",
captchaEnabled: true,
loginForm: {
username: "",
password: "",
code: "",
uuid: ''
}
}
},
created() {
this.getCode()
},
methods: {
// 获取图形验证码
getCode() {
getCodeImg().then(res => {
this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
if (this.captchaEnabled) {
this.codeUrl = 'data:image/gif;base64,' + res.img
this.loginForm.uuid = res.uuid
}
})
},
// 登录方法
async handleLogin() {
if (this.loginForm.username === "") {
this.modal.msgError("请输入您的账号")
} else if (this.loginForm.password === "") {
this.modal.msgError("请输入您的密码")
} else if (this.loginForm.code === "" && this.captchaEnabled) {
this.modal.msgError("请输入验证码")
} else {
this.modal.loading("登录中,请耐心等待...")
this.pwdLogin()
}
},
// 密码登录
async pwdLogin() {
this.store.dispatch('Login', this.loginForm).then(() => {
this.modal.closeLoading()
this.loginSuccess()
}).catch(() => {
if (this.captchaEnabled) {
this.getCode()
}
})
},
// 登录成功后,处理函数
loginSuccess(result) {
// 设置用户信息
this.store.dispatch('GetInfo').then(res => {
this.tab.reLaunch('/pages/index')
})
}
}
}
</script>
<style lang="scss">
page {
background-color: #ffffff;
}
.normal-login-container {
width: 100%;
.login-form-content {
text-align: center;
margin: 20px auto;
margin-top: 15%;
width: 80%;
.input-item {
margin: 20px auto;
background-color: #f5f6f7;
height: 45px;
border-radius: 20px;
.icon {
font-size: 38rpx;
margin-left: 10px;
color: #999;
}
.input {
width: 100%;
font-size: 14px;
line-height: 20px;
text-align: left;
padding-left: 15px;
}
}
.login-btn {
margin-top: 40px;
height: 45px;
}
.login-code {
height: 38px;
float: right;
.login-code-img {
height: 38px;
position: absolute;
margin-left: 10px;
width: 200rpx;
}
}
}
}
</style>
login.js
import request from '@/utils/request'
// 登录方法
export function login(username, password, code, uuid) {
const data = {
username,
password,
code,
uuid
}
return request({
'url': '/login',
headers: {
isToken: false
},
'method': 'post',
'data': data
})
}
// 注册方法
export function register(data) {
return request({
url: '/register',
headers: {
isToken: false
},
method: 'post',
data: data
})
}
// 获取用户详细信息
export function getInfo() {
return request({
'url': '/getInfo',
'method': 'get'
})
}
// 退出方法
export function logout() {
return request({
'url': '/logout',
'method': 'post'
})
}
// 获取验证码
export function getCodeImg() {
return request({
'url': '/captchaImage',
headers: {
isToken: false
},
method: 'get',
timeout: 20000
})
}
八个Utils:
const TokenKey = 'App-Token'
export function getToken() {
return uni.getStorageSync(TokenKey)
}
export function setToken(token) {
return uni.setStorageSync(TokenKey, token)
}
export function removeToken() {
return uni.removeStorageSync(TokenKey)
}
/**
* 显示消息提示框
* @param content 提示的标题
*/
export function toast(content) {
uni.showToast({
icon: 'none',
title: content
})
}
/**
* 显示模态弹窗
* @param content 提示的标题
*/
export function showConfirm(content) {
return new Promise((resolve, reject) => {
uni.showModal({
title: '提示',
content: content,
cancelText: '取消',
confirmText: '确定',
success: function(res) {
resolve(res)
}
})
})
}
export function praseStrEmpty(str) {
if (!str || str == "undefined" || str == "null") {
return "";
}
return str;
}
/**
* 参数处理
* @param params 参数
*/
export function tansParams(params) {
let result = ''
for (const propName of Object.keys(params)) {
const value = params[propName]
var part = encodeURIComponent(propName) + "="
if (value !== null && value !== "" && typeof (value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
let params = propName + '[' + key + ']'
var subPart = encodeURIComponent(params) + "="
result += subPart + encodeURIComponent(value[key]) + "&"
}
}
} else {
result += part + encodeURIComponent(value) + "&"
}
}
}
return result
}
const constant = {
avatar: 'vuex_avatar',
name: 'vuex_name',
roles: 'vuex_roles',
permissions: 'vuex_permissions'
}
export default constant
export default {
'401': '认证失败,无法访问系统资源',
'403': '当前操作没有权限',
'404': '访问资源不存在',
'default': '系统未知错误,请反馈给管理员'
}
import store from '@/store'
/**
* 字符权限校验
* @param {Array} value 校验值
* @returns {Boolean}
*/
export function checkPermi(value) {
if (value && value instanceof Array && value.length > 0) {
const permissions = store.getters && store.getters.permissions
const permissionDatas = value
const all_permission = "*:*:*"
const hasPermission = permissions.some(permission => {
return all_permission === permission || permissionDatas.includes(permission)
})
if (!hasPermission) {
return false
}
return true
} else {
console.error(`need roles! Like checkPermi="['system:user:add','system:user:edit']"`)
return false
}
}
/**
* 角色权限校验
* @param {Array} value 校验值
* @returns {Boolean}
*/
export function checkRole(value) {
if (value && value instanceof Array && value.length > 0) {
const roles = store.getters && store.getters.roles
const permissionRoles = value
const super_admin = "admin"
const hasRole = roles.some(role => {
return super_admin === role || permissionRoles.includes(role)
})
if (!hasRole) {
return false
}
return true
} else {
console.error(`need roles! Like checkRole="['admin','editor']"`)
return false
}
}
request.js
import store from '@/store'
import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'
import axios from 'axios'
let timeout = 10000
const baseUrl = config.baseUrl
const request = config => {
// 是否需要设置 token
const isToken = (config.headers || {}).isToken === false
config.header = config.header || {}
console.log("--------"+getToken())
if (getToken() && !isToken) {
config.header['Authorization'] = 'Bearer ' + getToken()
}
// get请求映射params参数
if (config.params) {
let url = config.url + '?' + tansParams(config.params)
url = url.slice(0, -1)
config.url = url
}
return new Promise((resolve, reject) => {
uni.request({
method: config.method || 'get',
timeout: config.timeout || timeout,
url: config.baseUrl || baseUrl + config.url,
data: config.data,
header: config.header,
dataType: 'json'
}).then(response => {
let [error, res] = response
if (error) {
toast('后端接口连接异常')
reject('后端接口连接异常')
return
}
const code = res.data.code || 200
const msg = errorCode[code] || res.data.msg || errorCode['default']
if (code === 401) {
showConfirm('登录状态已过期,您可以继续留在该页面,或者重新登录?').then(res => {
if (res.confirm) {
store.dispatch('LogOut').then(res => {
uni.reLaunch({ url: '/pages/login' })
})
}
})
reject('无效的会话,或者会话已过期,请重新登录。')
} else if (code === 500) {
toast(msg)
reject('500')
} else if (code !== 200) {
toast(msg)
reject(code)
}
resolve(res.data)
})
.catch(error => {
let { message } = error
if (message === 'Network Error') {
message = '后端接口连接异常'
} else if (message.includes('timeout')) {
message = '系统接口请求超时'
} else if (message.includes('Request failed with status code')) {
message = '系统接口' + message.substr(message.length - 3) + '异常'
}
toast(message)
reject(error)
})
})
}
export default request
storage.js
import constant from './constant'
// 存储变量名
let storageKey = 'storage_data'
// 存储节点变量名
let storageNodeKeys = [constant.avatar, constant.name, constant.roles, constant.permissions]
const storage = {
set: function(key, value) {
if (storageNodeKeys.indexOf(key) != -1) {
let tmp = uni.getStorageSync(storageKey)
tmp = tmp ? tmp : {}
tmp[key] = value
uni.setStorageSync(storageKey, tmp)
}
},
get: function(key) {
let storageData = uni.getStorageSync(storageKey) || {}
return storageData[key] || ""
},
remove: function(key) {
let storageData = uni.getStorageSync(storageKey) || {}
delete storageData[key]
uni.setStorageSync(storageKey, storageData)
},
clean: function() {
uni.removeStorageSync(storageKey)
}
}
export default storage
upload.js
import store from '@/store'
import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'
let timeout = 10000
const baseUrl = config.baseUrl
const upload = config => {
// 是否需要设置 token
const isToken = (config.headers || {}).isToken === false
config.header = config.header || {}
if (getToken() && !isToken) {
config.header['Authorization'] = 'Bearer ' + getToken()
}
// get请求映射params参数
if (config.params) {
let url = config.url + '?' + tansParams(config.params)
url = url.slice(0, -1)
config.url = url
}
return new Promise((resolve, reject) => {
uni.uploadFile({
timeout: config.timeout || timeout,
url: baseUrl + config.url,
filePath: config.filePath,
name: config.name || 'file',
header: config.header,
formData: config.formData,
success: (res) => {
let result = JSON.parse(res.data)
const code = result.code || 200
const msg = errorCode[code] || result.msg || errorCode['default']
if (code === 200) {
resolve(result)
} else if (code == 401) {
showConfirm("登录状态已过期,您可以继续留在该页面,或者重新登录?").then(res => {
if (res.confirm) {
store.dispatch('LogOut').then(res => {
uni.reLaunch({ url: '/pages/login/login' })
})
}
})
reject('无效的会话,或者会话已过期,请重新登录。')
} else if (code === 500) {
toast(msg)
reject('500')
} else if (code !== 200) {
toast(msg)
reject(code)
}
},
fail: (error) => {
let { message } = error
if (message == 'Network Error') {
message = '后端接口连接异常'
} else if (message.includes('timeout')) {
message = '系统接口请求超时'
} else if (message.includes('Request failed with status code')) {
message = '系统接口' + message.substr(message.length - 3) + '异常'
}
toast(message)
reject(error)
}
})
})
}
export default upload
后端:
传入URL:
http://localhost:8080/captchaImage
验证码操作处理(CaptchaController):
生成验证码的Controller,可以生成数字计算或者字符验证类型的验证码。生成的验证码被存储在Redis缓存中,并返回一个包含验证码图片Base64编码和验证码uuid的AjaxResult对象。
package com.muyuan.web.controller.common;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.muyuan.common.constant.Constants;
import com.muyuan.common.core.domain.AjaxResult;
import com.muyuan.common.core.redis.RedisCache;
import com.muyuan.common.utils.sign.Base64;
import com.muyuan.common.utils.uuid.IdUtils;
/**
* 验证码操作处理
*/
//@Api("验证码")
@RestController
public class CaptchaController {
@Resource(name = "captchaProducer")
private Producer captchaProducer;
@Resource(name = "captchaProducerMath")
private Producer captchaProducerMath;
@Autowired
private RedisCache redisCache;
// 验证码类型
@Value("${muyuan.captchaType}")
private String captchaType;
/**
* 生成验证码
*/
//@ApiOperation("生成验证码")
@GetMapping("/captchaImage")
public AjaxResult getCode(HttpServletResponse response) throws IOException
{
// 1.保存验证码信息
//1.1 生成简单的uuid(详细看文章ID生成工具)
String uuid = IdUtils.simpleUUID();
//1.2Constants.CAPTCHA_CODE_KEY就是拼接一个前缀信息("captcha_codes:")
// 确保唯一性(确定每个人独自的验证码)
String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
//1.3以下滞空
String capStr = null, code = null;
BufferedImage image = null;
// 2.生成验证码(两种方式计算验证码和字母验证码)
//2.1由captchaType控制在application.yml中定义:
//2.1.1 # 验证码类型 math 数组计算 char 字符验证
//2.1.2captchaType: math
if ("math".equals(captchaType))
{
//2.2.1用captchaProducerMath计算公式创建了一个文本 例如:1+1=@2
String capText = captchaProducerMath.createText();
//2.2.2字符串撕裂为 1+1= 这一部分
capStr = capText.substring(0, capText.lastIndexOf("@"));
//2.2.3字符串撕裂为 2 这一部分
code = capText.substring(capText.lastIndexOf("@") + 1);
//2.2.4创建了一个照片流
image = captchaProducerMath.createImage(capStr);
}
else if ("char".equals(captchaType))
{
//2.3.1用captchaProducerMath计算公式创建了一个文本
capStr = code = captchaProducer.createText();
//2.3.2创建了一个照片流
image = captchaProducer.createImage(capStr);
}
//redis存储(详见文章spring redis的工具类)
//TimeUnit.MINUTES为有效时间
redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
// 转换流信息写出
FastByteArrayOutputStream os = new FastByteArrayOutputStream();
try
{
//照片流转成jpg格式名为os
ImageIO.write(image, "jpg", os);
}
catch (IOException e)
{
return AjaxResult.error(e.getMessage());
}
//操作消息提醒(详见文章封装消息提醒)
AjaxResult ajax = AjaxResult.success();
ajax.put("uuid", uuid);
//将os进行Base64编码的操作提高兼容性
ajax.put("img", Base64.encode(os.toByteArray()));
return ajax;
}
}
接口 URL:
http://localhost:8080/login
登录的操作处理(LoginController):
/**
* 登录方法
*
* @param loginBody 登录信息
* @return 结果
*/
@PostMapping("/login")
public AjaxResult login(@RequestBody LoginBody loginBody) {
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
loginBody.getUuid());
ajax.put(Constants.TOKEN, token);
return ajax;
}
登录的操作处理(LoginService):
- 参数:用户名(username)、密码(password)、验证码(code)、验证码唯一标识(uuid)。
- 首先根据uuid拼接出验证码在Redis缓存中的键名(verifyKey)。
- 从Redis缓存中获取该键名对应的验证码(captcha)。
- 删除Redis缓存中的该键名。
- 如果验证码为null,说明验证码已过期,抛出CaptchaExpireException异常。
- 如果验证码不匹配,抛出CaptchaException异常。
- 调用authenticationManager的authenticate方法进行用户验证,传入用户名和密码。
- 如果验证失败,根据异常类型进行相应处理:
- 记录登录日志,包括用户名、登录结果(成功或失败)、相关消息。
- 获取验证通过的用户对象(LoginUser)。
- 调用tokenService的createToken方法生成token并返回。
package com.muyuan.framework.web.service;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.muyuan.common.constant.Constants;
import com.muyuan.common.core.domain.model.LoginUser;
import com.muyuan.common.core.redis.RedisCache;
import com.muyuan.common.exception.CustomException;
import com.muyuan.common.exception.user.CaptchaException;
import com.muyuan.common.exception.user.CaptchaExpireException;
import com.muyuan.common.exception.user.UserPasswordNotMatchException;
import com.muyuan.common.utils.MessageUtils;
import com.muyuan.framework.manager.AsyncManager;
import com.muyuan.framework.manager.factory.AsyncFactory;
/**
* 登录校验方法
*
*
*/
@Component
public class SysLoginService {
@Autowired
private TokenService tokenService;
@Resource
private AuthenticationManager authenticationManager;
@Autowired
private RedisCache redisCache;
/**
* 登录验证
*
* @param username 用户名
* @param password 密码
* @param code 验证码
* @param uuid 唯一标识
* @return 结果
*/
public String login(String username, String password, String code, String uuid) {
//前端获取的进行拼接verifyKey
String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
//从redisCache存储中获得verifyKey
String captcha = redisCache.getCacheObject(verifyKey);
//清除verifyKey缓存
redisCache.deleteObject(verifyKey);
if (captcha == null)
{
//记录日志(详见文章日志记录)
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
throw new CaptchaExpireException();
}
if (!code.equalsIgnoreCase(captcha))
{
//记录日志(详见文章日志记录)
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
throw new CaptchaException();
}
// 用户验证
Authentication authentication = null;
try {
/**
*获取用户对象的时候,会去调用下面的这个方法查询用户对象
* UserDetailsServiceImpl.loadUserByUsername
*/
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
System.out.println("username "+username+" -----password "+password);
authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(username, password));
}catch (Exception e) {
e.printStackTrace();
if (e instanceof BadCredentialsException) {
//记录日志(详见文章日志记录)
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException();
}else {
//记录日志(详见文章日志记录)
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
throw new CustomException(e.getMessage());
}
}
//记录日志(详见文章日志记录)
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
// 生成token(详见文章Token验证处理)
return tokenService.createToken(loginUser);
}
}
原文地址:https://blog.csdn.net/A2029292473/article/details/134739723
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_44112.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。