Skip to content

Commit

Permalink
Merge branch 'bugfix-oauth-401'
Browse files Browse the repository at this point in the history
  • Loading branch information
insomnious committed Jul 27, 2023
2 parents fd6aac8 + 3252b69 commit 20c5a43
Show file tree
Hide file tree
Showing 7 changed files with 73 additions and 114 deletions.
27 changes: 0 additions & 27 deletions src/extensions/nexus_integration/eventHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ import * as semver from 'semver';
import { format as urlFormat } from 'url';
import { ITokenReply } from './util/oauth';
import { isLoggedIn } from './selectors';
//import { getUserInfo } from './util/api';

export function onChangeDownloads(api: IExtensionApi, nexus: Nexus) {
const state: IState = api.store.getState();
Expand Down Expand Up @@ -99,32 +98,6 @@ export function onChangeDownloads(api: IExtensionApi, nexus: Nexus) {
updateDebouncer.schedule(undefined, newValue);
}

/*
export function onForceTokenRefresh(api: IExtensionApi, nexus: Nexus) {
return () => {
log('info', 'onForceTokenRefresh');
// limit lifetime of state
const state = api.getState();
//const Nexus: typeof NexusT = require('@nexusmods/nexus-api').default;
const apiKey = state.confidential.account?.['nexus']?.['APIKey'];
const oauthCred = state.confidential.account?.['nexus']?.['OAuthCredentials'];
log('info', 'api key', { isUndefined: apiKey !== undefined });
log('info', 'oauth cred', { isUndefined: oauthCred !== undefined });
if (oauthCred !== undefined) {
log('info', 'nexus.forceJwtRefresh()');
nexus.forceJwtRefresh();
}
}
}*/



/**
* callback for when mods are changed
*
Expand Down
40 changes: 25 additions & 15 deletions src/extensions/nexus_integration/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ import { NEXUS_API_SUBDOMAIN, NEXUS_BASE_URL, NEXUS_DOMAIN,
import * as eh from './eventHandlers';
import NXMUrl from './NXMUrl';
import * as sel from './selectors';
import { bringToFront, endorseThing, ensureLoggedIn, getCollectionInfo, getInfo, getOAuthTokenFromState, getUserInfo, IRemoteInfo,
import { bringToFront, endorseThing, ensureLoggedIn, getCollectionInfo, getInfo, getOAuthTokenFromState, IRemoteInfo,
nexusGames, nexusGamesProm, oauthCallback, onCancelLoginImpl,
processErrorMessage, requestLogin, retrieveNexusGames, startDownload, transformUserInfoFromApi, updateKey, updateToken } from './util';
import { checkModVersion } from './util/checkModsVersion';
Expand Down Expand Up @@ -582,7 +582,7 @@ function makeNXMLinkCallback(api: IExtensionApi) {
} else if (nxmUrl.type === 'premium') {
try {
log('info', 'makeNXMLinkCallback() premium');
api.events.emit('refresh-user-info');
userInfoDebouncer.schedule();
return false;
} catch (err) {
// ignore unexpected code
Expand Down Expand Up @@ -944,12 +944,6 @@ function once(api: IExtensionApi, callbacks: Array<(nexus: NexusT) => void>) {

const gameMode = activeGameId(state);

userInfoDebouncer = new Debouncer(() => {
console.log('debouncer ');
api.events.emit('refresh-user-info');
return Promise.resolve();
}, 10000, true, true);

nexus = new Proxy(
new Proxy(
new Nexus('Vortex', getApplication().version, nexusGameId(getGame(gameMode)), 30000),
Expand Down Expand Up @@ -1022,8 +1016,6 @@ function once(api: IExtensionApi, callbacks: Array<(nexus: NexusT) => void>) {
});
});



// register when window is focussed to do a userinfo check?
getApplication().window.on('focus', (event, win) => {
console.log('browser-window-focus');
Expand All @@ -1043,7 +1035,6 @@ function once(api: IExtensionApi, callbacks: Array<(nexus: NexusT) => void>) {
api.onAsync('get-latest-mods', eh.onGetLatestMods(api, nexus));
api.onAsync('get-trending-mods', eh.onGetTrendingMods(api, nexus));
api.events.on('refresh-user-info', eh.onRefreshUserInfo(nexus, api));
//api.events.on('force-token-refresh', eh.onForceTokenRefresh(api, nexus));
api.events.on('endorse-mod', eh.onEndorseMod(api, nexus));
api.events.on('submit-feedback', eh.onSubmitFeedback(nexus));
api.events.on('submit-collection', eh.onSubmitCollection(nexus));
Expand Down Expand Up @@ -1356,6 +1347,8 @@ function makeNXMProtocol(api: IExtensionApi, onAwaitLink: AwaitLinkCB) {

log('warn', 'userInfo checking for downloads?');



const userInfo: any = getSafe(state, ['persistent', 'nexus', 'userInfo'], undefined);
if ((url.userId !== undefined) && (url.userId !== userInfo?.userId)) {
const userName: string =
Expand Down Expand Up @@ -1427,7 +1420,7 @@ function onSkip(inputUrl: string) {
}
}

function onRetryImpl(resolveFunc: ResolveFunc, inputUrl: string) {
function onRetryImpl(resolveFunc: ResolveFunc, api: IExtensionApi, inputUrl: string) {
const queueItem = freeDLQueue.find(iter => iter.input === inputUrl);
if (queueItem === undefined) {
log('error', 'failed to find queue item', { inputUrl, queue: JSON.stringify(freeDLQueue) });
Expand All @@ -1436,10 +1429,13 @@ function onRetryImpl(resolveFunc: ResolveFunc, inputUrl: string) {

const { url } = queueItem;


resolveFunc(queueItem.input)
.then(queueItem.res)
.catch(queueItem.rej);



/*
const awaitedLink = {
gameId: url.gameId,
Expand All @@ -1458,6 +1454,10 @@ function onRetryImpl(resolveFunc: ResolveFunc, inputUrl: string) {
//console.log('awaitedLink', JSON.stringify(awaitedLink));
}

function onCheckStatusImpl() {

userInfoDebouncer.schedule();
}

function onCancelImpl(api: IExtensionApi, inputUrl: string): boolean {
const copy = freeDLQueue.slice(0);
Expand Down Expand Up @@ -1537,9 +1537,16 @@ function init(context: IExtensionContextExt): boolean {
context.api.store.dispatch(clearOAuthCredentials(null));
});*/


userInfoDebouncer = new Debouncer(() => {
console.log('debouncer');
context.api.events.emit('refresh-user-info');
return Promise.resolve();
}, 1000, true, true);

context.registerAction('global-icons', 100, 'nexus', {}, 'Refresh User Info', () => {
log('info', 'Refresh User Info');
context.api.events.emit('refresh-user-info');
userInfoDebouncer.schedule();
});

context.registerAction('mods-action-icons', 300, 'smart', {}, 'Fix missing IDs',
Expand Down Expand Up @@ -1582,8 +1589,10 @@ function init(context: IExtensionContextExt): boolean {
const onDownload = (inputUrl: string) => onDownloadImpl(resolveFunc, inputUrl);

const onCancel = (inputUrl: string) => onCancelImpl(context.api, inputUrl);

const onCheckStatus = () => onCheckStatusImpl();

const onRetry = (inputUrl: string) => onRetryImpl(resolveFunc, inputUrl);
const onRetry = (inputUrl: string) => onRetryImpl(resolveFunc, context.api, inputUrl);

context.registerDialog('free-user-download', FreeUserDLDialog, () => ({
t: context.api.translate,
Expand All @@ -1592,7 +1601,8 @@ function init(context: IExtensionContextExt): boolean {
onDownload,
onSkip,
onCancel,
onRetry
onRetry,
onCheckStatus
}));

context.registerBanner('downloads', () => {
Expand Down
37 changes: 14 additions & 23 deletions src/extensions/nexus_integration/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ import OAuth, { ITokenReply } from './util/oauth';
import { IAccountStatus, IValidateKeyData, IValidateKeyDataV2 } from './types/IValidateKeyData';
import { getPageURL } from './util/sso';
import transformUserInfo from './util/transformUserInfo';
import * as NexusAPI from './util/api';

const remote = lazyRequire<typeof RemoteT>(() => require('@electron/remote'));

Expand All @@ -66,6 +65,16 @@ interface INexusLoginMessage {
token?: string;
}

interface IUserInfo {
sub: string;
name: string;
email: string;
avatar: string;
group_id: number;
membership_roles: string[];
premium_expiry: number;
}

let cancelLogin: () => void;

export function onCancelLoginImpl(api: IExtensionApi) {
Expand Down Expand Up @@ -251,15 +260,9 @@ export function requestLogin(nexus: Nexus, api: IExtensionApi, callback: (err: E
return callback(err);
}


const tokenDecoded: IJWTAccessToken = jwt.decode(token.access_token);

api.store.dispatch(setOAuthCredentials(token.access_token, token.refresh_token, tokenDecoded.fingerprint));

//const apiUserInfo = await getUserInfo(nexus);

//api.store.dispatch(setUserInfo(transformUserInfoFromApi(apiUserInfo)));
//log('info', 'apiUserInfo', apiUserInfo);

callback(null);

Expand Down Expand Up @@ -403,20 +406,7 @@ function startDownloadCollection(api: IExtensionApi,
});
}

/*
export function getUserInfo(token:string) : Promise<NexusAPI.IUserInfo> {
return Promise.resolve((async () => {
try {
const userInfo = await NexusAPI.getUserInfo(token);
return userInfo;
} catch (err) {
err['attachLogOnReport'] = true;
throw err;
}
})());
}*/

export function getUserInfo(nexus: Nexus) : Promise<NexusAPI.IUserInfo> {
export function getUserInfo(nexus: Nexus) : Promise<IUserInfo> {
return Promise.resolve((async () => {
try {
const userInfo = await nexus.getUserInfo();
Expand All @@ -428,6 +418,7 @@ export function getUserInfo(nexus: Nexus) : Promise<NexusAPI.IUserInfo> {
})());
}


export interface IRemoteInfo {
modInfo?: IModInfo;
fileInfo?: IFileInfo;
Expand Down Expand Up @@ -1268,7 +1259,7 @@ function errorFromNexusError(err: NexusError): string {
}


function getAccountStatus(apiUserInfo:NexusAPI.IUserInfo):IAccountStatus {
function getAccountStatus(apiUserInfo:IUserInfo):IAccountStatus {

if(apiUserInfo.group_id === 5) return IAccountStatus.Banned;
else if(apiUserInfo.group_id === 41) return IAccountStatus.Closed;
Expand All @@ -1277,7 +1268,7 @@ function getAccountStatus(apiUserInfo:NexusAPI.IUserInfo):IAccountStatus {
else return IAccountStatus.Free;
}

export function transformUserInfoFromApi(input: NexusAPI.IUserInfo) {
export function transformUserInfoFromApi(input: IUserInfo) {

const stateUserInfo:IValidateKeyDataV2 = {
email: input.email,
Expand Down
42 changes: 0 additions & 42 deletions src/extensions/nexus_integration/util/api.ts

This file was deleted.

11 changes: 9 additions & 2 deletions src/extensions/nexus_integration/views/FreeUserDLDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ interface IFreeUserDLDialogProps {
onCancel: (url: string) => boolean;
onUpdated: () => void;
onRetry: (url: string) => void;
onCheckStatus: () => void;
}

const FILE_QUERY: IModFileQuery = {
Expand Down Expand Up @@ -83,10 +84,12 @@ function nop() {

function FreeUserDLDialog(props: IFreeUserDLDialogProps) {

const { t, nexus, onCancel, onDownload, onSkip, onUpdated, onRetry } = props;
const { t, nexus, onCancel, onDownload, onSkip, onUpdated, onRetry, onCheckStatus } = props;

//return oauthCred !== undefined ? oauthCred.token : undefined;



const urls: string[] = useSelector<IState, string[]>(state =>
state.session['nexus'].freeUserDLQueue);

Expand Down Expand Up @@ -135,6 +138,10 @@ function FreeUserDLDialog(props: IFreeUserDLDialogProps) {
}
}, [urls]);

const checkStatus = React.useCallback(() => {
onCheckStatus();
}, [])

const retry = React.useCallback(() => {
onRetry(urls[0]);
}, [onRetry, urls]);
Expand Down Expand Up @@ -203,7 +210,7 @@ function FreeUserDLDialog(props: IFreeUserDLDialogProps) {
) : null}
</FlexLayout.Flex>
</FlexLayout>
<PremiumNagBanner t={t} onDownload={download} campaign={campaign} />
<PremiumNagBanner t={t} onCheckStatus={checkStatus} onDownload={download} campaign={campaign} />
</Panel>
</Modal.Body>
<Modal.Footer>
Expand Down
3 changes: 0 additions & 3 deletions src/extensions/nexus_integration/views/LoginIcon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,6 @@ class LoginIcon extends ComponentEx<IProps, {}> {
private showLoginLayer = async () => {
const { userInfo } = this.props;

//this.context.api.events.emit('force-token-refresh');
//this.context.api.events.emit('refresh-user-info');

if (!this.isLoggedIn()) {
this.context.api.events.emit('analytics-track-click-event', 'Profile', 'Site profile');
this.setDialogVisible(true);
Expand Down
Loading

0 comments on commit 20c5a43

Please sign in to comment.