chore: get api key from coookie

This commit is contained in:
Sebastian Velez
2023-02-15 12:25:19 -05:00
parent ffd2a48b29
commit 00209ec96f
5 changed files with 35 additions and 4 deletions

View File

@@ -4,7 +4,7 @@ import axios, { AxiosResponse } from 'axios';
import moment from 'moment'; import moment from 'moment';
import browser, { Tabs } from 'webextension-polyfill'; import browser, { Tabs } from 'webextension-polyfill';
import { IDBPDatabase, openDB } from 'idb'; import { IDBPDatabase, openDB } from 'idb';
import { AxiosUserResponse, User } from '../types/user'; import { ApiKeyPayload, AxiosUserResponse, User } from '../types/user';
import config from '../config/config'; import config from '../config/config';
import { SummariesPayload, GrandTotal } from '../types/summaries'; import { SummariesPayload, GrandTotal } from '../types/summaries';
import changeExtensionState from '../utils/changeExtensionState'; import changeExtensionState from '../utils/changeExtensionState';
@@ -63,6 +63,22 @@ class WakaTimeCore {
return summariesAxiosPayload.data.data[0].grand_total; return summariesAxiosPayload.data.data[0].grand_total;
} }
/**
* Fetches the api token for logged users in wakatime website
*
* @returns {*}
*/
async fetchApiKey(): Promise<string> {
try {
const apiKeyResponse: AxiosResponse<ApiKeyPayload> = await axios.post(
`${config.currentUserApiUrl}/get_api_key`,
);
return apiKeyResponse.data.data.api_key;
} catch (err: unknown) {
return '';
}
}
/** /**
* Checks if the user is logged in. * Checks if the user is logged in.
* *

View File

@@ -26,5 +26,5 @@
"page": "options.html" "page": "options.html"
}, },
"permissions": ["alarms", "tabs", "storage", "idle"], "permissions": ["alarms", "tabs", "storage", "idle"],
"version": "3.0.1" "version": "3.0.2"
} }

View File

@@ -52,3 +52,11 @@ export interface CurrentUser {
pending?: boolean; pending?: boolean;
user?: User; user?: User;
} }
export interface ApiKeyPayload {
data: ApiKey;
}
export interface ApiKey {
api_key: string;
}

View File

@@ -8,8 +8,8 @@ export default (store: Store<RootState>) =>
(time: number): unsub => { (time: number): unsub => {
const fetchUser = () => { const fetchUser = () => {
const apiKey: string = (store.getState() as ReduxSelector).config.apiKey; const apiKey: string = (store.getState() as ReduxSelector).config.apiKey;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error // @ts-expect-error be able to dispatch async thunk
store.dispatch(fetchCurrentUser(apiKey)); store.dispatch(fetchCurrentUser(apiKey));
}; };
fetchUser(); fetchUser();

View File

@@ -34,6 +34,13 @@ export const fetchUserData = async (
apiKey: config.apiKey, apiKey: config.apiKey,
}); });
apiKey = storage.apiKey as string; apiKey = storage.apiKey as string;
if (!apiKey) {
apiKey = await WakaTimeCore.fetchApiKey();
if (apiKey) {
await browser.storage.sync.set({ apiKey });
}
}
dispatch(setApiKey(apiKey)); dispatch(setApiKey(apiKey));
} }