]>
Commit | Line | Data |
---|---|---|
1 | import * as request from 'supertest' | |
2 | ||
3 | import { ServerInfo } from '../server/servers' | |
4 | import { getClient } from '../server/clients' | |
5 | ||
6 | type Client = { id: string, secret: string } | |
7 | type User = { username: string, password: string } | |
8 | type Server = { url: string, client: Client, user: User } | |
9 | ||
10 | function login (url: string, client: Client, user: User, expectedStatus = 200) { | |
11 | const path = '/api/v1/users/token' | |
12 | ||
13 | const body = { | |
14 | client_id: client.id, | |
15 | client_secret: client.secret, | |
16 | username: user.username, | |
17 | password: user.password, | |
18 | response_type: 'code', | |
19 | grant_type: 'password', | |
20 | scope: 'upload' | |
21 | } | |
22 | ||
23 | return request(url) | |
24 | .post(path) | |
25 | .type('form') | |
26 | .send(body) | |
27 | .expect(expectedStatus) | |
28 | } | |
29 | ||
30 | async function serverLogin (server: Server) { | |
31 | const res = await login(server.url, server.client, server.user, 200) | |
32 | ||
33 | return res.body.access_token as string | |
34 | } | |
35 | ||
36 | async function userLogin (server: Server, user: User, expectedStatus = 200) { | |
37 | const res = await login(server.url, server.client, user, expectedStatus) | |
38 | ||
39 | return res.body.access_token as string | |
40 | } | |
41 | ||
42 | async function getAccessToken (url: string, username: string, password: string) { | |
43 | const resClient = await getClient(url) | |
44 | const client = { | |
45 | id: resClient.body.client_id, | |
46 | secret: resClient.body.client_secret | |
47 | } | |
48 | ||
49 | const user = { username, password } | |
50 | ||
51 | try { | |
52 | const res = await login(url, client, user) | |
53 | return res.body.access_token | |
54 | } catch (err) { | |
55 | throw new Error('Cannot authenticate. Please check your username/password.') | |
56 | } | |
57 | } | |
58 | ||
59 | function setAccessTokensToServers (servers: ServerInfo[]) { | |
60 | const tasks: Promise<any>[] = [] | |
61 | ||
62 | for (const server of servers) { | |
63 | const p = serverLogin(server).then(t => { server.accessToken = t }) | |
64 | tasks.push(p) | |
65 | } | |
66 | ||
67 | return Promise.all(tasks) | |
68 | } | |
69 | ||
70 | // --------------------------------------------------------------------------- | |
71 | ||
72 | export { | |
73 | login, | |
74 | serverLogin, | |
75 | userLogin, | |
76 | getAccessToken, | |
77 | setAccessTokensToServers, | |
78 | Server, | |
79 | Client, | |
80 | User | |
81 | } |