AdsToken: make the form actually work

ads-token
Alex Gleason 2022-11-15 14:00:12 -06:00
rodzic e5d11c2415
commit 9bd7c52244
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 7211D1F99744FBB7
1 zmienionych plików z 52 dodań i 11 usunięć

Wyświetl plik

@ -4,25 +4,65 @@ import { defineMessages, FormattedMessage, useIntl } from 'react-intl';
import snackbar from 'soapbox/actions/snackbar';
import CopyableInput from 'soapbox/components/copyable-input';
import { Column, Stack, Form, FormGroup, Input, Text, FormActions, Button } from 'soapbox/components/ui';
import { useApi, useAppDispatch } from 'soapbox/hooks';
import { useApi, useAppDispatch, useOwnAccount } from 'soapbox/hooks';
const messages = defineMessages({
heading: { id: 'column.ads_token.heading', defaultMessage: 'Advertiser Token' },
error: { id: 'ads_token.error', defaultMessage: 'There was a problem obtaining the token. Are you sure your password is correct?' },
});
interface OAuthApp {
client_id: string,
client_secret: string,
}
interface OAuthToken {
access_token: string,
}
const useAdsToken = () => {
const api = useApi();
const createAdsApp = async(): Promise<OAuthApp> => {
const { data: app } = await api.post<OAuthApp>('/api/v1/apps', {
client_name: 'Soapbox Ads',
redirect_uris: 'urn:ietf:wg:oauth:2.0:oob',
scopes: 'ads',
});
return app;
};
const obtainAdsToken = async(username: string, password: string): Promise<OAuthToken> => {
const app = await createAdsApp();
const { data: token } = await api.post<OAuthToken>('/oauth/token', {
grant_type: 'password',
client_id: app.client_id,
client_secret: app.client_secret,
redirect_uri: 'urn:ietf:wg:oauth:2.0:oob',
scope: 'ads',
username,
password,
});
return token;
};
return {
obtainAdsToken,
};
};
interface IAdsToken {
}
/** Obtains an OAuth token with `ads` scope only. */
const AdsToken: React.FC<IAdsToken> = () => {
const intl = useIntl();
const account = useOwnAccount();
const dispatch = useAppDispatch();
const api = useApi();
const { obtainAdsToken } = useAdsToken();
const [password, setPassword] = useState<string>('');
const [submitting, setSubmitting] = useState(false);
@ -33,15 +73,16 @@ const AdsToken: React.FC<IAdsToken> = () => {
};
const handleSubmit = () => {
setSubmitting(true);
api.post<OAuthToken>('/oauth/token', {}).then(({ data }) => {
setToken(data.access_token);
setSubmitting(false);
}).catch(() => {
dispatch(snackbar.error(intl.formatMessage(messages.error)));
setSubmitting(false);
});
if (account && password) {
setSubmitting(true);
obtainAdsToken(account.username, password).then(token => {
setToken(token.access_token);
setSubmitting(false);
}).catch(() => {
dispatch(snackbar.error(intl.formatMessage(messages.error)));
setSubmitting(false);
});
}
};
return (