]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - shared/extra-utils/users/login.ts
Begin auth plugin support
[github/Chocobozzz/PeerTube.git] / shared / extra-utils / users / login.ts
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 function logout (url: string, token: string, expectedStatus = 200) {
31 const path = '/api/v1/users/revoke-token'
32
33 return request(url)
34 .post(path)
35 .set('Authorization', 'Bearer ' + token)
36 .type('form')
37 .expect(expectedStatus)
38 }
39
40 async function serverLogin (server: Server) {
41 const res = await login(server.url, server.client, server.user, 200)
42
43 return res.body.access_token as string
44 }
45
46 async function userLogin (server: Server, user: User, expectedStatus = 200) {
47 const res = await login(server.url, server.client, user, expectedStatus)
48
49 return res.body.access_token as string
50 }
51
52 async function getAccessToken (url: string, username: string, password: string) {
53 const resClient = await getClient(url)
54 const client = {
55 id: resClient.body.client_id,
56 secret: resClient.body.client_secret
57 }
58
59 const user = { username, password }
60
61 try {
62 const res = await login(url, client, user)
63 return res.body.access_token
64 } catch (err) {
65 throw new Error('Cannot authenticate. Please check your username/password.')
66 }
67 }
68
69 function setAccessTokensToServers (servers: ServerInfo[]) {
70 const tasks: Promise<any>[] = []
71
72 for (const server of servers) {
73 const p = serverLogin(server).then(t => { server.accessToken = t })
74 tasks.push(p)
75 }
76
77 return Promise.all(tasks)
78 }
79
80 // ---------------------------------------------------------------------------
81
82 export {
83 login,
84 logout,
85 serverLogin,
86 userLogin,
87 getAccessToken,
88 setAccessTokensToServers,
89 Server,
90 Client,
91 User
92 }