pleroma/src/actions/oauth.ts

64 lines
2.1 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
*/
2023-05-18 08:17:55 -07:00
import { getBaseURL } from 'soapbox/utils/state';
import { getFetch } from '../api';
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: Record<string, string | undefined>, baseURL?: string) =>
(dispatch: AppDispatch) => {
2021-08-21 17:37:28 -07:00
dispatch({ type: OAUTH_TOKEN_CREATE_REQUEST, params });
return getFetch(null, baseURL)('/oauth/token', {
method: 'POST',
body: JSON.stringify(params),
}).then(({ json: 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: Record<string, string>) =>
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());
return getFetch(null, baseURL)('/oauth/revoke', {
method: 'POST',
body: JSON.stringify(params),
}).then(({ json: 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,
};