1 import * as request from 'supertest'
3 import { ServerInfo } from '../server/servers'
4 import { getClient } from '../server/clients'
5 import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
7 type Client = { id: string, secret: string }
8 type User = { username: string, password: string }
9 type Server = { url: string, client: Client, user: User }
11 function login (url: string, client: Client, user: User, expectedStatus = HttpStatusCode.OK_200) {
12 const path = '/api/v1/users/token'
16 client_secret: client.secret,
17 username: user.username,
18 password: user.password,
19 response_type: 'code',
20 grant_type: 'password',
28 .expect(expectedStatus)
31 function logout (url: string, token: string, expectedStatus = HttpStatusCode.OK_200) {
32 const path = '/api/v1/users/revoke-token'
36 .set('Authorization', 'Bearer ' + token)
38 .expect(expectedStatus)
41 async function serverLogin (server: Server) {
42 const res = await login(server.url, server.client, server.user, HttpStatusCode.OK_200)
44 return res.body.access_token as string
47 function refreshToken (server: ServerInfo, refreshToken: string, expectedStatus = HttpStatusCode.OK_200) {
48 const path = '/api/v1/users/token'
51 client_id: server.client.id,
52 client_secret: server.client.secret,
53 refresh_token: refreshToken,
54 response_type: 'code',
55 grant_type: 'refresh_token'
58 return request(server.url)
62 .expect(expectedStatus)
65 async function userLogin (server: Server, user: User, expectedStatus = HttpStatusCode.OK_200) {
66 const res = await login(server.url, server.client, user, expectedStatus)
68 return res.body.access_token as string
71 async function getAccessToken (url: string, username: string, password: string) {
72 const resClient = await getClient(url)
74 id: resClient.body.client_id,
75 secret: resClient.body.client_secret
78 const user = { username, password }
81 const res = await login(url, client, user)
82 return res.body.access_token
84 throw new Error('Cannot authenticate. Please check your username/password.')
88 function setAccessTokensToServers (servers: ServerInfo[]) {
89 const tasks: Promise<any>[] = []
91 for (const server of servers) {
92 const p = serverLogin(server).then(t => { server.accessToken = t })
96 return Promise.all(tasks)
99 function loginUsingExternalToken (server: Server, username: string, externalAuthToken: string, expectedStatus = HttpStatusCode.OK_200) {
100 const path = '/api/v1/users/token'
103 client_id: server.client.id,
104 client_secret: server.client.secret,
106 response_type: 'code',
107 grant_type: 'password',
112 return request(server.url)
116 .expect(expectedStatus)
119 // ---------------------------------------------------------------------------
128 setAccessTokensToServers,
132 loginUsingExternalToken