import * as congig from 'config' import { client } from './tws-auth' import { Middleware, Context } from 'koa' const authToken = async (ctx: Context) => { const token = ctx.req.headers.authorization.split(' ')[1] const { result, error } = await client.user.checkToken(token) if (error) throw new Error() ctx.app['coreToken'] = token ctx.state.user = result.user } const authSession = async (ctx: Context) => { const { KEY, SIGN_KEY } = congig.AUTH const [keyValue, signValue, lang] = [ctx.cookies.get(KEY), ctx.cookies.get(SIGN_KEY), ctx.cookies.get('lang')] const { result, error } = await client.user.checkCookie(keyValue, signValue) if (error) throw new Error() ctx.state.lang = lang ctx.state.user = result.user } export const auth:Middleware = async (ctx, next) => { try { if (ctx.headers.authorization) { await authToken(ctx) } else { await authSession(ctx) } } catch (e) { ctx.throw(400, 'UserNotLogin') } await next() }