Commit 41a1c839 authored by 刘文虎's avatar 刘文虎

重新定义token机制

parent 93077745
;(function() {
let NODE_ENV = 'prod' // dev:开发环境 | test:测试环境 | prod:生产环境
let NODE_ENV = 'test' // dev:开发环境 | test:测试环境 | prod:生产环境
let ENV_VAR = null
let VERSION = 'v1.0.0'
if (process.env.NODE_ENV === 'development') {
......
......@@ -15,3 +15,13 @@ export function sendCode(data) {
data
})
}
export function update(data) {
return request({
url: `/rest/user`,
method: 'POST',
data
})
}
\ No newline at end of file
......@@ -214,7 +214,7 @@
"path" : "update-log/update-log",
"style" :
{
"navigationBarTitleText": "",
"navigationBarTitleText": "更新日志",
"enablePullDownRefresh": false
}
......@@ -245,7 +245,14 @@
"enablePullDownRefresh": false
}
}
},
{
"path": "u-avatar-cropper/u-avatar-cropper",
"style": {
"navigationBarTitleText": "头像裁剪",
"navigationBarBackgroundColor": "#000000"
}
}
]
},
{
......
<template>
<view class="user-header">
<view class="user-profile">
<image :src="userInfo.avatar_l" mode="" v-if="userInfo.avatar_l"></image>
<view class="user-profile" @click="toUserSetting">
<image :src="userInfo.avatar" mode="" v-if="userInfo.avatar"></image>
<image :src="avatar" v-else></image>
</view>
<view class="user-info" @click="toLogin">
......@@ -32,6 +32,7 @@
</template>
<script>
import {mineBaseUrl} from "@/utils/config.js"
import { mapGetters } from 'vuex';
export default {
props: {
......@@ -44,21 +45,20 @@ export default {
}
},
data() {
return {};
return {
mineBaseUrl,
};
},
computed: {
...mapGetters(['userInfo']),
baseUrl() {
return process.uniEnv.qn_base_url + 'mine/';
},
avatar() {
return this.baseUrl + 'toxuiang@3x.png';
return this.mineBaseUrl + 'toxuiang@3x.png';
},
isVip() {
return this.baseUrl + 'shihuiyuan@3x.png';
return this.mineBaseUrl + 'shihuiyuan@3x.png';
},
notVip() {
return this.baseUrl + 'bushihuiyuan@3x.png';
return this.mineBaseUrl + 'bushihuiyuan@3x.png';
}
},
methods: {
......@@ -69,6 +69,13 @@ export default {
});
}
},
toUserSetting(){
if (this.userInfo.id) {
uni.navigateTo({
url: '/pages/mine/user-setting/user-setting'
});
}
},
toPay(){
uni.navigateTo({
url:'/pages/mine/pay/pay'
......
......@@ -102,6 +102,14 @@ export default {
maxlength: 4,
height: 240
};
case 'user-nickname':
return {
title: '用户昵称',
type: 'textarea',
placeholder: '请输入用户昵称(10个字以内)',
maxlength: 10,
height: 240
};
case 'menu-introduce':
return {
title: '频道介绍',
......
<template>
<view class="content">
<view class="cropper-wrapper" :style="{ height: cropperOpt.height + 'px' }">
<canvas
class="cropper"
:disable-scroll="true"
@touchstart="touchStart"
@touchmove="touchMove"
@touchend="touchEnd"
:style="{ width: cropperOpt.width, height: cropperOpt.height, backgroundColor: 'rgba(0, 0, 0, 0.8)' }"
canvas-id="cropper"
id="cropper"
></canvas>
<canvas
class="cropper"
:disable-scroll="true"
:style="{
position: 'fixed',
top: `-${cropperOpt.width * cropperOpt.pixelRatio}px`,
left: `-${cropperOpt.height * cropperOpt.pixelRatio}px`,
width: `${cropperOpt.width * cropperOpt.pixelRatio}px`,
height: `${cropperOpt.height * cropperOpt.pixelRatio}`
}"
canvas-id="targetId"
id="targetId"
></canvas>
</view>
<view class="cropper-buttons safe-area-padding" :style="{ height: bottomNavHeight + 'px' }">
<!-- #ifdef H5 -->
<view class="upload" @tap="uploadTap">选择图片</view>
<!-- #endif -->
<!-- #ifndef H5 -->
<view class="upload" @tap="uploadTap">重新选择</view>
<!-- #endif -->
<view class="getCropperImage" @tap="getCropperImage(false)">确定</view>
</view>
</view>
</template>
<script>
import WeCropper from './weCropper.js';
export default {
props: {
// 裁剪矩形框的样式,其中可包含的属性为lineWidth-边框宽度(单位rpx),color: 边框颜色,
// mask-遮罩颜色,一般设置为一个rgba的透明度,如"rgba(0, 0, 0, 0.35)"
boundStyle: {
type: Object,
default() {
return {
lineWidth: 4,
borderColor: 'rgb(245, 245, 245)',
mask: 'rgba(0, 0, 0, 0.35)'
};
}
}
// // 裁剪框宽度,单位rpx
// rectWidth: {
// type: [String, Number],
// default: 400
// },
// // 裁剪框高度,单位rpx
// rectHeight: {
// type: [String, Number],
// default: 400
// },
// // 输出图片宽度,单位rpx
// destWidth: {
// type: [String, Number],
// default: 400
// },
// // 输出图片高度,单位rpx
// destHeight: {
// type: [String, Number],
// default: 400
// },
// // 输出的图片类型,如果发现裁剪的图片很大,可能是因为设置为了"png",改成"jpg"即可
// fileType: {
// type: String,
// default: 'jpg',
// },
// // 生成的图片质量
// // H5上无效,目前不考虑使用此参数
// quality: {
// type: [Number, String],
// default: 1
// }
},
data() {
return {
// 底部导航的高度
bottomNavHeight: 50,
originWidth: 200,
width: 0,
height: 0,
cropperOpt: {
id: 'cropper',
targetId: 'targetCropper',
pixelRatio: 1,
width: 0,
height: 0,
scale: 2.5,
zoom: 8,
cut: {
x: (this.width - this.originWidth) / 2,
y: (this.height - this.originWidth) / 2,
width: this.originWidth,
height: this.originWidth
},
boundStyle: {
lineWidth: uni.upx2px(this.boundStyle.lineWidth),
mask: this.boundStyle.mask,
color: this.boundStyle.borderColor
}
},
// 裁剪框和输出图片的尺寸,高度默认等于宽度
// 输出图片宽度,单位px
destWidth: 200,
// 裁剪框宽度,单位px
rectWidth: 200,
// 输出的图片类型,如果'png'类型发现裁剪的图片太大,改成"jpg"即可
fileType: 'jpg',
src: '', // 选择的图片路径,用于在点击确定时,判断是否选择了图片
};
},
onLoad(option) {
let rectInfo = uni.getSystemInfoSync();
this.width = rectInfo.windowWidth;
this.height = rectInfo.windowHeight - this.bottomNavHeight;
this.cropperOpt.width = this.width;
this.cropperOpt.height = this.height;
this.cropperOpt.pixelRatio = rectInfo.pixelRatio;
if (option.destWidth) this.destWidth = option.destWidth;
if (option.rectWidth) {
let rectWidth = Number(option.rectWidth);
this.cropperOpt.cut = {
x: (this.width - rectWidth) / 2,
y: (this.height - rectWidth) / 2,
width: rectWidth,
height: rectWidth
};
}
this.rectWidth = option.rectWidth;
if (option.fileType) this.fileType = option.fileType;
// 初始化
this.cropper = new WeCropper(this.cropperOpt)
.on('ready', ctx => {
// wecropper is ready for work!
})
.on('beforeImageLoad', ctx => {
// before picture loaded, i can do something
})
.on('imageLoad', ctx => {
// picture loaded
})
.on('beforeDraw', (ctx, instance) => {
// before canvas draw,i can do something
});
// 设置导航栏样式,以免用户在page.json中没有设置为黑色背景
uni.setNavigationBarColor({
frontColor: '#ffffff',
backgroundColor: '#000000'
});
uni.chooseImage({
count: 1, // 默认9
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: res => {
this.src = res.tempFilePaths[0];
// 获取裁剪图片资源后,给data添加src属性及其值
this.cropper.pushOrign(this.src);
}
});
},
methods: {
touchStart(e) {
this.cropper.touchStart(e);
},
touchMove(e) {
this.cropper.touchMove(e);
},
touchEnd(e) {
this.cropper.touchEnd(e);
},
getCropperImage(isPre = false) {
if(!this.src) return this.$u.toast('请先选择图片再裁剪');
let cropper_opt = {
destHeight: Number(this.destWidth), // uni.canvasToTempFilePath要求这些参数为数值
destWidth: Number(this.destWidth),
fileType: this.fileType
};
this.cropper.getCropperImage(cropper_opt, (path, err) => {
if (err) {
uni.showModal({
title: '温馨提示',
content: err.message
});
} else {
if (isPre) {
uni.previewImage({
current: '', // 当前显示图片的 http 链接
urls: [path] // 需要预览的图片 http 链接列表
});
} else {
uni.$emit('uAvatarCropper', path);
this.$u.route({
type: 'back'
});
}
}
});
},
uploadTap() {
const self = this;
uni.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: (res) => {
self.src = res.tempFilePaths[0];
// 获取裁剪图片资源后,给data添加src属性及其值
self.cropper.pushOrign(this.src);
}
});
}
}
};
</script>
<style scoped lang="scss">
@import '@/node_modules/uview-ui/libs/css/style.components.scss';
.content {
background: rgba(255, 255, 255, 1);
}
.cropper {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 11;
}
.cropper-buttons {
background-color: #000000;
color: #eee;
}
.cropper-wrapper {
position: relative;
@include vue-flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
width: 100%;
background-color: #000;
}
.cropper-buttons {
width: 100vw;
@include vue-flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
position: fixed;
bottom: 0;
left: 0;
font-size: 28rpx;
}
.cropper-buttons .upload,
.cropper-buttons .getCropperImage {
width: 50%;
text-align: center;
}
.cropper-buttons .upload {
text-align: left;
padding-left: 50rpx;
}
.cropper-buttons .getCropperImage {
text-align: right;
padding-right: 50rpx;
}
</style>
This diff is collapsed.
This diff is collapsed.
import {
checkToken,
getToken,
getUserinfo,
checkCodeTimetamp,
showToast
......@@ -28,7 +28,7 @@ const router = createRouter({
let index=whiteList.findIndex(item=>item===path)
// 鉴权
console.log("需要鉴权")
if(checkToken()){
if(getToken()){
next()
}else {
// next()
......
import {
setToken,
setRefreshToken,
setUserinfo,
getUserinfo,
removeToken,
......@@ -178,10 +179,13 @@ const actions = {
authType: info.authType
})
let {
token
token,
refreshToken
} = res.data
setTimetamp()
let timestamp=res.timestamp
console.log("timestamp===",new Date(res.timestamp))
setToken(token)
setRefreshToken(refreshToken)
dispatch("Set_auto_login",true)
await dispatch('Get_UserInfo')
resolve(res)
......@@ -217,10 +221,12 @@ const actions = {
// 退出系统
LogOut({
commit,
state
state,
dispatch
}) {
removeToken()
removeUserinfo()
dispatch("Set_auto_login",false)
commit("SET_USERINFO",{})
removeTimetamp()
},
......
......@@ -20,6 +20,20 @@ export function removeToken() {
removeUserinfo()
}
export function setRefreshToken(data) {
uni.setStorageSync("REFRESH-TOKEN", data);
}
export function getRefreshToken() {
return uni.getStorageSync("REFRESH-TOKEN") || ""
}
export function removeRefreshToken() {
uni.removeStorageSync("REFRESH-TOKEN");
removeTimetamp()
removeUserinfo()
}
export function setTimetamp(date) {
let time = new Date().getTime()
if (date) {
......@@ -203,12 +217,13 @@ export function checkAdminToken() {
export function checkCodeTimetamp() {
let time = new Date().getTime()
let backTime = getCodeTimetamp()
let backTime = getTimetamp()
if (backTime) {
if (time - backTime <= 8 * 60 * 60 * 1000) {
// if (time - backTime <= 23*60*60* 1000) {
if (time - backTime <= 10* 1000) {
return true;
} else {
removeCodeTimetamp()
// removeTimetamp()
return false;
}
......
......@@ -68,7 +68,7 @@ function request({
responseType,
success: res => {
// 重置时间戳
setTimetamp()
// setTimetamp()
if (res.data.code === 0) {
if (!noLoading) {
......
......@@ -8,17 +8,95 @@ import {
setToken,
getToken,
removeToken,
getRefreshToken,
setRefreshToken,
checkToken,
getUserinfo,
removeUserinfo,
setTimetamp,
getTimetamp,
removeTimetamp,
checkCodeTimetamp,
showToast
} from "./common.js"
import store from "@/store/index.js"
const globalUrl = process.uniEnv || {}
let apiUrl = globalUrl.apiUrl
// ====响应拦截====
// 存储 request 创建后的实例,刷新token时,将后续可能发生的请求储存下来
let subscribers = [];
// 正在刷新token锁
let isRefreshing = true;
// 刷新锁
let refreshLock = false
// 防抖
let stabilization = true
// 存储请求头对象
let requestConfig = {}
// 刷新token结束后执行已保存的其他请求
function onAccessTokenFetched() {
subscribers.forEach((callback, index) => {
console.log("onAccessTokenFetched:第" + (index + 1) + "个回调")
callback();
})
subscribers = [];
}
// 存储后续可能发生的请求
function addSubscriber(callback) {
subscribers.push(callback)
}
// 刷新token
function refreshToken(header) {
return request({
// url: `/rest/api/v1/auth/refresh`,
url: `/app/unify/refresh`,
method: 'POST',
header,
noLoading: true
})
}
function refreshTokenRequst() {
console.log("refreshTokenRequst")
let header = {
'R-Authorization': getRefreshToken()
}
refreshToken(header).then((response) => {
console.log(response)
let {
token,
refreshToken
} = response.data
setToken(token)
setRefreshToken(refreshToken)
isRefreshing = true;
onAccessTokenFetched();
}).catch(err => {
console.log("subscribers", subscribers)
console.log("登陆已过期")
console.log(err)
uni.navigateTo({
url: "/pages/login/login",
})
setTimeout(() => {
store.dispatch("LogOut")
isRefreshing = true;
// 刷新锁
refreshLock = false
// 防抖
stabilization = true
subscribers = []
}, 1500)
console.log("准备跳转登录页")
})
}
function request({
url,
......@@ -35,7 +113,7 @@ function request({
header['Content-type'] = header['Content-type'] ? header['Content-type'] : 'application/json;charset=utf-8'
}
let token = getToken()
let requestUrl=""
let requestUrl = ""
// #ifdef H5
if (process.env.NODE_ENV === 'development') {
if (!noBase) {
......@@ -61,14 +139,9 @@ function request({
mask: true
});
}
// ====响应拦截====
// 刷新锁
let refreshLock = false
// 防抖
let stabilization = true
// 存储请求对象
let requestConfig={
requestConfig = {
method,
url,
data,
......@@ -78,6 +151,7 @@ function request({
noBase,
}
return new Promise((resolve, reject) => {
uni.request({
method,
......@@ -88,11 +162,14 @@ function request({
success: res => {
// 重置时间戳
// setTimetamp()
console.log("header",header)
console.log(res)
let resHeader=res.header
let {token,token_expire}=resHeader
if(token&&token_expire){
// console.log("header", header)
// console.log(res)
let resHeader = res.header
let {
token,
token_expire
} = resHeader
if (token && token_expire) {
// setTimetamp(token_expire)
// setToken(token)
}
......@@ -103,10 +180,7 @@ function request({
resolve(res.data)
} else {
uni.hideLoading()
// 白名单内直接返回
if (responseWhiteList.findIndex(item => url.indexOf(item) !== -1) !== -1) {
resolve(res.data)
} else if (res.data.code === 403 || res.data.code === 401) {
if (res.data.code === 403 || res.data.code === 401) {
// if (url.indexOf("customer/logout") !== -1) {
// resolve(res.data)
// } else {
......@@ -116,9 +190,25 @@ function request({
// })
// }
console.log("未登录或者登陆已过期")
console.log(res)
store.dispatch("LogOut")
// console.log(res)
// store.dispatch("LogOut")
reject(res.data)
// uni.navigateTo({
// url: "/pages/login/login",
// })
// setTimeout(() => {
// // store.dispatch("LogOut")
// isRefreshing = true;
// // 刷新锁
// refreshLock = false
// // 防抖
// stabilization = true
// subscribers = []
// }, 1500)
} else if (responseWhiteList.findIndex(item => url.indexOf(item) !== -1) !== -
1) {
// 白名单内直接返回
resolve(res.data)
} else if (res.data.code === 23001) {
reject(res.data)
} else {
......@@ -142,6 +232,31 @@ function request({
}
function request1(config) {
let token = getToken()
if (token) {
console.log("checkCodeTimetamp", checkCodeTimetamp())
console.log("getTimetamp", getTimetamp())
if (getTimetamp() && !checkCodeTimetamp()) {
console.log("isRefreshing", isRefreshing)
if (isRefreshing) {
isRefreshing = false;
refreshTokenRequst()
}
const retryOriginalRequest = new Promise((resolve) => {
addSubscriber(() => {
resolve(request(config))
})
});
return retryOriginalRequest;
} else {
return request(config)
}
} else {
return request(config)
}
}
export default request
export default request1
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment