diff --git a/app/soapbox/features/ads-token/index.tsx b/app/soapbox/features/ads-token/index.tsx index 532fb5c2d..4beed593a 100644 --- a/app/soapbox/features/ads-token/index.tsx +++ b/app/soapbox/features/ads-token/index.tsx @@ -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 => { + const { data: app } = await api.post('/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 => { + const app = await createAdsApp(); + + const { data: token } = await api.post('/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 = () => { const intl = useIntl(); + const account = useOwnAccount(); const dispatch = useAppDispatch(); - const api = useApi(); + const { obtainAdsToken } = useAdsToken(); const [password, setPassword] = useState(''); const [submitting, setSubmitting] = useState(false); @@ -33,15 +73,16 @@ const AdsToken: React.FC = () => { }; const handleSubmit = () => { - setSubmitting(true); - - api.post('/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 (