Skip to content

Commit

Permalink
feat(fix): 修复云函数上传文件bug;引入 jwt 库;增加云函数参数;
Browse files Browse the repository at this point in the history
  • Loading branch information
maslow committed Jun 11, 2021
1 parent 8f753b8 commit c28db5d
Show file tree
Hide file tree
Showing 14 changed files with 3,839 additions and 99 deletions.
3,783 changes: 3,754 additions & 29 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"dotenv": "^8.2.0",
"express": "^4.17.1",
"fs-extra": "^9.1.0",
"jsonwebtoken": "^8.5.1",
"less-api": "^1.4.3",
"less-api-database": "^0.3.7",
"lodash": "^4.17.21",
Expand All @@ -43,6 +44,7 @@
"@types/dotenv": "^8.2.0",
"@types/express": "^4.17.11",
"@types/fs-extra": "^9.0.8",
"@types/jsonwebtoken": "^8.5.1",
"@types/mongodb": "^3.6.10",
"@types/multer": "^1.4.5",
"@types/node": "^14.14.37",
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as express from 'express'
import { parseToken } from './lib/api/token'
import { parseToken } from './lib/utils/token'
import { router } from './router/index'
import { v4 as uuidv4 } from 'uuid'
import { getLogger } from './lib/logger'
Expand Down
39 changes: 0 additions & 39 deletions src/lib/api/token.ts

This file was deleted.

1 change: 1 addition & 0 deletions src/lib/faas/engine2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export class FunctionEngine {
body: incomingCtx.body,
auth: incomingCtx.auth,
params: incomingCtx.params,
files: incomingCtx.files,
method: incomingCtx.method,
requestId: requestId,
},
Expand Down
20 changes: 12 additions & 8 deletions src/lib/faas/invoke.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,23 @@ import { LocalFileStorage } from "../storage/local_file_storage"
import request from 'axios'
import Config from "../../config"
import { CloudFunctionStruct, CloudSdkInterface, FunctionContext } from "./types"
import { getToken, parseToken } from "../utils/token"

