提交 f759aed9 编写于 作者: 雪洛's avatar 雪洛

feat: init project

上级 ad23509e
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = false
insert_final_newline = false
\ No newline at end of file
module.exports = {
"extends": "standard",
"globals": {
"uniCloud": true,
"__ctx__": true
},
"rules": {
"no-throw-literal": 0
}
};
node_modules
dist
yarn-error.log
\ No newline at end of file
build/
dev-script/
ext/
node_modules/
src/
.eslintrc.js
.gitignore
yarn.lock
\ No newline at end of file
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
文档已移至:[uni-id](https://uniapp.dcloud.net.cn/uniCloud/uni-id-common.html)
\ No newline at end of file
const { builtinModules } = require('module')
const { terser } = require('rollup-plugin-terser')
const resolve = require('@rollup/plugin-node-resolve')
const commonjs = require('@rollup/plugin-commonjs')
const json = require('@rollup/plugin-json')
const plugins = [resolve(), commonjs({
ignore: ['uni-config-center'],
include: ['node_modules/**']
}), json()]
if (process.env.NODE_ENV === 'production') {
plugins.push(
terser({
output: {
comments: false
}
})
)
}
module.exports = function (moduleName) {
return {
input: 'src/index.js',
output: {
file: 'dist/index.js',
format: 'commonjs'
},
plugins,
external: [
'uni-config-center',
...builtinModules
]
}
}
{
"passwordSecret": "passwordSecret-demo",
"tokenSecret": "tokenSecret-demo",
"tokenExpiresIn": 7200,
"tokenExpiresThreshold": 600,
"autoSetInviteCode": false,
"forceInviteCode": false,
"app": {
"tokenExpiresIn": 2592000,
"oauth" : {
"weixin" : {
"appid" : "weixin appid",
"appsecret" : "weixin appsecret"
},
"apple": {
"bundleId": "your APP bundleId"
}
}
},
"mp-weixin": {
"oauth" : {
"weixin" : {
"appid" : "weixin appid",
"appsecret" : "weixin appsecret"
}
}
},
"mp-alipay": {
"oauth" : {
"alipay" : {
"appid" : "alipay appid",
"privateKey" : "alipay privateKey"
}
}
},
"service": {
"sms": {
"name": "DCloud",
"codeExpiresIn": 300,
"smsKey": "your sms key",
"smsSecret": "your sms secret"
},
"univerify": {
"appid":"your appid",
"apiKey": "your apiKey",
"apiSecret": "your apiSecret"
}
}
}
{
"name": "@dcloudio/uni-id-common",
"version": "1.0.0",
"description": "uni-id token生成、校验、刷新",
"main": "dist/index.js",
"homepage": "https://uniapp.dcloud.io/uniCloud/uni-id-common.html",
"repository": {
"type": "git",
"url": "git+https://gitee.com/dcloud/uni-id-common.git"
},
"scripts": {
"lint": "eslint --fix src build",
"build": "npm run lint && rollup -c build/rollup.config.js --environment NODE_ENV:production && node script/sync-package.js",
"dev": "rollup -c build/rollup.config.js --environment NODE_ENV:development"
},
"author": "DCloud",
"license": "Apache-2.0",
"devDependencies": {
"@rollup/plugin-commonjs": "^11.1.0",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^7.1.3",
"eslint": "^6.8.0",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-import": "^2.19.1",
"eslint-plugin-node": "^11.0.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"husky": "^8.0.1",
"rollup": "^1.28.0",
"rollup-plugin-terser": "^5.1.3"
},
"husky": {
"hooks": {
"pre-commit": "npm run lint",
"commit-msg": "node script/check-commit-msg.js"
}
}
}
此差异已折叠。
const fs = require('fs')
const path = require('path')
const cwd = process.cwd()
const message = fs.readFileSync(path.join(cwd, process.env.HUSKY_GIT_PARAMS), 'utf-8')
const commitRE = /^(\d+\.\d+\.\d+(-(alpha|beta|rc.\d+))?)|((revert: )?(feat|fix|polish|docs|style|refactor|perf|test|workflow|ci|chore|types|build|deps)(\(.+\))?!?: .{1,50})/
if (!commitRE.test(message)) {
console.log('\u001b[41;37mGit提交信息不符合规范\u001b[0m')
console.log('提交信息需形如:type(scope?): subject')
console.log('type可取值为:revert|feat|fix|polish|docs|style|refactor|perf|test|workflow|ci|chore|types|build|deps')
console.log('subject部分长度应在1-50之间')
process.exitCode = 1
}
const fs = require('fs')
const path = require('path')
const packageJsonPath = path.resolve(__dirname, '../package.json')
const distPackagePath = path.resolve(__dirname, '../dist/package.json')
const packageJson = require(packageJsonPath)
delete packageJson.devDependencies
delete packageJson.dependencies
delete packageJson.scripts
delete packageJson.husky
packageJson.main = 'index.js'
packageJson.name = 'uni-id-common'
packageJson.dependencies = {
'uni-config-center': 'file:../../../../../uni-config-center/uniCloud/cloudfunctions/common/uni-config-center'
}
const packageStr = JSON.stringify(packageJson, null, 2)
fs.writeFileSync(distPackagePath, packageStr)
export const db = uniCloud.database()
export const dbCmd = db.command
export const userCollectionName = 'uni-id-users'
export const userCollection = db.collection(userCollectionName)
export const roleCollectionName = 'uni-id-roles'
export const roleCollection = db.collection(roleCollectionName)
export const ERROR = {
TOKEN_EXPIRED: 'uni-id-token-expired',
CHECK_TOKEN_FAILED: 'uni-id-check-token-failed',
PARAM_REQUIRED: 'uni-id-param-required',
ACCOUNT_EXISTS: 'uni-id-account-exists',
ACCOUNT_NOT_EXISTS: 'uni-id-account-not-exists',
ACCOUNT_CONFLICT: 'uni-id-account-conflict',
ACCOUNT_BANNED: 'uni-id-account-banned',
ACCOUNT_AUDITING: 'uni-id-account-auditing',
ACCOUNT_AUDIT_FAILED: 'uni-id-account-audit-failed',
ACCOUNT_CLOSED: 'uni-id-account-closed'
}
export function isUniIDError (errCode) {
return Object.values(ERROR).includes(errCode)
}
import crypto from 'crypto'
// nodejs8没有base64url这种encoding,此处为对应的polyfill
function toBase64Url (str) {
return str.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_')
}
function fromBase64Url (base64url) {
base64url = base64url.toString()
var padding = 4 - base64url.length % 4
if (padding !== 4) {
for (var i = 0; i < padding; ++i) {
base64url += '='
}
}
return base64url
.replace(/-/g, '+')
.replace(/_/g, '/')
}
function atob (str) {
return Buffer.from(str, 'base64').toString('utf-8')
}
function btoa (str) {
return Buffer.from(str, 'utf-8').toString('base64')
}
function fromToken (base64url) {
return JSON.parse(
atob(
fromBase64Url(
base64url
)
)
)
}
function toToken (obj) {
return toBase64Url(
btoa(
JSON.stringify(
obj
)
)
)
}
function getSign (str, secret) {
return toBase64Url(
crypto.createHmac('sha256', secret).update(str).digest('base64')
)
}
const jwt = {
verify: function (token, secret) {
if (typeof token !== 'string') {
throw new Error('Invalid token')
}
const tokenArr = token.split('.')
if (tokenArr.length !== 3) {
throw new Error('Invalid token')
}
const [headerBase64, payloadBase64, signatureBase64] = tokenArr
if (getSign(headerBase64 + '.' + payloadBase64, secret) !== signatureBase64) {
throw new Error('Invalid token')
}
const header = fromToken(headerBase64)
if (header.alg !== 'HS256' || header.typ !== 'JWT') {
throw new Error('Invalid token')
}
const payload = fromToken(payloadBase64)
if (payload.exp * 1000 < Date.now()) {
const err = new Error('Token expired')
err.name = 'TokenExpiredError'
throw err
}
return payload
},
sign: function (data, secret, options = {}) {
const {
expiresIn
} = options
if (!expiresIn) {
throw new Error('expiresIn is required')
}
const header = {
alg: 'HS256',
typ: 'JWT'
}
const now = parseInt(Date.now() / 1000)
const payload = {
...data,
iat: now,
exp: now + options.expiresIn
}
const signStr = toToken(header) + '.' + toToken(payload)
const signature = getSign(signStr, secret)
return signStr + '.' + signature
}
}
export default jwt
export function getDistinctArray (arr) {
return Array.from(new Set(arr))
}
export function getType (val) {
return Object.prototype.toString.call(val).slice(8, -1).toLowerCase()
}
export function isPromise (obj) {
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}
import {
isUniIDError
} from './error'
import {
getType,
isPromise
} from './utils'
// 保证各版本clientDB能正常运行
const codeMap = {
'uni-id-token-expired': 30203,
'uni-id-check-token-failed': 30202
}
function parseErrMsg (err) {
const {
errCode,
errMsgValue
} = err
err.errMsg = this._t(errCode, errMsgValue)
if (errCode in codeMap) {
err.code = codeMap[errCode]
}
}
function isUniIDResponse (res) {
return getType(res) === 'object' && res.errCode && isUniIDError(res.errCode) && !!res.errCode
}
export function wrapFn (fn) {
return function () {
let promise
try {
promise = fn.apply(this, arguments)
} catch (error) {
if (isUniIDResponse(error)) {
parseErrMsg.call(this, error)
return error
}
throw error
}
if (isPromise(promise)) {
return promise.then((res) => {
if (isUniIDResponse(res)) {
parseErrMsg.call(this, res)
}
return res
}, (err) => {
if (isUniIDResponse(err)) {
parseErrMsg.call(this, err)
return err
}
throw err
})
} else {
if (isUniIDResponse(promise)) {
parseErrMsg.call(this, promise)
}
}
return promise
}
}
import {
wrapFn
} from './common/wrap-fn'
import messages from './lang/index'
import * as methodList from './uni-id'
function parseContext (context) {
return {
appId: context.APPID,
platform: context.PLATFORM,
locale: context.LOCALE,
clientIP: context.CLIENTIP,
deviceId: context.DEVICEID
}
}
const uniIDConfig = require('uni-config-center')({
pluginId: 'uni-id'
})
class UniID {
constructor ({
context,
clientInfo,
config
} = {}) {
this._clientInfo = context ? parseContext(context) : clientInfo
this.config = config || this._getOriginConfig()
this.interceptorMap = new Map()
if (uniIDConfig.hasFile('custom-token.js')) {
this.setInterceptor('customToken', require(uniIDConfig.resolve('custom-token.js')))
}
this._i18n = uniCloud.initI18n({
locale: this._clientInfo.locale,
fallbackLocale: 'zh-Hans',
messages
})
}
_t (...args) {
return this._i18n.t(...args)
}
_getOriginConfig () {
if (uniIDConfig.hasFile('config.json')) {
let configContent
try {
configContent = uniIDConfig.config()
} catch (error) {
throw new Error('Invalid uni-id config file\n' + error.messages)
}
// require [1,2] => {0:1,1:2}
if (Array.isArray(configContent)) {
return configContent
}
return configContent[0] ? Object.values(configContent) : configContent
} else {
throw new Error('Invalid uni-id config file')
}
}
_getAppConfig () {
const originConfig = this._getOriginConfig()
if (!Array.isArray(originConfig)) {
return originConfig
}
return originConfig.find(item => item.dcloudAppid === this.clientInfo.appId) || originConfig.find(item => item.isDefaultConfig)
}
_getPlatformConfig () {
const appConfig = this._getAppConfig()
if (this._clientInfo.platform === 'app-plus') {
this._clientInfo.platform = 'app'
}
if (this._clientInfo.platform === 'h5') {
this._clientInfo.platform = 'web'
}
const defaultConfig = {}
const argsRequired = ['tokenSecret', 'tokenExpiresIn']
const config = Object.assign(defaultConfig, appConfig, appConfig[this._clientInfo.platform])
argsRequired.forEach((item) => {
if (!config || !config[item]) {
throw new Error(`Config parameter missing, ${item} is required`)
}
})
return config
}
_getConfig () {
return this._getPlatformConfig()
}
}
for (const key in methodList) {
UniID.prototype[key] = methodList[key]
}
function createInstance (params) {
// {
// context,
// clientInfo,
// config
// } = params
const uniIDOrigin = new UniID(params)
const uniID = new Proxy(uniIDOrigin, {
get (target, prop) {
if (prop in target && prop.indexOf('_') !== 0) {
if (typeof target[prop] === 'function') {
return wrapFn(target[prop]).bind(target)
} else if (prop === 'context' || prop === 'config') {
} else {
return target[prop]
}
}
}
})
return uniID
}
UniID.prototype.createInstance = createInstance
const uniID = {
// 自4.0.0版起只能使用createInstance创建实例,直接require('uni-id')仅会得到一个包含createInstance方法的对象
createInstance
}
export default uniID
const word = {}
const sentence = {
// end user message
'uni-id-token-expired': 'The login status is invalid, token has expired',
'uni-id-check-token-failed': 'Check token failed',
'uni-id-param-required': 'Parameter required: {param}',
'uni-id-account-exists': 'Account exists',
'uni-id-account-not-exists': 'Account does not exists',
'uni-id-account-conflict': 'User account conflict',
'uni-id-account-banned': 'Account has been banned',
'uni-id-account-auditing': 'Account audit in progress',
'uni-id-account-audit-failed': 'Account audit failed',
'uni-id-account-closed': 'Account has been closed'
}
export default {
...word,
...sentence
}
import zhHans from './zh-Hans'
import en from './en'
let lang = {
'zh-Hans': zhHans,
en: en
}
function mergeLanguage (lang1, lang2) {
const localeList = Object.keys(lang1)
localeList.push(...Object.keys(lang2))
const result = {}
for (let i = 0; i < localeList.length; i++) {
const locale = localeList[i]
result[locale] = Object.assign({}, lang1[locale], lang2[locale])
}
return result
}
try {
const langPath = require.resolve('uni-config-center/uni-id/lang/index.js')
lang = mergeLanguage(lang, require(langPath))
} catch (error) { }
export default lang
const word = {}
const sentence = {
// end user message
'uni-id-token-expired': '登陆状态失效,token已过期',
'uni-id-check-token-failed': 'token校验未通过',
'uni-id-param-required': '缺少参数: {param}',
'uni-id-account-exists': '此账号已注册',
'uni-id-account-not-exists': '此账号未注册',
'uni-id-account-conflict': '用户账号冲突',
'uni-id-account-banned': '从账号已封禁',
'uni-id-account-auditing': '此账号正在审核中',
'uni-id-account-audit-failed': '此账号审核失败',
'uni-id-account-closed': '此账号已注销'
}
export default {
...word,
...sentence
}
import {
checkTokenInternal,
refreshTokenInternal
} from './utils'
export default async function checkToken (token, {
autoRefresh = true
} = {}) {
const payload = await checkTokenInternal.call(this, token)
const {
tokenExpiresThreshold
} = this._getConfig()
if (!tokenExpiresThreshold || !autoRefresh) {
return {
code: 0,
errCode: 0,
...payload
}
}
const now = Date.now()
const needRefreshToken = payload.exp * 1000 - now < tokenExpiresThreshold * 1000
let newToken = {}
if (needRefreshToken) {
newToken = await refreshTokenInternal.call(this, payload)
}
return {
code: 0,
errCode: 0,
...payload,
...newToken
}
}
import {
createTokenInternal
} from './utils'
export default async function createToken ({
uid,
role,
permission
} = {}) {
return createTokenInternal.call(this, {
uid,
role,
permission
})
}
import checkToken from './check-token'
import createToken from './create-token'
import refreshToken from './refresh-token'
export {
checkToken,
createToken,
refreshToken
}
import {
checkTokenInternal,
refreshTokenInternal
} from './utils'
export default async function refreshToken ({
token
} = {}) {
const payload = await checkTokenInternal.call(this, token)
const newToken = await refreshTokenInternal.call(this, payload)
return {
errCode: 0,
...newToken
}
}
import jwt from '../../common/jwt'
import {
ERROR
} from '../../common/error'
import {
dbCmd,
userCollection,
roleCollection
} from '../../common/constants'
import {
getDistinctArray
} from '../../common/utils'
export async function checkTokenInternal (token) {
const {
tokenSecret,
tokenExpiresIn,
tokenExpiresThreshold
} = this._getConfig()
if (tokenExpiresThreshold > tokenExpiresIn) {
throw new Error('Config error, tokenExpiresThreshold should be less than tokenExpiresIn')
}
let payload
try {
payload = jwt.verify(token, tokenSecret)
} catch (error) {
if (error.name === 'TokenExpiredError') {
throw {
errCode: ERROR.TOKEN_EXPIRED
}
}
throw {
errCode: ERROR.CHECK_TOKEN_FAILED
}
}
return payload
}
export async function refreshTokenInternal (payload) {
// refresh时查库校验对比token创建时间和用户表的valid_token_date
const uid = payload.uid
const getUserRes = await userCollection.doc(uid).get()
const userRecord = getUserRes.data[0]
if (!userRecord) {
throw {
errCode: ERROR.CHECK_TOKEN_FAILED
}
}
if (userRecord.valid_token_date && userRecord.valid_token_date > payload.iat * 1000) {
throw {
errCode: ERROR.TOKEN_EXPIRED
}
}
const {
role,
permission
} = await getUserPermission(userRecord)
return createTokenInternal.call(this, {
uid,
role,
permission
})
}
async function getUserPermission (userRecord) {
// const getUserRes = await userCollection.doc(uid).get()
// const userRecord = getUserRes.data[0]
if (!userRecord) {
throw {
errCode: ERROR.ACCOUNT_NOT_EXISTS
}
}
checkUserStatus(userRecord)
const role = userRecord.role || []
if (role.length === 0) {
return {
role: [],
permission: []
}
}
if (role.includes('admin')) {
return {
role: ['admin'],
permission: []
}
}
const getRoleListRes = await roleCollection.where({
role_id: dbCmd.in(role)
})
const permission = getDistinctArray(
getRoleListRes.data.reduce((list, item) => {
if (item.permission) {
list.push(...item.permission)
}
}, [])
)
return {
role,
permission
}
}
function checkUserStatus (userRecord) {
switch (userRecord.status) {
case undefined:
case 0:
break
case 1:
throw {
errCode: ERROR.ACCOUNT_BANNED
}
case 2:
throw {
errCode: ERROR.ACCOUNT_AUDITING
}
case 3:
throw {
errCode: ERROR.ACCOUNT_AUDIT_FAILED
}
case 4:
throw {
errCode: ERROR.ACCOUNT_CLOSED
}
default:
break
}
}
async function postCreateToken ({
uid,
signContent,
tokenSecret,
tokenExpiresIn
} = {}) {
const now = Date.now()
const token = jwt.sign(signContent, tokenSecret, {
expiresIn: tokenExpiresIn
})
await userCollection.doc(uid).update({
last_login_ip: this._clientInfo.clientIP,
last_login_date: now
})
return {
token,
tokenExpired: now + tokenExpiresIn * 1000
}
}
export async function createTokenInternal ({
uid,
role,
permission
} = {}) {
const {
tokenSecret,
tokenExpiresIn,
tokenExpiresThreshold
} = this._getConfig()
if (!uid) {
throw {
errCode: ERROR.PARAM_REQUIRED,
errMsgValue: {
param: 'uid'
}
}
}
if (tokenExpiresThreshold > tokenExpiresIn) {
throw new Error('Config error, tokenExpiresThreshold should be less than tokenExpiresIn')
}
if (!role || !permission) {
const getUserRes = await userCollection.doc(uid).get()
const userRecord = getUserRes.data[0]
const getUserPermissionResult = await getUserPermission(userRecord)
role = getUserPermissionResult.role
permission = getUserPermissionResult.permission
}
if (!this.interceptorMap.has('customToken')) {
return postCreateToken.call(this, {
uid,
signContent: {
uid,
role,
permission
},
tokenSecret,
tokenExpiresIn
})
}
const customToken = this.interceptorMap.get('customToken')
if (typeof customToken === 'function') {
throw new Error('Invalid custom token file')
}
const customTokenRes = await customToken({
uid,
role,
permission
})
return postCreateToken.call(this, {
uid,
signContent: customTokenRes,
tokenSecret,
tokenExpiresIn
})
}
export * from './lib/token'
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册