]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - shared/extra-utils/users/login.ts
Merge branch 'release/2.1.0' into develop
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / users / login.ts
CommitLineData
0e1dc3e7
C
1import * as request from 'supertest'
2
c5d31dba 3import { ServerInfo } from '../server/servers'
8d2be0ed 4import { getClient } from '../server/clients'
0e1dc3e7
C
5
6type Client = { id: string, secret: string }
7type User = { username: string, password: string }
8type Server = { url: string, client: Client, user: User }
9
10function 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
eec63bbc 30async function serverLogin (server: Server) {
0e1dc3e7
C
31 const res = await login(server.url, server.client, server.user, 200)
32
33 return res.body.access_token as string
34}
35
f8b8c36b
C
36async function userLogin (server: Server, user: User, expectedStatus = 200) {
37 const res = await login(server.url, server.client, user, expectedStatus)
0e1dc3e7
C
38
39 return res.body.access_token as string
40}
41
8d2be0ed
C
42async 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
0e1dc3e7
C
59function setAccessTokensToServers (servers: ServerInfo[]) {
60 const tasks: Promise<any>[] = []
61
62 for (const server of servers) {
a1587156 63 const p = serverLogin(server).then(t => { server.accessToken = t })
0e1dc3e7
C
64 tasks.push(p)
65 }
66
67 return Promise.all(tasks)
68}
69
70// ---------------------------------------------------------------------------
71
72export {
73 login,
eec63bbc
C
74 serverLogin,
75 userLogin,
8d2be0ed 76 getAccessToken,
c1e791ba
RK
77 setAccessTokensToServers,
78 Server,
79 Client,
80 User
0e1dc3e7 81}