Browse Source

优化登录

master
Gao xiaosong 5 years ago
parent
commit
0f344a4d7e
  1. 6
      libs/login.js
  2. 21
      pages/Loading/index.vue
  3. 351
      pages/authorization/index.vue
  4. 186
      utils/index.js

6
libs/login.js

@ -4,11 +4,11 @@ import cookie from "@/utils/store/cookie";
import { import {
isWeixin, isWeixin,
login, login,
replaceLogin,
getCurrentPageUrl, getCurrentPageUrl,
getCurrentPageUrlWithArgs, getCurrentPageUrlWithArgs,
parseQuery, parseQuery,
replace, replace,
routerPermissions,
handleQrCode handleQrCode
} from "@/utils"; } from "@/utils";
@ -41,11 +41,11 @@ export default function toLogin(push, backUrl) {
}) })
} else { } else {
console.log('是扫描的砍价海报进来的,但是没有获取到参数') console.log('是扫描的砍价海报进来的,但是没有获取到参数')
replaceLogin() routerPermissions()
} }
} else { } else {
console.log('无特殊情况,重新登录') console.log('无特殊情况,重新登录')
replaceLogin() routerPermissions()
} }
store.commit("UPDATE_AUTHORIZATION", false); store.commit("UPDATE_AUTHORIZATION", false);
store.commit("UPDATE_AUTHORIZATIONPAGE", true); store.commit("UPDATE_AUTHORIZATIONPAGE", true);

21
pages/Loading/index.vue

