pleroma/src/actions/oauth.ts

62 lines
2.2 KiB
TypeScript
Raw Normal View History

/**
* OAuth: create and revoke tokens.
* Tokens can be used by users and apps.
* https://docs.joinmastodon.org/methods/apps/oauth/
* @module soapbox/actions/oauth
* @see module:soapbox/actions/auth
*/
import { PlApiClient, type GetTokenParams, type RevokeTokenParams } from 'pl-api';
2023-05-18 08:17:55 -07:00
import * as BuildConfig from 'soapbox/build-config';
import { getBaseURL } from 'soapbox/utils/state';
2021-08-21 17:37:28 -07:00
2023-05-18 09:53:32 -07:00
import type { AppDispatch, RootState } from 'soapbox/store';
const OAUTH_TOKEN_CREATE_REQUEST = 'OAUTH_TOKEN_CREATE_REQUEST';
const OAUTH_TOKEN_CREATE_SUCCESS = 'OAUTH_TOKEN_CREATE_SUCCESS';
const OAUTH_TOKEN_CREATE_FAIL = 'OAUTH_TOKEN_CREATE_FAIL';
2021-08-21 17:37:28 -07:00
const OAUTH_TOKEN_REVOKE_REQUEST = 'OAUTH_TOKEN_REVOKE_REQUEST';
const OAUTH_TOKEN_REVOKE_SUCCESS = 'OAUTH_TOKEN_REVOKE_SUCCESS';
const OAUTH_TOKEN_REVOKE_FAIL = 'OAUTH_TOKEN_REVOKE_FAIL';
2021-08-21 17:37:28 -07:00
const obtainOAuthToken = (params: GetTokenParams, baseURL?: string) =>
(dispatch: AppDispatch) => {
2021-08-21 17:37:28 -07:00
dispatch({ type: OAUTH_TOKEN_CREATE_REQUEST, params });
const client = new PlApiClient(baseURL || BuildConfig.BACKEND_URL || '', undefined, { fetchInstance: false });
return client.oauth.getToken(params).then((token) => {
2021-08-21 17:37:28 -07:00
dispatch({ type: OAUTH_TOKEN_CREATE_SUCCESS, params, token });
return token;
}).catch(error => {
dispatch({ type: OAUTH_TOKEN_CREATE_FAIL, params, error, skipAlert: true });
2021-08-21 17:37:28 -07:00
throw error;
});
};
const revokeOAuthToken = (params: RevokeTokenParams) =>
2023-05-18 08:17:55 -07:00
(dispatch: AppDispatch, getState: () => RootState) => {
2021-08-21 17:37:28 -07:00
dispatch({ type: OAUTH_TOKEN_REVOKE_REQUEST, params });
2023-05-18 08:17:55 -07:00
const baseURL = getBaseURL(getState());
const client = new PlApiClient(baseURL || '', undefined, { fetchInstance: false });
return client.oauth.revokeToken(params).then((data) => {
2021-08-21 17:37:28 -07:00
dispatch({ type: OAUTH_TOKEN_REVOKE_SUCCESS, params, data });
return data;
}).catch(error => {
dispatch({ type: OAUTH_TOKEN_REVOKE_FAIL, params, error });
throw error;
});
};
export {
OAUTH_TOKEN_CREATE_REQUEST,
OAUTH_TOKEN_CREATE_SUCCESS,
OAUTH_TOKEN_CREATE_FAIL,
OAUTH_TOKEN_REVOKE_REQUEST,
OAUTH_TOKEN_REVOKE_SUCCESS,
OAUTH_TOKEN_REVOKE_FAIL,
obtainOAuthToken,
revokeOAuthToken,
};