forked from realByg/office-user-auto-create
-
Notifications
You must be signed in to change notification settings - Fork 21
/
worker.js
284 lines (256 loc) · 6.34 KB
/
worker.js
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
const notice = '公告,留空不显示'
const officeConfig = {
subscriptions: [
{
name: 'Office 365 A1 Plus for faculty',
sku: ''
},
{
name: 'Office 365 A1 Plus for students',
sku: ''
},
],
domains: ['a1p.us'],
getCodeLink: 'https://a1p.us',
}
const AADConfig = {
tenantId: '',
clientId: '',
clientSecret: '',
}
const KV = _KV
const genCodesPassword = ''
const genCodesAmount = 10
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
class CreateOfficeUser {
constructor(u, d, s) {
this.username = u
this.domain = d
this.skuId = s
this.password = null
this.accessToken = null
this.userEmail = this.username + '@' + this.domain
}
async create() {
this.createPassword()
await this.getAccessToken()
await this.createUser()
await sleep(1000)
await this.assignLicense()
return {
email: this.userEmail,
password: this.password
}
}
async getAccessToken() {
const url = 'https://login.microsoftonline.com/' + AADConfig.tenantId + '/oauth2/v2.0/token'
const postData = {
grant_type: 'client_credentials',
client_id: AADConfig.clientId,
client_secret: AADConfig.clientSecret,
scope: 'https://graph.microsoft.com/.default'
}
const reqOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: this.enQuery(postData)
}
const response = await fetch(url, reqOptions)
const results = await response.json()
this.accessToken = results.access_token
}
async createUser() {
const url = 'https://graph.microsoft.com/v1.0/users'
const postData = {
accountEnabled: true,
displayName: this.username,
mailNickname: this.username,
passwordPolicies: 'DisablePasswordExpiration, DisableStrongPassword',
passwordProfile: {
password: this.password,
forceChangePasswordNextSignIn: true
},
userPrincipalName: this.userEmail,
usageLocation: 'CN'
}
const reqOptions = {
method: 'POST',
headers: {
'content-type': 'application/json',
'Authorization': 'Bearer ' + this.accessToken
},
body: JSON.stringify(postData)
}
const response = await fetch(url, reqOptions)
const results = await response.json()
if (!!results.error) {
if (results.error.message ==
'Another object with the same value for property userPrincipalName already exists.')
throw '用户名已存在'
else
throw JSON.stringify(results.error)
}
this.userId = results.id
}
async assignLicense() {
const url = 'https://graph.microsoft.com/v1.0/users/' + this.userEmail + '/assignLicense'
const postData = {
addLicenses: [
{
disabledPlans: [],
skuId: this.skuId
},
],
removeLicenses: []
}
const reqOptions = {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + this.accessToken,
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
}
const response = await fetch(url, reqOptions)
const results = await response.json()
if (!!results.error)
throw JSON.stringify(results.error)
}
createPassword() {
const a = 'ABCDEFGHIJKLMNOPQRSTUVWXTZ'
const b = 'abcdefghiklmnopqrstuvwxyz'
const c = '1234567890'
let p = ''
for (let i = 0; i < 4; i++) {
p += a.charAt(Math.floor(Math.random() * (a.length - 0) + 0))
p += b.charAt(Math.floor(Math.random() * (a.length - 0) + 0))
p += c.charAt(Math.floor(Math.random() * (a.length - 0) + 0))
}
this.password = p
}
enQuery(data) {
const ret = []
for (let d in data) {
ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]))
}
return ret.join("&")
}
}
class Code {
init(c) {
this.code_k = c.split('@')[0]
this.code_v = c.split('@')[1]
}
async validate() {
const v = await KV.get(this.code_k)
if (!!v && v === this.code_v) {
return true
} else
return false
}
async delete() {
await KV.delete(this.code_k)
}
async gen() {
const a = 'ABCDEFGHIJKLMNOPQRSTUVWXTZ'
const b = 'abcdefghiklmnopqrstuvwxyz'
const c = '1234567890'
const s = '@'
let k = ''
let v = ''
k += a.charAt(Math.floor(Math.random() * (a.length - 0) + 0))
k += a.charAt(Math.floor(Math.random() * (a.length - 0) + 0))
k += b.charAt(Math.floor(Math.random() * (a.length - 0) + 0))
k += b.charAt(Math.floor(Math.random() * (a.length - 0) + 0))
k += c.charAt(Math.floor(Math.random() * (a.length - 0) + 0))
v += a.charAt(Math.floor(Math.random() * (a.length - 0) + 0))
v += b.charAt(Math.floor(Math.random() * (a.length - 0) + 0))
v += a.charAt(Math.floor(Math.random() * (a.length - 0) + 0))
await KV.put(k, v)
return k + s + v
}
}
const handleRequest = async request => {
const requestUrl = new URL(request.url)
const requestPath = requestUrl.pathname
switch (requestPath) {
case '/':
const html = await fetch(
'https://cdn.jsdelivr.net/gh/KusakabeSi/Office-User-Auto-Create@master/build/index.html'
)
return new Response(
await html.text(), {
status: 200,
headers: {
"Content-Type": "text/html; charset=utf-8"
}
}
)
case '/' + genCodesPassword:
let codes = []
for (let i = 0; i <= genCodesAmount; i++) {
codes.push(
await new Code().gen()
)
}
return new Response(codes.join('<br>'), {
status: 200,
headers: {
"Content-Type": "text/html; charset=utf-8"
}
})
case '/getNotice':
return new Response(notice, {
status: 200
})
case '/getOfficeConfig':
return new Response(JSON.stringify(officeConfig), {
status: 200
})
case '/getOffice':
const requestBody = await request.json()
let response = {}
const code = new Code()
code.init(requestBody.code)
if (await code.validate()) {
try {
const createOfficeUser = new CreateOfficeUser(
requestBody.email.username,
requestBody.email.domain,
requestBody.subscription
)
const account = await createOfficeUser.create()
response = {
success: true,
msg: '创建成功',
account: account,
}
await code.delete()
} catch (e) {
response = {
success: false,
msg: e,
}
}
} else {
response = {
success: false,
msg: '激活码无效',
}
}
return new Response(JSON.stringify(response), {
status: 200
})
default:
return new Response('Path does not exist', {
status: 200
})
}
}