Issues (124)

app/permissions.js (3 issues)

1
const Redis = require('./libraries/redis')
2
const Constant = require('./libraries/constant')
3
const ApiError = require('./util/api_error')
4
module.exports = function (permission) {
5
6
	return async function (ctx, next) {
7
8
		async function checkToken() {
9
			let token = (typeof (ctx.request.headers.token) == 'undefined' || !ctx.request.headers.token) ?
10
				ctx.cookies.get('token') : ctx.request.headers.token
11
			let uid = (typeof (ctx.request.headers.uid) == 'undefined' || !ctx.request.headers.uid) ?
12
				ctx.cookies.get('uid') : ctx.request.headers.uid
13
14
			if (!token || !uid) {
15
				console.log('token: ' + token)
0 ignored issues
show
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
16
				console.log('uid: ' + uid)
17
				throw new ApiError('auth.error', 'token missing')
18
			}
19
20
			sessionKey = Constant.WECHAT_SESSION + token
21
			session = await Redis.get(sessionKey)
22
			session = JSON.parse(session)
23
			if (!session) {
24
				throw new ApiError('auth.error', 'token error')
25
			}
26
27
			if (session.uid == uid) {
28
				ctx.uid = uid
29
				return true
30
			} else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
31
				throw new ApiError('auth.error', 'no permission')
32
			}
33
			
34
		}
35
36
		async function checkUser() {
37
			await checkToken()
38
			await next()
39
		}
40
41
		// guest
42
		if (permission === 'guest') {
43
			await next()
44
		} else if (permission === 'user') {
0 ignored issues
show
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
45
			return await checkUser()
46
		} else {
47
			throw new ApiError('role.notExist')
48
		}
49
50
	}
51
52
}
53