Commit 57832185 authored by 张圳龙's avatar 张圳龙

dev

parent bbc22da3
......@@ -2,7 +2,7 @@
ENV = 'development'
# base api
VUE_APP_BASE_API = 'http://127.0.0.1:8002'
VUE_APP_BASE_API = 'https://work-order.shangjiadao.com'
# vue-cli uses the VUE_CLI_BABEL_TRANSPILE_MODULES environment variable,
# to control whether the babel-plugin-dynamic-import-node plugin is enabled.
......
......@@ -2,5 +2,4 @@
ENV = 'production'
# base api
VUE_APP_BASE_API = ''
VUE_APP_BASE_API = 'https://work-order.shangjiadao.com'
\ No newline at end of file
......@@ -35,7 +35,7 @@
账号:admin
密码:123456
演示demo登陆需要取消ldap验证,就是登陆页面取消ldap的打勾。
登录页支持本地账号密码登录和飞书扫码登录。
```
文档: [https://www.fdevops.com/docs/ferry](https://www.fdevops.com/docs/ferry-tutorial-document/introduction)
......
......@@ -2,7 +2,7 @@
"name": "ferry_web",
"version": "1.0.0",
"description": "A magical vue admin. An out-of-box UI solution for enterprise applications. Newest development stack of vue. Lots of awesome features",
"author": "lanyulei<fdevops@163.com>",
"author": "",
"license": "LGPL-3.0",
"scripts": {
"dev": "vue-cli-service serve",
......
ignoredBuiltDependencies:
- core-js
- deasync
- ejs
- husky
- yorkie
......@@ -103,11 +103,10 @@ export function updateUserProfile(data) {
}
// 用户密码重置
export function updateUserPwd(oldPassword, newPassword, passwordType) {
export function updateUserPwd(oldPassword, newPassword) {
const data = {
oldPassword,
newPassword,
passwordType
newPassword
}
return request({
url: '/api/v1/user/pwd',
......
......@@ -16,6 +16,15 @@ export function refreshtoken(data) {
})
}
export function feishuLogin(code) {
return request({
url: '/login/feishu',
method: 'post',
data: { code },
timeout: 15000
})
}
export function getInfo() {
return request({
url: '/api/v1/getinfo',
......
......@@ -24,7 +24,7 @@ export default {
}
},
computed: {
...mapGetters(['title', 'logo', 'isLdap'])
...mapGetters(['title', 'logo'])
},
methods: {
getSystemSettings() {
......
module.exports = {
title: 'ferry 管理平台',
logo: 'https://www.fdevops.com/wp-content/uploads/2020/08/1597815294-ferry_logo_white.png',
isLdap: false,
isVerifyCode: true,
/**
......
......@@ -15,7 +15,6 @@ const getters = {
errorLogs: state => state.errorLog.logs,
title: state => state.settings.title,
logo: state => state.settings.logo,
isLdap: state => state.settings.isLdap,
isVerifyCode: state => state.settings.isVerifyCode
}
export default getters
......@@ -2,7 +2,7 @@ import variables from '@/styles/element-variables.scss'
import defaultSettings from '@/settings'
import { getSettings } from '@/api/system/settings'
const { title, logo, isLdap, showSettings, tagsView, fixedHeader, sidebarLogo, isVerifyCode } = defaultSettings
const { title, logo, showSettings, tagsView, fixedHeader, sidebarLogo, isVerifyCode } = defaultSettings
const state = {
theme: variables.theme,
......@@ -12,7 +12,6 @@ const state = {
sidebarLogo: sidebarLogo,
title: title,
logo: logo,
isLdap: isLdap,
isVerifyCode: isVerifyCode
}
......@@ -25,7 +24,6 @@ const mutations = {
CHANGE_SYSTEM_SETTING: (state, content) => {
state.title = content.name
state.logo = content.logo
state.isLdap = content.is_ldap
state.isVerifyCode = content.is_verify_code
}
}
......
import { login, logout, getInfo, refreshtoken } from '@/api/user'
import { login, logout, getInfo, refreshtoken, feishuLogin } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
......@@ -41,6 +41,12 @@ const mutations = {
}
const actions = {
async feishuLogin({ commit }, code) {
const response = await feishuLogin(code)
if (!response || !response.token) throw new Error('飞书登录失败,请重新扫码')
commit('SET_TOKEN', response.token)
setToken(response.token)
},
// user login
login({ commit }, userInfo) {
return new Promise((resolve, reject) => {
......
const SDK_URL = 'https://lf-package-cn.feishucdn.com/obj/feishu-static/lark/passport/qrcode/LarkSSOSDKWebQRCode-1.0.3.js'
const STATE_KEY = 'feishu-login-state'
const CALLBACK_KEYS = ['code', 'state', 'error', 'error_description']
export const FEISHU_REDIRECT_URI = 'https://work-order.shangjiadao.com/#/login'
let sdkPromise
export function loadFeishuSdk() {
if (window.QRLogin) return Promise.resolve(window.QRLogin)
if (sdkPromise) return sdkPromise
sdkPromise = new Promise((resolve, reject) => {
const script = document.createElement('script')
const timer = setTimeout(() => fail(), 15000)
const fail = () => {
clearTimeout(timer)
script.onload = null
script.onerror = null
script.remove()
sdkPromise = null
reject(new Error('飞书登录 SDK 加载失败,请检查网络后重试'))
}
script.src = SDK_URL
script.async = true
script.onerror = fail
script.onload = () => {
if (!window.QRLogin) return fail()
clearTimeout(timer)
resolve(window.QRLogin)
}
document.head.appendChild(script)
})
return sdkPromise
}
export function createFeishuAuthorizeUrl() {
const bytes = new Uint8Array(24)
window.crypto.getRandomValues(bytes)
const state = Array.from(bytes, byte => ('0' + byte.toString(16)).slice(-2)).join('')
window.sessionStorage.setItem(STATE_KEY, state)
return 'https://passport.feishu.cn/suite/passport/oauth/authorize' +
'?client_id=cli_aa54791236b89cfa' +
'&redirect_uri=' + encodeURIComponent(FEISHU_REDIRECT_URI) +
'&response_type=code&state=' + encodeURIComponent(state)
}
export function getFeishuCallback() {
const search = new URLSearchParams(window.location.search)
const hash = window.location.hash
const hashQuery = new URLSearchParams(hash.includes('?') ? hash.slice(hash.indexOf('?') + 1) : '')
// OAuth parameters may be placed before or after the Vue hash route.
const params = search.has('code') || search.has('error') ? search : hashQuery
if (!params.has('code') && !params.has('error')) return null
return {
code: params.get('code'),
state: params.get('state'),
error: params.get('error')
}
}
export function consumeFeishuCallback() {
const callback = getFeishuCallback()
if (!callback) return null
const expectedState = window.sessionStorage.getItem(STATE_KEY)
window.sessionStorage.removeItem(STATE_KEY)
const url = new URL(window.location.href)
CALLBACK_KEYS.forEach(key => url.searchParams.delete(key))
const [path, query = ''] = url.hash.split('?')
const hashQuery = new URLSearchParams(query)
CALLBACK_KEYS.forEach(key => hashQuery.delete(key))
url.hash = path + (hashQuery.toString() ? '?' + hashQuery.toString() : '')
window.history.replaceState(window.history.state, '', url.toString())
if (!expectedState || callback.state !== expectedState) {
throw new Error('飞书登录状态校验失败,请重新扫码')
}
if (callback.error || !callback.code) {
throw new Error('飞书授权未完成,请重新扫码')
}
return callback.code
}
<template>
<div class="feishu-login">
<el-alert v-if="authorized" title="正在登录系统,请稍候…" type="info" :closable="false" show-icon />
<el-alert v-else-if="error" :title="error" type="error" :closable="false" show-icon />
<div v-show="!authorized && !error" v-loading="loading" class="feishu-qrcode">
<div id="feishu-login-container" />
</div>
<p v-if="!authorized && !error" class="feishu-tip">使用飞书 App 扫码并确认授权</p>
<el-button v-if="!authorized" type="text" :disabled="loading" @click="initQrCode">刷新二维码</el-button>
</div>
</template>
<script>
import { consumeFeishuCallback, createFeishuAuthorizeUrl, loadFeishuSdk } from '@/utils/feishu-login'
export default {
name: 'FeishuLogin',
data() {
return {
loading: false,
authorized: false,
error: ''
}
},
mounted() {
window.addEventListener('message', this.handleMessage)
try {
const code = consumeFeishuCallback()
if (code) {
this.completeLogin(code)
return
}
} catch (error) {
this.error = error.message
return
}
this.initQrCode()
},
beforeDestroy() {
window.removeEventListener('message', this.handleMessage)
this.qrLogin = null
},
methods: {
async completeLogin(code) {
this.authorized = true
this.loading = true
try {
await this.$store.dispatch('user/feishuLogin', code)
this.$emit('success')
} catch (error) {
this.authorized = false
this.error = error.message || '飞书登录失败,请重新扫码或联系管理员'
} finally {
this.loading = false
}
},
async initQrCode() {
if (this.loading) return
this.loading = true
this.error = ''
this.qrLogin = null
try {
const QRLogin = await loadFeishuSdk()
if (this._isBeingDestroyed || this._isDestroyed) return
this.authorizeUrl = createFeishuAuthorizeUrl()
this.$el.querySelector('#feishu-login-container').innerHTML = ''
this.qrLogin = QRLogin({
id: 'feishu-login-container',
goto: this.authorizeUrl,
width: '300',
height: '300',
style: 'width:300px;height:300px;border:0;'
})
} catch (error) {
this.error = error.message || '飞书二维码加载失败,请重试'
} finally {
this.loading = false
}
},
handleMessage(event) {
if (!this.qrLogin || !this.qrLogin.matchOrigin(event.origin) || !this.qrLogin.matchData(event.data)) return
const iframe = this.$el.querySelector('iframe')
if (!iframe || event.source !== iframe.contentWindow) return
const tmpCode = event.data.tmp_code
if (typeof tmpCode !== 'string' || !tmpCode) return
this.qrLogin = null
this.loading = true
window.location.assign(this.authorizeUrl + '&tmp_code=' + encodeURIComponent(tmpCode))
}
}
}
</script>
<style lang="scss" scoped>
.feishu-login {
text-align: center;
min-height: 360px;
}
.feishu-qrcode {
width: 300px;
height: 300px;
margin: 0 auto;
}
.feishu-tip {
color: #606266;
font-size: 14px;
margin: 12px 0 0;
}
</style>
......@@ -29,7 +29,12 @@
<div class="login-border">
<div class="login-main">
<div class="login-title"> 用户登录 </div>
<el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
<el-tabs v-model="loginMethod" stretch>
<el-tab-pane label="账号密码登录" name="account" />
<el-tab-pane label="飞书扫码登录" name="feishu" />
</el-tabs>
<feishu-login v-if="loginMethod === 'feishu'" @success="handleFeishuSuccess" />
<el-form v-show="loginMethod === 'account'" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
<el-form-item prop="username">
<span class="svg-container">
<i class="el-icon-user" />
......@@ -90,9 +95,6 @@
<img style="height: 48px;width: 100%;border: 1px solid rgba(0,0,0, 0.1);border-radius:5px;" :src="codeUrl" @click="getCode">
</div>
</template>
<div prop="code" style="width: 100%;float: left;margin-bottom: 13px">
<el-checkbox v-model="isLdapTmp">LDAP登陆</el-checkbox>
</div>
<el-button :loading="loading" type="primary" style="width:100%;padding:12px 20px;margin-bottom:30px;" @click.native.prevent="handleLogin">
<span v-if="!loading">登 录</span>
<span v-else>登 录 中...</span>
......@@ -110,12 +112,15 @@
import { getCodeImg } from '@/api/login'
import moment from 'moment'
import { mapGetters } from 'vuex'
import FeishuLogin from './components/FeishuLogin'
import { getFeishuCallback } from '@/utils/feishu-login'
export default {
name: 'LoginIndex',
components: { FeishuLogin },
data() {
return {
isLdapTmp: false,
loginMethod: getFeishuCallback() ? 'feishu' : 'account',
codeUrl: '',
cookiePassword: '',
loginForm: {
......@@ -123,8 +128,7 @@ export default {
password: '',
rememberMe: false,
code: '',
uuid: '',
loginType: 1
uuid: ''
},
loginRules: {
username: [
......@@ -144,7 +148,7 @@ export default {
}
},
computed: {
...mapGetters(['title', 'logo', 'isLdap', 'isVerifyCode']),
...mapGetters(['title', 'logo', 'isVerifyCode']),
isVerifyCodeTmp: function() {
if (this.isVerifyCode) {
this.getCode()
......@@ -163,11 +167,6 @@ export default {
},
immediate: true
},
isLdap: {
handler: function(val) {
this.isLdapTmp = val
}
},
isVerifyCode: {
handler: function(val) {
if (val) {
......@@ -181,6 +180,7 @@ export default {
this.getCurrentTime()
},
mounted() {
if (this.loginMethod !== 'account') return
if (this.loginForm.username === '') {
this.$refs.username.focus()
} else if (this.loginForm.password === '') {
......@@ -192,6 +192,9 @@ export default {
// window.removeEventListener('storage', this.afterQRScan)
},
methods: {
handleFeishuSuccess() {
this.$router.replace({ path: '/' })
},
getCurrentTime() {
this.timer = setInterval(_ => {
this.currentTime = moment().format('YYYY-MM-DD HH时mm分ss秒')
......@@ -226,12 +229,6 @@ export default {
handleLogin() {
this.$refs.loginForm.validate(valid => {
if (valid) {
if (this.isLdapTmp) {
this.loginForm.loginType = 1
} else {
this.loginForm.loginType = 0
}
this.loading = true
this.$store.dispatch('user/login', this.loginForm)
.then(() => {
......
......@@ -9,9 +9,6 @@
<el-form-item label="确认密码" prop="confirmPassword" style="/* margin-bottom: 10px */">
<el-input v-model="user.confirmPassword" placeholder="请确认密码" type="password" />
</el-form-item>
<!-- <el-form-item style="margin-bottom: 5px">
<el-checkbox v-model="passwordTyleStatus">LDAP密码</el-checkbox>
</el-form-item> -->
<el-form-item>
<el-button type="primary" size="mini" @click="submit">保存</el-button>
<el-button type="danger" size="mini" @click="close">关闭</el-button>
......@@ -32,12 +29,10 @@ export default {
}
}
return {
passwordTyleStatus: true,
user: {
oldPassword: undefined,
newPassword: undefined,
confirmPassword: undefined,
passwordType: 1
confirmPassword: undefined
},
// 表单校验
rules: {
......@@ -59,11 +54,7 @@ export default {
submit() {
this.$refs['form'].validate(valid => {
if (valid) {
if (!this.passwordTyleStatus) {
this.user.passwordType = 0
}
this.user.passwordType = 0
updateUserPwd(this.user.oldPassword, this.user.newPassword, this.user.passwordType).then(
updateUserPwd(this.user.oldPassword, this.user.newPassword).then(
response => {
if (response.code === 200) {
this.msgSuccess('修改成功')
......
<template>
<el-form ref="form" :model="user" :rules="rules" label-width="80px">
<el-form-item label="登录账号">
<el-input :value="user.username" readonly />
<span class="text-muted">可使用此账号在登录页通过账号密码登录</span>
</el-form-item>
<el-form-item label="用户昵称" prop="nickName">
<el-input v-model="user.nickName" />
</el-form-item>
......
......@@ -26,58 +26,12 @@
<el-radio v-model="ruleForm.is_verify_code" :label="true">是</el-radio>
<el-radio v-model="ruleForm.is_verify_code" :label="false">否</el-radio>
</el-form-item>
<el-form-item label="LDAP登陆:">
<el-radio v-model="ruleForm.is_ldap" :label="true">是</el-radio>
<el-radio v-model="ruleForm.is_ldap" :label="false">否</el-radio>
</el-form-item>
<el-form-item style="margin-bottom: 0">
<el-button v-permisaction="['system:settings:index:config']" type="primary" @click="submitForm('ruleForm', 1)">确定</el-button>
</el-form-item>
</el-form>
</div>
</el-card>
<el-card class="box-card" style="margin-top: 15px">
<div slot="header" class="clearfix">
<span>Ldap配置</span>
</div>
<div class="text item">
<el-alert
title="Ldap登陆验证通过后,会将用户同步至本地数据库中,请在此配置数据同步的映射关系。单击Ldap字段可编辑,双击可隐藏编辑。"
type="info"
style="margin-bottom: 10px"
/>
<el-table
:data="tableData"
border
style="width: 100%"
>
<el-table-column
prop="local_field_name"
label="字段名称"
width="150"
/>
<el-table-column
prop="local_field_nick"
label="字段昵称"
width="150"
/>
<el-table-column
prop="ldap_field_name"
label="Ldap字段"
>
<template slot-scope="{row, $index}">
<div style="width: 100%; min-height: 24px;" @click="{{ chengenum($index, true) }}" @dblclick="{{ chengenum($index, false) }}">
<el-input v-if="editable[$index]" v-model="row.ldap_field_name" />
<span v-else>{{ row.ldap_field_name }}</span>
</div>
</template>
</el-table-column>
</el-table>
<div style="margin-top: 20px">
<el-button v-permisaction="['system:settings:index:ldap']" type="primary" @click="submitForm('ruleForm', 2)">确定</el-button>
</div>
</div>
</el-card>
</div>
</template>
......@@ -90,11 +44,9 @@ export default {
data() {
return {
url: process.env.VUE_APP_BASE_API + '/api/v1/public/uploadFile',
editable: [],
ruleForm: {
name: '',
logo: '',
is_ldap: false,
is_verify_code: true
},
rules: {
......@@ -105,8 +57,7 @@ export default {
logo: [
{ required: true, message: '请设置Logo', trigger: 'blur' }
]
},
tableData: []
}
}
},
created() {
......@@ -121,19 +72,14 @@ export default {
this.ruleForm = {
name: '',
logo: '',
is_ldap: false
is_verify_code: true
}
} else {
if (v.content.is_ldap === undefined || v.content.is_ldap === null) {
v.content.is_ldap = false
this.ruleForm = {
name: v.content.name || '',
logo: v.content.logo || '',
is_verify_code: v.content.is_verify_code !== false
}
this.ruleForm = v.content
}
} else if (v.classify === 2) {
if (v.content === undefined || v.content === null) {
this.tableData = []
} else {
this.tableData = v.content
}
}
}
......@@ -152,9 +98,6 @@ export default {
requestStatus = true
}
})
} else if (classify === 2) {
jsonValue.content = this.tableData
requestStatus = true
}
if (requestStatus) {
setSettings(jsonValue).then(response => {
......@@ -178,10 +121,6 @@ export default {
this.$message.error('上传头像图片大小不能超过 2MB!')
}
return isLt2M
},
chengenum(row, status) { // 我的方法
this.editable[row] = status
this.$set(this.editable, row, status)
}
}
}
......
// Run without project dependencies: node --experimental-vm-modules --test tests/feishu-login.node.test.mjs
import assert from 'node:assert/strict'
import { webcrypto } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { test } from 'node:test'
import { createContext, SourceTextModule, SyntheticModule } from 'node:vm'
async function setup() {
const storage = new Map()
const window = {
crypto: webcrypto,
location: new URL('https://work-order.shangjiadao.com/#/login'),
sessionStorage: {
getItem: key => storage.get(key), setItem: (key, value) => storage.set(key, value),
removeItem: key => storage.delete(key)
}
}
window.history = { replaceState: (_, unused, url) => { window.location = new URL(url, window.location) } }
const context = createContext({ window, URL, URLSearchParams, Uint8Array })
const source = await readFile(new URL('../src/utils/feishu-login.js', import.meta.url), 'utf8')
const utility = new SourceTextModule(source, { context })
await utility.link(() => { throw new Error('Unexpected import') })
await utility.evaluate()
const tokens = []
const apiCalls = []
let response = { token: 'system-jwt' }
const mock = exports => new SyntheticModule(Object.keys(exports), function() {
for (const [key, value] of Object.entries(exports)) this.setExport(key, value)
}, { context })
const api = mock({
login: () => {}, logout: () => {}, getInfo: () => {}, refreshtoken: () => {},
feishuLogin: async code => { apiCalls.push(code); if (response instanceof Error) throw response; return response }
})
const auth = mock({ getToken: () => '', setToken: token => tokens.push(token), removeToken: () => {} })
const router = mock({ default: {}, resetRouter: () => {} })
const user = new SourceTextModule(await readFile(new URL('../src/store/modules/user.js', import.meta.url), 'utf8'), { context })
await user.link(name => ({ '@/api/user': api, '@/utils/auth': auth, '@/router': router })[name])
await user.evaluate()
const componentSource = await readFile(new URL('../src/views/login/components/FeishuLogin.vue', import.meta.url), 'utf8')
const component = new SourceTextModule(componentSource.split('<script>')[1].split('</script>')[0], { context })
await component.link(() => utility)
await component.evaluate()
return {
window, util: utility.namespace, action: user.namespace.default.actions.feishuLogin,
methods: component.namespace.default.methods, tokens, apiCalls,
respond: value => { response = value },
begin: () => new URL(utility.namespace.createFeishuAuthorizeUrl()).searchParams.get('state')
}
}
test('authorization URL encodes the hash callback and carries random state', async() => {
const { util } = await setup()
const first = new URL(util.createFeishuAuthorizeUrl())
const second = new URL(util.createFeishuAuthorizeUrl())
assert.equal(first.searchParams.get('client_id'), 'cli_aa54791236b89cfa')
assert.equal(first.searchParams.get('redirect_uri'), util.FEISHU_REDIRECT_URI)
assert.equal(first.searchParams.get('response_type'), 'code')
assert.equal(first.hash, '')
assert.equal(first.searchParams.get('state').length, 48)
assert.notEqual(first.searchParams.get('state'), second.searchParams.get('state'))
})
for (const placement of ['search', 'hash']) {
test(`callback in ${placement} consumes state once and removes credentials`, async() => {
const env = await setup()
const state = env.begin()
env.window.history.replaceState(null, '', placement === 'search'
? `/?code=auth-code&state=${state}&keep=1#/login?redirect=%2Fdashboard`
: `/#/login?code=auth-code&state=${state}&redirect=%2Fdashboard`)
assert.equal(env.util.consumeFeishuCallback(), 'auth-code')
assert.equal(env.util.getFeishuCallback(), null)
assert.equal(env.window.sessionStorage.getItem('feishu-login-state'), undefined)
assert.equal(env.window.location.hash, '#/login?redirect=%2Fdashboard')
if (placement === 'search') assert.equal(env.window.location.search, '?keep=1')
})
}
for (const scenario of ['mismatch', 'unsolicited', 'denied', 'replay']) {
test(`rejects ${scenario} callback`, async() => {
const env = await setup()
let state = scenario === 'unsolicited' ? 'old' : env.begin()
if (scenario === 'mismatch') state = 'wrong'
const url = `/#/login?${scenario === 'denied' ? 'error=access_denied' : 'code=auth-code'}&state=${state}`
env.window.history.replaceState(null, '', url)
if (scenario === 'replay') {
env.util.consumeFeishuCallback()
env.window.history.replaceState(null, '', url)
}
assert.throws(() => env.util.consumeFeishuCallback(), scenario === 'denied' ? /授权未完成/ : /状态校验失败/)
assert.equal(env.util.getFeishuCallback(), null)
})
}
test('successful backend login persists only the system JWT', async() => {
const env = await setup()
const commits = []
await env.action({ commit: (...args) => commits.push(args) }, 'one-use-code')
assert.deepEqual(env.apiCalls, ['one-use-code'])
assert.deepEqual(commits, [['SET_TOKEN', 'system-jwt']])
assert.deepEqual(env.tokens, ['system-jwt'])
})
for (const response of [undefined, {}, new Error('unbound account')]) {
test(`failed backend login never stores a session (${String(response)})`, async() => {
const env = await setup()
env.respond(response)
await assert.rejects(env.action({ commit: () => assert.fail('unexpected session') }, 'code'))
assert.deepEqual(env.tokens, [])
})
}
test('component emits success only after the backend creates a session', async() => {
const { methods } = await setup()
const events = []
const vm = { $store: { dispatch: async(name, code) => {
assert.equal(name, 'user/feishuLogin'); assert.equal(code, 'code')
} }, $emit: event => events.push(event) }
await methods.completeLogin.call(vm, 'code')
assert.deepEqual(events, ['success'])
assert.equal(vm.loading, false)
vm.$store.dispatch = async() => { throw new Error('denied') }
await methods.completeLogin.call(vm, 'code')
assert.deepEqual(events, ['success'])
assert.equal(vm.authorized, false)
assert.equal(vm.error, 'denied')
})
test('QR message requires both SDK validation and the originating iframe', async() => {
const { methods, window } = await setup()
const frameWindow = {}
let navigation
window.location.assign = url => { navigation = url }
const qrLogin = { matchOrigin: origin => origin === 'https://passport.feishu.cn', matchData: data => !!data.tmp_code }
const vm = { qrLogin, authorizeUrl: 'https://passport.feishu.cn/authorize?state=state', $el: { querySelector: () => ({ contentWindow: frameWindow }) } }
methods.handleMessage.call(vm, { origin: 'https://evil.example', data: { tmp_code: 'code' }, source: frameWindow })
assert.equal(navigation, undefined)
methods.handleMessage.call(vm, { origin: 'https://passport.feishu.cn', data: { tmp_code: 'code' }, source: {} })
assert.equal(navigation, undefined)
methods.handleMessage.call(vm, { origin: 'https://passport.feishu.cn', data: { tmp_code: 'code&injected=1' }, source: frameWindow })
assert.equal(navigation, vm.authorizeUrl + '&tmp_code=code%26injected%3D1')
assert.equal(vm.qrLogin, null)
})
import { consumeFeishuCallback, createFeishuAuthorizeUrl, getFeishuCallback, FEISHU_REDIRECT_URI } from '@/utils/feishu-login'
describe('Feishu OAuth callback', () => {
beforeEach(() => {
window.sessionStorage.clear()
window.history.replaceState(null, '', '/#/login')
Object.defineProperty(window, 'crypto', {
configurable: true,
value: { getRandomValues: bytes => bytes.fill(12) }
})
})
function beginLogin() {
return new URL(createFeishuAuthorizeUrl()).searchParams.get('state')
}
it('encodes the entire hash redirect URI as one OAuth parameter', () => {
const url = new URL(createFeishuAuthorizeUrl())
expect(url.searchParams.get('redirect_uri')).toBe(FEISHU_REDIRECT_URI)
expect(url.searchParams.get('client_id')).toBe('cli_aa54791236b89cfa')
expect(url.searchParams.get('response_type')).toBe('code')
expect(url.hash).toBe('')
expect(url.searchParams.get('state')).toHaveLength(48)
})
it('accepts callback parameters before the hash and removes only OAuth parameters', () => {
const state = beginLogin()
window.history.replaceState(null, '', '/?code=auth-code&state=' + state + '&keep=1#/login?redirect=%2Fdashboard')
expect(consumeFeishuCallback()).toBe('auth-code')
expect(window.location.search).toBe('?keep=1')
expect(window.location.hash).toBe('#/login?redirect=%2Fdashboard')
expect(getFeishuCallback()).toBe(null)
expect(window.sessionStorage.getItem('feishu-login-state')).toBe(null)
})
it('accepts callback parameters inside the hash route', () => {
const state = beginLogin()
window.history.replaceState(null, '', '/#/login?code=auth-code&state=' + state)
expect(consumeFeishuCallback()).toBe('auth-code')
expect(window.location.hash).toBe('#/login')
})
it('rejects a mismatched state and clears the callback', () => {
beginLogin()
window.history.replaceState(null, '', '/#/login?code=auth-code&state=wrong')
expect(() => consumeFeishuCallback()).toThrow('状态校验失败')
expect(getFeishuCallback()).toBe(null)
})
it('rejects unsolicited or replayed callbacks', () => {
window.history.replaceState(null, '', '/?code=auth-code&state=old#/login')
expect(() => consumeFeishuCallback()).toThrow('状态校验失败')
})
it('reports denied authorization without accepting a code', () => {
const state = beginLogin()
window.history.replaceState(null, '', '/?error=access_denied&state=' + state + '#/login')
expect(() => consumeFeishuCallback()).toThrow('授权未完成')
expect(window.location.search).toBe('')
})
})
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