1 import { HttpStatusCode } from '@shared/core-utils'
2 import { PeerTubeProblemDocument } from '@shared/models'
3 import { unwrapBody } from '../requests'
4 import { AbstractCommand, OverrideCommandOptions } from '../shared'
6 export class LoginCommand extends AbstractCommand {
8 login (options: OverrideCommandOptions & {
9 client?: { id?: string, secret?: string }
10 user?: { username: string, password?: string }
12 const { client = this.server.store.client, user = this.server.store.user } = options
13 const path = '/api/v1/users/token'
17 client_secret: client.secret,
18 username: user.username,
19 password: user.password ?? 'password',
20 response_type: 'code',
21 grant_type: 'password',
25 return unwrapBody<{ access_token: string, refresh_token: string } & PeerTubeProblemDocument>(this.postBodyRequest({
32 defaultExpectedStatus: HttpStatusCode.OK_200
36 getAccessToken (arg1?: { username: string, password?: string }): Promise<string>
37 getAccessToken (arg1: string, password?: string): Promise<string>
38 async getAccessToken (arg1?: { username: string, password?: string } | string, password?: string) {
39 let user: { username: string, password?: string }
41 if (!arg1) user = this.server.store.user
42 else if (typeof arg1 === 'object') user = arg1
43 else user = { username: arg1, password }
46 const body = await this.login({ user })
48 return body.access_token
50 throw new Error(`Cannot authenticate. Please check your username/password. (${err})`)
54 loginUsingExternalToken (options: OverrideCommandOptions & {
56 externalAuthToken: string
58 const { username, externalAuthToken } = options
59 const path = '/api/v1/users/token'
62 client_id: this.server.store.client.id,
63 client_secret: this.server.store.client.secret,
65 response_type: 'code',
66 grant_type: 'password',
71 return this.postBodyRequest({
78 defaultExpectedStatus: HttpStatusCode.OK_200
82 logout (options: OverrideCommandOptions & {
85 const path = '/api/v1/users/revoke-token'
87 return unwrapBody<{ redirectUrl: string }>(this.postBodyRequest({
93 defaultExpectedStatus: HttpStatusCode.OK_200
97 refreshToken (options: OverrideCommandOptions & {
100 const path = '/api/v1/users/token'
103 client_id: this.server.store.client.id,
104 client_secret: this.server.store.client.secret,
105 refresh_token: options.refreshToken,
106 response_type: 'code',
107 grant_type: 'refresh_token'
110 return this.postBodyRequest({
116 implicitToken: false,
117 defaultExpectedStatus: HttpStatusCode.OK_200
121 getClient (options: OverrideCommandOptions = {}) {
122 const path = '/api/v1/oauth-clients/local'
124 return this.getRequestBody<{ client_id: string, client_secret: string }>({
128 host: this.server.host,
129 implicitToken: false,
130 defaultExpectedStatus: HttpStatusCode.OK_200