@ -43,22 +43,23 @@ export default {
} }
cookie.get("spread"); cookie.get("spread");
// this.toLaunch(); // this.toLaunch();
if (this.$deviceType == 'app') { if (this.$deviceType == "app") {
// this.toLaunch(); // this.toLaunch();
this.$yrouter.switchTab({ this.$yrouter.switchTab({
path: '/pages/home/index', path: "/pages/home/index"
}); });
return return;
} }
login({ login().finally(() => {
fail: () => { this.$yrouter.switchTab({
this.toLaunch(); path: "/pages/home/index"
} });
}); });
}, },
methods: { methods: {
...mapActions(["changeAuthorization", "setUserInfo"]), ...mapActions(["changeAuthorization", "setUserInfo"]),
toLaunch() { toLaunch() {
console.log("loading home");
this.changeAuthorization(false); this.changeAuthorization(false);
this.$yrouter.switchTab({ this.$yrouter.switchTab({
path: "/pages/home/index" path: "/pages/home/index"

351
pages/authorization/index.vue

@ -1,211 +1,218 @@
<template> <template>
<view class="container"> <view class="container">
<view v-if="!token"> <view v-if="!token">
<!-- 小程序 --> <!-- 小程序 -->
<view v-if="$deviceType == 'routine'"> <view v-if="$deviceType == 'routine'">
<view class="getUserInfo"> <view class="getUserInfo">
<text>您还未允许微信登录授权请点击下方按钮允许微信授权登录</text> <text>您还未允许微信登录授权请点击下方按钮允许微信授权登录</text>
<button type="primary" open-type="getUserInfo" @getuserinfo="getUserInfo">允许微信登录授权</button> <button type="primary" open-type="getUserInfo" @getuserinfo="getUserInfo">允许微信登录授权</button>
<view style="height:20rpx"></view> <view style="height:20rpx"></view>
<button @click="back">取消微信登录授权</button> <button @click="back">取消微信登录授权</button>
</view> </view>
</view> </view>
<!-- app --> <!-- app -->
<view v-if="$deviceType == 'app'"> <view v-if="$deviceType == 'app'">
<view class="getUserInfo"> <view class="getUserInfo">
<text>请先登录</text> <text>请先登录</text>
<button type="primary" @click="this.toLogin">去登录</button> <button type="primary" @click="this.toLogin">去登录</button>
</view> </view>
</view> </view>
</view> </view>
</view> </view>
</template> </template>
<script> <script>
import { mapState, mapMutations, mapActions } from 'vuex'; import { mapState, mapMutations, mapActions } from "vuex";
// //
// import request from "@//api/request"; // import request from "@//api/request";
import { wxappAuth, getUser } from '@/api/user'; import { wxappAuth, getUser } from "@/api/user";
import dayjs from 'dayjs'; import dayjs from "dayjs";
import cookie from '@/utils/store/cookie'; import cookie from "@/utils/store/cookie";
import { login } from '@/utils'; import { login } from "@/utils";
export default { export default {
data() { data() {
return { return {};
}; },
}, computed: {
computed: { ...mapState(["isAuthorization", "$deviceType", "token"])
...mapState(['isAuthorization','$deviceType','token']) },
}, onShow() {
onShow() { this.UPDATE_AUTHORIZATIONPAGE(true);
this.UPDATE_AUTHORIZATIONPAGE(true); },
}, onHide() {
onHide() { this.UPDATE_AUTHORIZATIONPAGE(false);
this.UPDATE_AUTHORIZATIONPAGE(false); this.changeAuthorization(false);
this.changeAuthorization(false); },
}, onUnload() {
onUnload() { this.UPDATE_AUTHORIZATIONPAGE(false);
this.UPDATE_AUTHORIZATIONPAGE(false); this.changeAuthorization(false);
this.changeAuthorization(false); },
}, methods: {
methods: { ...mapActions(["changeAuthorization", "setUserInfo"]),
...mapActions(['changeAuthorization', 'setUserInfo']), ...mapMutations(["UPDATE_AUTHORIZATIONPAGE", "CHANGE_TABTAR"]),
...mapMutations(['UPDATE_AUTHORIZATIONPAGE', 'CHANGE_TABTAR']), back() {
back() { this.$yrouter.switchTab({
this.$yrouter.switchTab({ path: "/pages/home/index",
path: '/pages/home/index', query: {}
query: {} });
}); },
}, getUserInfo(data) {
getUserInfo(data) { if (data.detail.errMsg == "getUserInfo:fail auth deny") {
if (data.detail.errMsg == 'getUserInfo:fail auth deny') { uni.showToast({
uni.showToast({ title: "取消授权",
title: '取消授权', icon: "none",
icon: 'none', duration: 2000
duration: 2000 });
}); return;
return; }
} uni.showLoading({
uni.showLoading({ title: "登录中"
title: '登录中' });
}); login()
login({ .then(res => {
success: () => {} this.$yrouter.replace({ path: cookie.get("redirect") });
}); })
}, .catch(error => {
toLogin() { console.log(error);
this.$yrouter.push({ uni.showToast({
path: '/pages/user/Login/index', title: "登录失败",
query: {} icon: "none",
}); duration: 2000
} });
}, });
onUnload() {}, },
mounted() { toLogin() {
} this.$yrouter.push({
path: "/pages/user/Login/index",
query: {}
});
}
},
onUnload() {},
mounted() {}
}; };
</script> </script>
<style lang="less"> <style lang="less">
.sp-cell { .sp-cell {
height: 20rpx; height: 20rpx;
} }
.getUserInfo { .getUserInfo {
display: flex; display: flex;
align-items: center; align-items: center;
flex-direction: column; flex-direction: column;
padding: 30px; padding: 30px;
text { text {
font-size: 30rpx; font-size: 30rpx;
text-align: center; text-align: center;
margin-bottom: 20px; margin-bottom: 20px;
} }
} }
.container { .container {
flex: 1; flex: 1;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
justify-content: flex-start; justify-content: flex-start;
position: relative; position: relative;
} }
.tab-bar { .tab-bar {
font-size: 0; font-size: 0;
display: flex; display: flex;
align-items: center; align-items: center;
background: rgba(255, 255, 255, 0.9); background: rgba(255, 255, 255, 0.9);
position: fixed; position: fixed;
bottom: 0; bottom: 0;
left: 0; left: 0;
right: 0; right: 0;
z-index: 99; z-index: 99;
border-top: 1px solid rgba(248, 248, 248, 1); border-top: 1px solid rgba(248, 248, 248, 1);
.tab-bar-item { .tab-bar-item {
flex: 1; flex: 1;
height: 49px; height: 49px;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
flex-direction: column; flex-direction: column;
&.active { &.active {
text { text {
color: #ee7559; color: #ee7559;
} }
.tab-bar-pic { .tab-bar-pic {
display: none; display: none;
background: #f9f9f9; background: #f9f9f9;
&.active { &.active {
display: block; display: block;
} }
} }
} }
.tab-bar-pic { .tab-bar-pic {
display: block; display: block;
background: #f9f9f9; background: #f9f9f9;
&.active { &.active {
display: none; display: none;
} }
} }
} }
.tab-bar-pic { .tab-bar-pic {
width: 25px; width: 25px;
height: 25px; height: 25px;
background: #f9f9f9; background: #f9f9f9;
image { image {
width: 25px; width: 25px;
height: 25px; height: 25px;
} }
} }
.tab-bar-pic-active { .tab-bar-pic-active {
} }
text { text {
font-size: 10px; font-size: 10px;
color: rgb(160, 160, 160); color: rgb(160, 160, 160);
line-height: 10px; line-height: 10px;
margin-top: 5px; margin-top: 5px;
} }
} }
.tab-bar-bg { .tab-bar-bg {
padding-top: 46px; padding-top: 46px;
width: 100%; width: 100%;
} }
.view-item { .view-item {
display: none; display: none;
width: 100%; width: 100%;
} }
.view-item-active { .view-item-active {
display: block; display: block;
} }
.getUserInfo { .getUserInfo {
display: flex; display: flex;
align-items: center; align-items: center;
flex-direction: column; flex-direction: column;
padding: 30px; padding: 30px;
p { p {
margin-bottom: 20px; margin-bottom: 20px;
} }
} }
._van-dialog { ._van-dialog {
z-index: 99999999999; z-index: 99999999999;
} }
</style> </style>

186
utils/index.js

@ -109,46 +109,6 @@ export const copyClipboard = (data) => {
}) })
} }
export const replaceLogin = (msg) => {
uni.hideLoading();
console.log('尝试开始重新登录')
uni.showToast({
title: '重新登录中...',
icon: 'none',
duration: 2000
});
// 这里代表已经失去登录状态以及401强制推出登录了
store.commit('LOGOUT')
if (Vue.prototype.$deviceType == 'routine') {
console.log('当前是微信小程序,开始调用登录方法')
// 如果是微信小程序,跳转到授权页
login({
fail: () => {
console.log('自动登录失败,重定向授权页面')
reLaunch({
path: '/pages/authorization/index',
query: {
redirect: `/${getCurrentPageUrl()}`,
...parseQuery()
}
})
}
})
} else {
// 如果不是小程序跳转到登录页
console.log('当前是app,跳转到登录页面')
push({
path: '/pages/user/Login/index',
query: {
redirect: `/${getCurrentPageUrl()}`,
...parseQuery()
}
})
}
}
export const getProvider = (service) => { export const getProvider = (service) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// 获取当前环境的服务商 // 获取当前环境的服务商
@ -172,27 +132,26 @@ export const getProvider = (service) => {
export const authorize = (authorizeStr) => { export const authorize = (authorizeStr) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
console.log('检验授权')
uni.authorize({ uni.authorize({
scope: `scope.${authorizeStr}`, scope: `scope.${authorizeStr}`,
success() { success() {
console.log('检验授权____授权成功')
resolve('获取授权成功') resolve('获取授权成功')
}, },
fail() { fail() {
console.log('检验授权____授权失败')
console.log('授权失败跳转首页') // switchTab({
switchTab({ // path: '/pages/home/index',
path: '/pages/home/index', // // query
// query // });
});
reject('获取授权失败') reject('获取授权失败')
} }
}) })
}).catch(error => {
console.log(error)
}) })
} }
export const login = (option) => { export const login = () => {
console.log('开始登录 ————————————————————') console.log('开始登录 ————————————————————')
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
console.log('获取环境商') console.log('获取环境商')
@ -215,62 +174,48 @@ export const login = (option) => {
success: function (user) { success: function (user) {
console.log('获取用户信息成功') console.log('获取用户信息成功')
console.log('开始调用登录接口') console.log('开始调用登录接口')
if (Vue.prototype.$deviceType == 'routine') { wxappAuth({
wxappAuth({ encryptedData: user.encryptedData,
encryptedData: user.encryptedData, iv: user.iv,
iv: user.iv, code: code,
code: code, spread: cookie.get("spread")
spread: cookie.get("spread") }).then(({ data }) => {
}).then(({ console.log('登录接口调用成功')
data console.log('开始处理登录信息保存,并获取用户详情')
}) => { uni.hideLoading();
console.log('登录接口调用成功') store.commit("LOGIN", data.token, dayjs(data.expires_time));
console.log('开始处理登录信息保存,并获取用户详情') store.dispatch('USERINFO', true)
resolve(data) getUser().then(user => {
uni.hideLoading(); console.log('获取用户信息成功')
store.commit("LOGIN", data.token, dayjs(data.expires_time)); store.dispatch('setUserInfo', user.data)
store.dispatch('USERINFO', true) resolve(user)
console.log(store)
handleGetUserInfo()
}).catch(error => { }).catch(error => {
console.log('登录接口调用失败') console.log('获取用户信息失败')
reject() reject('获取用户信息失败')
console.log(error)
handleFail(option, '微信登录失败')
}); });
} }).catch(error => {
console.log('登录接口调用失败')
reject('登录接口调用失败')
});
}, },
fail() { fail() {
console.log('获取用户信息失败') console.log('获取用户信息失败')
// 获取用户信息失败 reject('获取用户信息失败')
reject()
handleFail(option, '获取用户信息失败')
} }
}); });
}).catch(error => { }).catch(error => {
console.log('用户未授权') console.log('用户未授权')
reject() reject('用户未授权')
console.log(error)
handleFail(option, '用户未授权')
}) })
}, },
fail() { fail() {
console.log('调用登录接口失败') console.log('调用登录接口失败')
// 调用登录接口失败 reject('调用登录接口失败')
reject()
handleFail(option, '登录失败')
} }
}); });
}).catch(error => { }).catch(error => {
handleFail(option, '获取环境服务商失败') reject('获取环境服务商失败')
reject()
console.log(error)
handleFail(option, '获取环境服务商失败')
}) })
}).catch(error => {
handleFail(option, '登录失败')
console.log(error)
handleFail(option, '登录失败')
}) })
} }
@ -343,18 +288,13 @@ export const handleGetUserInfo = () => {
}) })
} }
const handleFail = (option, msg) => {
// 此处是处理登录失效的问题的
option && option.fail ? option.fail() : replaceLogin('登录失败,请重新登录')
}
export function parseUrl(location) { export function parseUrl(location) {
if (typeof location === 'string') return location if (typeof location === 'string') return location
const { const {
path, path,
query query
} = location } = location
const queryStr = stringify(query) const queryStr = stringify(query)
if (!queryStr) { if (!queryStr) {
@ -419,6 +359,8 @@ export const handleLoginStatus = (location, complete, fail, success) => {
// 是否可以访问 // 是否可以访问
let isAuth = false let isAuth = false
console.log('即将跳转', location, parseUrl(location))
// 从 location 中获取当前url,location typeof string || object // 从 location 中获取当前url,location typeof string || object
let path = '' let path = ''
if (typeof location === 'string') { if (typeof location === 'string') {
@ -427,6 +369,7 @@ export const handleLoginStatus = (location, complete, fail, success) => {
path = location.path path = location.path
} }
// 判断用户是否有token
if (!auth()) { if (!auth()) {
page.map((item) => { page.map((item) => {
if (item.path == path) { if (item.path == path) {
@ -439,7 +382,7 @@ export const handleLoginStatus = (location, complete, fail, success) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (isAuth) { if (isAuth) {
// 登录了有权限 // 有token
resolve({ resolve({
url: parseUrl(location), url: parseUrl(location),
complete, complete,
@ -447,8 +390,8 @@ export const handleLoginStatus = (location, complete, fail, success) => {
success success
}) })
} else { } else {
// 未登录没有权限 // 没有token,先校验用户是否授权,如果授权了,进行自动登录
replaceLogin() routerPermissions(parseUrl(location))
reject() reject()
} }
}).catch(error => { }).catch(error => {
@ -456,6 +399,55 @@ export const handleLoginStatus = (location, complete, fail, success) => {
}) })
} }
// export function checkPermissions(){
// }
export function routerPermissions(url) {
let path = url
if (!path) {
path = getCurrentPageUrlWithArgs()
}
if (Vue.prototype.$deviceType == 'routine') {
console.log('当前是微信小程序,开始处理小程序登录方法')
// 如果是微信小程序,跳转到授权页
// 先校验用户是否授权,如果授权了,进行自动登录
authorize('userInfo').then(() => {
// 自动登录
login().then(res => {
// 登录成功,跳转到需要跳转的页面
push({
path,
})
}).catch(error => {
uni.showToast({
title: error,
icon: "none",
duration: 2000
});
reLaunch({
path: '/pages/authorization/index',
})
cookie.set('redirect', path)
})
}).catch(error => {
// 跳转到登录页面或者授权页面
reLaunch({
path: '/pages/authorization/index',
})
cookie.set('redirect', path)
})
} else {
// 如果不是小程序跳转到登录页
console.log('当前是app,开始处理app登录方法')
push({
path: '/pages/user/Login/index',
})
cookie.set('redirect', path)
}
}
export function push(location, complete, fail, success) { export function push(location, complete, fail, success) {
handleLoginStatus(location, complete, fail, success).then(params => { handleLoginStatus(location, complete, fail, success).then(params => {
uni.navigateTo(params) uni.navigateTo(params)

Loading…
Cancel
Save