/**
* 调用云函数
*/
export async function invokeFunction(func: CloudFunctionStruct, param: FunctionContext) {
const { query, body, auth, requestId } = param
// const { query, body, auth, requestId } = param
const engine = new FunctionEngine()
const result = await engine.run(func.code, {
requestId,
...param,
// requestId,
functionName: func.name,
query: query,
body: body,
auth: auth,
params: param.params,
method: param.method,
// query: query,
// body: body,
// auth: auth,
// params: param.params,
// method: param.method,
less: createCloudSdk()
})

Expand Down Expand Up @@ -79,7 +81,9 @@ function createCloudSdk(): CloudSdkInterface {
fetch: request,
invoke: _invokeInFunction,
emit: (event: string, param: any) => scheduler.emit(event, param),
shared: _shared_preference
shared: _shared_preference,
getToken: getToken,
parseToken: parseToken
}

return less
Expand Down
2 changes: 1 addition & 1 deletion src/lib/faas/trigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { getCloudFunctionById, invokeFunction } from "./invoke"
import { db, accessor } from '../../lib/db'
import { now } from "../utils/time"
import { FunctionContext } from "./types"
import { convertActionType } from "../utils/util"
import { convertActionType } from "../utils"


const logger = getLogger('trigger')
Expand Down
10 changes: 6 additions & 4 deletions src/lib/faas/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,21 @@ import { Db } from 'less-api-database'
import { FileStorageInterface } from "../storage/interface"
import { IncomingHttpHeaders } from "node:http"


export type RequireFuncType = (module: 'crypto' | 'path' | 'querystring' | 'url' | 'lodash' | 'moment') => any

export type RequireFuncType = (module: string) => any
export type InvokeFunctionType = (name: string, param: FunctionContext) => Promise<any>
export type EmitFunctionType = (event: string, param: any) => void
export type GetTokenFunctionType = (payload: any) => string
export type ParseTokenFunctionType = (token: string) => any | null

export interface CloudSdkInterface {
fetch: AxiosStatic
storage(namespace: string): FileStorageInterface
database(): Db,
invoke: InvokeFunctionType
emit: EmitFunctionType
shared: Map<string, any>
getToken: GetTokenFunctionType
parseToken: ParseTokenFunctionType
}

// vm run context (global)
Expand Down Expand Up @@ -46,7 +49,6 @@ export interface FunctionContext {
// param for engine.run()
export interface IncomingContext extends FunctionContext {
functionName: string,
requestId: string,
less?: CloudSdkInterface
}

Expand Down
11 changes: 11 additions & 0 deletions src/lib/utils/hash.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import * as crypto from 'crypto'
import Config from '../../config'
const secret = Config.SERVER_SALT


export function hashPassword(content) {
return crypto
.createHash('md5')
.update(secret + content)
.digest('hex')
}
File renamed without changes.
24 changes: 24 additions & 0 deletions src/lib/utils/token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import Config from '../../config'
import * as jwt from 'jsonwebtoken'
const secret = Config.SERVER_SALT

/**
* 生成 token
* @param payload
* @param expire 秒
* @returns
*/
export function getToken(payload: any): string {
return jwt.sign(payload, secret)
}

// 解析 token
export function parseToken(token: string): any | null {
if (!token) return null
try {
const ret = jwt.verify(token, secret)
return ret
} catch (error) {
return null
}
}
18 changes: 11 additions & 7 deletions src/router/admin/admin.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Request, Response } from 'express'
import { getToken, hash } from '../../lib/api/token'
import { getToken } from '../../lib/utils/token'
import { db } from '../../lib/db'
import { checkPermission, getPermissions } from '../../lib/api/permission'
import { getLogger } from '../../lib/logger'
import { hashPassword } from '../../lib/utils/hash'


const logger = getLogger('admin:api')
Expand All @@ -26,7 +27,9 @@ export async function handleAdminLogin(req: Request, res: Response) {
//
const ret = await db.collection('admins')
.withOne({
query: db.collection('password').where({ password: hash(password), type: 'login' }),
query: db
.collection('password')
.where({ password: hashPassword(password), type: 'login' }),
localField: '_id',
foreignField: 'uid'
})
Expand All @@ -37,12 +40,13 @@ export async function handleAdminLogin(req: Request, res: Response) {
const admin = ret.data[0]

// 默认 token 有效期为 7 天
const expire = new Date().getTime() + 60 * 60 * 1000 * 24 * 7
const expire = Math.floor(Date.now() / 1000) + 60 * 60 * 1000 * 24 * 7
const payload = {
uid: admin._id,
type: 'admin'
type: 'admin',
exp: expire
}
const access_token = getToken(payload, expire)
const access_token = getToken(payload)
logger.info(`[${requestId}] admin login success: ${admin._id} ${username}`)

return res.send({
Expand Down Expand Up @@ -158,7 +162,7 @@ export async function handleAdminAdd(req: Request, res: Response) {
await db.collection('password')
.add({
uid: r.id,
password: hash(password),
password: hashPassword(password),
type: 'login',
created_at: Date.now(),
updated_at: Date.now()
Expand Down Expand Up @@ -223,7 +227,7 @@ export async function handleAdminEdit(req: Request, res: Response) {
await db.collection('password')
.where({ uid: uid })
.update({
password: hash(password),
password: hashPassword(password),
updated_at: Date.now()
})
}
Expand Down
14 changes: 9 additions & 5 deletions src/router/user/login.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Router } from 'express'
import { getToken, hash } from '../../lib/api/token'
import { getToken } from '../../lib/utils/token'
import { db } from '../../lib/db'
import { hashPassword } from '../../lib/utils/hash'

export const LoginRouter = Router()

Expand All @@ -20,7 +21,9 @@ LoginRouter.post('/login/password', async (req, res) => {
//
const ret = await db.collection('users')
.withOne({
query: db.collection('password').field({ password: 0 }).where({ password: hash(password), type: 'login' }),
query: db.collection('password')
.field({ password: 0 })
.where({ password: hashPassword(password), type: 'login' }),
localField: '_id',
foreignField: 'uid'
})
Expand All @@ -37,12 +40,13 @@ LoginRouter.post('/login/password', async (req, res) => {
const user = ret.data[0]

// 默认 token 有效期为 7 天
const expire = new Date().getTime() + 60 * 60 * 1000 * 24 * 7
const expire = Math.floor(Date.now() / 1000) + 60 * 60 * 1000 * 24 * 7
const payload = {
uid: user._id,
type: 'user'
type: 'user',
exp: expire
}
const access_token = getToken(payload, expire)
const access_token = getToken(payload)
return res.send({
code: 0,
data: {
Expand Down
12 changes: 7 additions & 5 deletions src/router/user/register.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Router } from 'express'
import { getToken, hash } from '../../lib/api/token'
import { getToken } from '../../lib/utils/token'
import { db } from '../../lib/db'
import * as assert from 'assert'
import { hashPassword } from '../../lib/utils/hash'
export const RegisterRouter = Router()

/**
Expand Down Expand Up @@ -48,20 +49,21 @@ RegisterRouter.post('/register/password', async (req, res) => {
// 创建 user password
await db.collection('password').add({
uid: r.id,
password: hash(password),
password: hashPassword(password),
created_at: Date.now(),
updated_at: Date.now()
})


// 注册完成后自动登录,生成 token: 默认 token 有效期为 7 天
const expire = new Date().getTime() + 60 * 60 * 1000 * 24 * 7
const expire = Math.floor(Date.now()) + 60 * 60 * 1000 * 24 * 7
const payload = {
uid: r.id,
type: 'user'
type: 'user',
exp: expire
}

const access_token = getToken(payload, expire)
const access_token = getToken(payload)
return res.send({
code: 0,
data: {
Expand Down

0 comments on commit c28db5d

Please sign in to comment.