/
index.ts
189 lines (152 loc) · 4.84 KB
/
index.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
/* eslint-disable @typescript-eslint/camelcase */
import { FieldResolver } from 'nexus'
import { NexusGenObjects } from 'server/nexus/generated/nexus'
import { MODXListUser, MODXUser } from '..'
/**
* Авторизация
*/
export const signin: FieldResolver<'Mutation', 'signin'> = async (
_,
args,
ctx
) => {
const { login_context, password, username } = args
const formBody = new URLSearchParams()
formBody.append('login_context', login_context || 'mgr')
formBody.append('username', username)
formBody.append('password', password)
formBody.append('login', '1')
formBody.append('returnUrl', '/manager/')
const result = await fetch(ctx.config.managerUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
/**
* Запрещаем редирект, так как иначе MODX в ответе присылает редирект
* и выполняется за раз сразу два запроса.
* При этом в последнем запросе прилетает кукис без авторизации. Нужен именно первый.
*/
redirect: 'manual', // manual, *follow, error
body: formBody,
})
.then(async (r) => {
const setCookie = await r.headers.get('set-cookie')
if (setCookie) {
const PHPSESSID = setCookie
.split(';')
.find((n) => n.startsWith('PHPSESSID'))
/**
* Запрашиваем код админки, чтобы получить токен.
* Приходится именно на страницу профиля заходить, чтобы найти ID текущего пользователя.
*/
return await fetch(ctx.config.managerUrl + '?a=security/profile', {
headers: {
cookie: PHPSESSID || '',
},
})
.then(async (r) => {
const response2 = await r.text()
/**
* ищем в ответе токен
*/
const tokenMatch = response2.match(/"auth":"(.+?)"/)
const token = tokenMatch && tokenMatch[1]
/**
* ищем в ответе ID пользователя. Без него мы не сможем получать объект текущего пользователя
*/
const userIdMatch = response2.match(/user: "(\d+?)"/)
const userId = userIdMatch && userIdMatch[1]
if (token && userId) {
/**
* Устанавливаем куки авторизованного пользователя
*/
ctx.res?.cookie(setCookie, undefined)
return { token, userId: parseInt(userId) }
}
return null
})
.catch(console.error)
}
})
.catch(console.error)
if (!result) {
throw new Error('Ошибка авторизации')
}
return result
}
/**
* Пользователь
*/
export const user: FieldResolver<'Query', 'user' | 'me'> = async (
_,
args,
ctx
) => {
const { where } = args
if (!where.id) {
return null
}
const formBody = new URLSearchParams()
formBody.append('action', 'Security/User/Get')
type Name = keyof typeof where
Object.keys(where).forEach((name) => {
const value = where[name as Name]
if (value !== null && value !== undefined) {
formBody.append(name, value.toString())
}
})
return ctx
.connectorRequest<{
object?: MODXUser
}>(formBody, ctx)
.then(async (r) => {
return r.object || null
})
}
/**
* Список пользователей
*/
export const usersConnection: FieldResolver<
'Query',
'usersConnection'
> = async (_, args, ctx) => {
const formBody = new URLSearchParams()
formBody.append('action', 'Security/User/GetList')
type Name = keyof typeof args
Object.keys(args).forEach((name) => {
const value = args[name as Name]
if (value !== null && value !== undefined) {
formBody.append(name, value.toString())
}
})
const result = await ctx
.connectorRequest<{
results?: MODXListUser[]
}>(formBody, ctx)
.then(async (r) => {
// const response = await r.text()
// console.log('users response', response)
// console.log('users response headers', r.headers)
// try {
// const data = JSON.parse(response)
// console.log('data', data)
// return data.results || []
// } catch (error) {
// throw new Error(error)
// }
const users: NexusGenObjects['User'][] = []
// return r.results || [];
r.results?.forEach((n) => {
if (n) {
users.push(n)
}
})
return {
users,
total: r.total || 0,
}
})
// .catch(console.error)
return result
}