-
Notifications
You must be signed in to change notification settings - Fork 14
/
getViewer.ts
193 lines (164 loc) · 4.84 KB
/
getViewer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import type { Viewer, Connections, LANGUAGES } from 'definitions'
import cookie from 'cookie'
import { Request, Response } from 'express'
import jwt from 'jsonwebtoken'
import {
AUTH_MODE,
COOKIE_TOKEN_NAME,
COOKIE_USER_GROUP,
COOKIE_LANGUAGE,
USER_ROLE,
USER_STATE,
} from 'common/enums'
import { environment } from 'common/environment'
import { ForbiddenByStateError, TokenInvalidError } from 'common/errors'
import { getLogger } from 'common/logger'
import { clearCookie, getLanguage } from 'common/utils'
import { OAuthService, SystemService, AtomService } from 'connectors'
const logger = getLogger('utils-auth')
export const roleAccess = [USER_ROLE.visitor, USER_ROLE.user, USER_ROLE.admin]
export const authModes = [
AUTH_MODE.visitor,
AUTH_MODE.oauth,
AUTH_MODE.user,
AUTH_MODE.admin,
]
/**
* Define user group by id or ip. Even is group A, and odd is group B.
*
*/
export const getUserGroup = ({
id,
ip,
}: {
id?: string | null
ip?: string
}) => {
let num = 0
try {
if (id) {
num = parseInt(id, 10) || 0
} else if (ip) {
const last = ip.split(/[.:]/).pop() || '0'
num = parseInt(last, 10) || 0
}
} catch (error) {
logger.warn('getUserGroup failed: %j', { id, ip })
}
return num % 2 === 0 ? 'a' : 'b'
}
export const getViewerFromUser = async (
user: any,
group?: string,
token?: string
) => {
// overwrite default by user
const viewer = { role: USER_ROLE.visitor, ...user, token }
// append user group
viewer.group = group ? group : getUserGroup(user)
// append helper functions (keep it till we fully utilize scope)
viewer.hasRole = (requires: string) =>
roleAccess.findIndex((role) => role === viewer.role) >=
roleAccess.findIndex((role) => role === requires)
// append helper functions
viewer.hasAuthMode = (requires: string) =>
authModes.findIndex((mode) => mode === viewer.authMode) >=
authModes.findIndex((mode) => mode === requires)
return viewer
}
const getUser = async (
token: string,
agentHash: string,
connections: Connections
) => {
const atomService = new AtomService(connections)
const systemService = new SystemService(connections)
try {
// get general user
const source = jwt.verify(token, environment.jwtSecret) as {
id: string
}
const user = await atomService.userIdLoader.load(source.id)
if (user.state === USER_STATE.archived) {
if (agentHash) {
await systemService
.saveAgentHash(agentHash, user.id)
.catch((error) => logger.error(error))
}
throw new ForbiddenByStateError('user has been deleted')
}
return { ...user, authMode: user.role }
} catch (error) {
// get oauth user
const oAuthService = new OAuthService(connections)
const data = await oAuthService.getAccessToken(token)
if (data && data.accessTokenExpiresAt) {
// check it's expired or not
const live = data.accessTokenExpiresAt.getTime() - Date.now() > 0
if (!live) {
throw new TokenInvalidError('oauth token expired')
}
if (data.user.state === USER_STATE.archived) {
throw new ForbiddenByStateError('user has been deleted')
}
return {
...data.user,
authMode: AUTH_MODE.oauth,
scope: data.scope as string[],
oauthClient: data.client && data.client.rawClient,
}
}
throw new TokenInvalidError('token invalid')
}
}
export const getViewerFromReq = async (
{
req,
res,
}: {
req: Request
res?: Response
},
connections: Connections
): Promise<Viewer> => {
const headers = req ? req.headers : {}
const cookies = req ? cookie.parse(headers.cookie || '') : {}
// const isWeb = headers['x-client-name'] === 'web'
const language =
(cookies[COOKIE_LANGUAGE] as LANGUAGES) ||
getLanguage(
(headers['Accept-Language'] || headers['accept-language']) as LANGUAGES
)
const agentHash = headers['x-user-agent-hash'] as string
const userGroup = headers['x-user-group'] as string
const userAgent = headers['user-agent'] as string
// user information from request
let user = {
ip: req?.clientIp,
userAgent,
language,
authMode: AUTH_MODE.visitor,
scope: {},
agentHash,
}
// get user from token, use cookie first then 'x-access-token'
const token: string =
cookies[COOKIE_TOKEN_NAME] || (headers['x-access-token'] as string) || ''
const group = userGroup || cookies[COOKIE_USER_GROUP] || ''
if (!token) {
// logger.info('User is not logged in, viewing as guest')
return getViewerFromUser(user, group)
}
try {
const userDB = await getUser(token, agentHash, connections)
// overwrite request by user settings
user = { ...user, ...userDB }
} catch (err) {
logger.warn(err)
if (req && res) {
clearCookie({ req, res })
}
throw err
}
return getViewerFromUser(user, group, token)
}