1 import { PeerTubeRequestError } from '@server/helpers/requests'
2 import { HttpStatusCode } from '@shared/core-utils'
3 import { PeerTubeProblemDocument } from '@shared/models'
4 import { unwrapBody } from '../requests'
5 import { AbstractCommand, OverrideCommandOptions } from '../shared'
7 export class LoginCommand extends AbstractCommand {
9 login (options: OverrideCommandOptions & {
10 client?: { id?: string, secret?: string }
11 user?: { username: string, password: string }
13 const { client = this.server.client, user = this.server.user } = options
14 const path = '/api/v1/users/token'
18 client_secret: client.secret,
19 username: user.username,
20 password: user.password,
21 response_type: 'code',
22 grant_type: 'password',
26 return unwrapBody<{ access_token: string, refresh_token: string } & PeerTubeProblemDocument>(this.postBodyRequest({
33 defaultExpectedStatus: HttpStatusCode.OK_200
37 getAccessToken (user?: { username: string, password: string }): Promise<string>
38 getAccessToken (username: string, password: string): Promise<string>
39 async getAccessToken (arg1?: { username: string, password: string } | string, password?: string) {
40 let user: { username: string, password: string }
42 if (!arg1) user = this.server.user
43 else if (typeof arg1 === 'object') user = arg1
44 else user = { username: arg1, password }
47 const body = await this.login({ user })
49 return body.access_token
51 throw new Error('Cannot authenticate. Please check your username/password.')
55 loginUsingExternalToken (options: OverrideCommandOptions & {
57 externalAuthToken: string
59 const { username, externalAuthToken } = options
60 const path = '/api/v1/users/token'
63 client_id: this.server.client.id,
64 client_secret: this.server.client.secret,
66 response_type: 'code',
67 grant_type: 'password',
72 return this.postBodyRequest({
79 defaultExpectedStatus: HttpStatusCode.OK_200
83 logout (options: OverrideCommandOptions & {
86 const path = '/api/v1/users/revoke-token'
88 return unwrapBody<{ redirectUrl: string }>(this.postBodyRequest({
94 defaultExpectedStatus: HttpStatusCode.OK_200
98 refreshToken (options: OverrideCommandOptions & {
101 const path = '/api/v1/users/token'
104 client_id: this.server.client.id,
105 client_secret: this.server.client.secret,
106 refresh_token: options.refreshToken,
107 response_type: 'code',
108 grant_type: 'refresh_token'
111 return this.postBodyRequest({
117 implicitToken: false,
118 defaultExpectedStatus: HttpStatusCode.OK_200
122 getClient (options: OverrideCommandOptions = {}) {
123 const path = '/api/v1/oauth-clients/local'
125 return this.getRequestBody<{ client_id: string, client_secret: string }>({
129 host: this.server.host,
130 implicitToken: false,
131 defaultExpectedStatus: HttpStatusCode.OK_200