Skip to content

refactor: login methods and options #1158

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/__mocks__/state-mocks.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import {
type AuthState,
type EnterpriseAccount,
type GitifyUser,
type SettingsState,
Theme,
} from '../types';
import type { EnterpriseAccount } from '../utils/auth/types';

export const mockEnterpriseAccounts: EnterpriseAccount[] = [
{
Expand Down
168 changes: 91 additions & 77 deletions src/context/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ describe('context/App.tsx', () => {
jest.clearAllMocks();
});

describe('api methods', () => {
const apiRequestAuthMock = jest.spyOn(apiRequests, 'apiRequestAuth');
describe('notification methods', () => {
const getNotificationCountMock = jest.spyOn(
notifications,
'getNotificationCount',
Expand Down Expand Up @@ -269,18 +268,31 @@ describe('context/App.tsx', () => {
'github.com',
);
});
});
describe('authentication methods', () => {
const apiRequestAuthMock = jest.spyOn(apiRequests, 'apiRequestAuth');
const fetchNotificationsMock = jest.fn();

it('should call validateToken', async () => {
beforeEach(() => {
(useNotifications as jest.Mock).mockReturnValue({
fetchNotifications: fetchNotificationsMock,
});
});

it('should call loginWithPersonalAccessToken', async () => {
apiRequestAuthMock.mockResolvedValueOnce(null);

const TestComponent = () => {
const { validateToken } = useContext(AppContext);
const { loginWithPersonalAccessToken } = useContext(AppContext);

return (
<button
type="button"
onClick={() =>
validateToken({ hostname: 'github.com', token: '123-456' })
loginWithPersonalAccessToken({
hostname: 'github.com',
token: '123-456',
})
}
>
Test Case
Expand Down Expand Up @@ -332,90 +344,92 @@ describe('context/App.tsx', () => {
expect(clearStateMock).toHaveBeenCalledTimes(1);
});

it('should call updateSetting', async () => {
const saveStateMock = jest
.spyOn(storage, 'saveState')
.mockImplementation(jest.fn());
describe('settings methods', () => {
it('should call updateSetting', async () => {
const saveStateMock = jest
.spyOn(storage, 'saveState')
.mockImplementation(jest.fn());

const TestComponent = () => {
const { updateSetting } = useContext(AppContext);
const TestComponent = () => {
const { updateSetting } = useContext(AppContext);

return (
<button
type="button"
onClick={() => updateSetting('participating', true)}
>
Test Case
</button>
);
};
return (
<button
type="button"
onClick={() => updateSetting('participating', true)}
>
Test Case
</button>
);
};

const { getByText } = customRender(<TestComponent />);
const { getByText } = customRender(<TestComponent />);

act(() => {
fireEvent.click(getByText('Test Case'));
});
act(() => {
fireEvent.click(getByText('Test Case'));
});

expect(saveStateMock).toHaveBeenCalledWith({
auth: { enterpriseAccounts: [], token: null, user: null },
settings: {
participating: true,
playSound: true,
showNotifications: true,
showBots: true,
showNotificationsCountInTray: false,
openAtStartup: false,
theme: 'SYSTEM',
detailedNotifications: true,
markAsDoneOnOpen: false,
showAccountHostname: false,
delayNotificationState: false,
},
expect(saveStateMock).toHaveBeenCalledWith({
auth: { enterpriseAccounts: [], token: null, user: null },
settings: {
participating: true,
playSound: true,
showNotifications: true,
showBots: true,
showNotificationsCountInTray: false,
openAtStartup: false,
theme: 'SYSTEM',
detailedNotifications: true,
markAsDoneOnOpen: false,
showAccountHostname: false,
delayNotificationState: false,
},
});
});
});

it('should call updateSetting and set auto launch(openAtStartup)', async () => {
const setAutoLaunchMock = jest.spyOn(comms, 'setAutoLaunch');
const saveStateMock = jest
.spyOn(storage, 'saveState')
.mockImplementation(jest.fn());
it('should call updateSetting and set auto launch(openAtStartup)', async () => {
const setAutoLaunchMock = jest.spyOn(comms, 'setAutoLaunch');
const saveStateMock = jest
.spyOn(storage, 'saveState')
.mockImplementation(jest.fn());

const TestComponent = () => {
const { updateSetting } = useContext(AppContext);
const TestComponent = () => {
const { updateSetting } = useContext(AppContext);

return (
<button
type="button"
onClick={() => updateSetting('openAtStartup', true)}
>
Test Case
</button>
);
};
return (
<button
type="button"
onClick={() => updateSetting('openAtStartup', true)}
>
Test Case
</button>
);
};

const { getByText } = customRender(<TestComponent />);
const { getByText } = customRender(<TestComponent />);

act(() => {
fireEvent.click(getByText('Test Case'));
});
act(() => {
fireEvent.click(getByText('Test Case'));
});

expect(setAutoLaunchMock).toHaveBeenCalledWith(true);

expect(saveStateMock).toHaveBeenCalledWith({
auth: { enterpriseAccounts: [], token: null, user: null },
settings: {
participating: false,
playSound: true,
showNotifications: true,
showBots: true,
showNotificationsCountInTray: false,
openAtStartup: true,
theme: 'SYSTEM',
detailedNotifications: true,
markAsDoneOnOpen: false,
showAccountHostname: false,
delayNotificationState: false,
},
expect(setAutoLaunchMock).toHaveBeenCalledWith(true);

expect(saveStateMock).toHaveBeenCalledWith({
auth: { enterpriseAccounts: [], token: null, user: null },
settings: {
participating: false,
playSound: true,
showNotifications: true,
showBots: true,
showNotificationsCountInTray: false,
openAtStartup: true,
theme: 'SYSTEM',
detailedNotifications: true,
markAsDoneOnOpen: false,
showAccountHostname: false,
delayNotificationState: false,
},
});
});
});
});
41 changes: 24 additions & 17 deletions src/context/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,23 @@ import { useInterval } from '../hooks/useInterval';
import { useNotifications } from '../hooks/useNotifications';
import {
type AccountNotifications,
type AuthOptions,
type AuthState,
type AuthTokenOptions,
type GitifyError,
type SettingsState,
type Status,
Theme,
} from '../types';
import { headNotifications } from '../utils/api/client';
import { addAccount, authGitHub, getToken, getUserData } from '../utils/auth';
import type {
LoginOAuthAppOptions,
LoginPersonalAccessTokenOptions,
} from '../utils/auth/types';
import {
addAccount,
authGitHub,
getToken,
getUserData,
} from '../utils/auth/utils';
import { setAutoLaunch, updateTrayTitle } from '../utils/comms';
import Constants from '../utils/constants';
import { getNotificationCount } from '../utils/notifications';
Expand Down Expand Up @@ -49,9 +56,9 @@ export const defaultSettings: SettingsState = {
interface AppContextState {
auth: AuthState;
isLoggedIn: boolean;
login: () => void;
loginEnterprise: (data: AuthOptions) => void;
validateToken: (data: AuthTokenOptions) => void;
loginWithGitHubApp: () => void;
loginWithOAuthApp: (data: LoginOAuthAppOptions) => void;
loginWithPersonalAccessToken: (data: LoginPersonalAccessTokenOptions) => void;
logout: () => void;

notifications: AccountNotifications[];
Expand Down Expand Up @@ -145,7 +152,7 @@ export const AppProvider = ({ children }: { children: ReactNode }) => {
return !!auth.token || auth.enterpriseAccounts.length > 0;
}, [auth]);

const login = useCallback(async () => {
const loginWithGitHubApp = useCallback(async () => {
const { authCode } = await authGitHub();
const { token } = await getToken(authCode);
const hostname = Constants.DEFAULT_AUTH_OPTIONS.hostname;
Expand All @@ -155,8 +162,8 @@ export const AppProvider = ({ children }: { children: ReactNode }) => {
saveState({ auth: updatedAuth, settings });
}, [auth, settings]);

const loginEnterprise = useCallback(
async (data: AuthOptions) => {
const loginWithOAuthApp = useCallback(
async (data: LoginOAuthAppOptions) => {
const { authOptions, authCode } = await authGitHub(data);
const { token, hostname } = await getToken(authCode, authOptions);
const updatedAuth = addAccount(auth, token, hostname);
Expand All @@ -166,14 +173,14 @@ export const AppProvider = ({ children }: { children: ReactNode }) => {
[auth, settings],
);

const validateToken = useCallback(
async ({ token, hostname }: AuthTokenOptions) => {
const loginWithPersonalAccessToken = useCallback(
async ({ token, hostname }: LoginPersonalAccessTokenOptions) => {
await headNotifications(hostname, token);

const user = await getUserData(token, hostname);
const updatedAccounts = addAccount(auth, token, hostname, user);
setAuth(updatedAccounts);
saveState({ auth: updatedAccounts, settings });
const updatedAuth = addAccount(auth, token, hostname, user);
setAuth(updatedAuth);
saveState({ auth: updatedAuth, settings });
},
[auth, settings],
);
Expand Down Expand Up @@ -236,9 +243,9 @@ export const AppProvider = ({ children }: { children: ReactNode }) => {
value={{
auth,
isLoggedIn,
login,
loginEnterprise,
validateToken,
loginWithGitHubApp,
loginWithOAuthApp,
loginWithPersonalAccessToken,
logout,

notifications,
Expand Down
8 changes: 4 additions & 4 deletions src/routes/LoginWithOAuthApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ import { useNavigate } from 'react-router-dom';
import { Button } from '../components/fields/Button';
import { FieldInput } from '../components/fields/FieldInput';
import { AppContext } from '../context/App';
import type { AuthOptions } from '../types';
import type { LoginOAuthAppOptions } from '../utils/auth/types';
import {
getNewOAuthAppURL,
isValidClientId,
isValidHostname,
isValidToken,
} from '../utils/auth';
} from '../utils/auth/utils';
import Constants from '../utils/constants';

interface IValues {
Expand Down Expand Up @@ -59,7 +59,7 @@ export const validate = (values: IValues): IFormErrors => {
export const LoginWithOAuthApp: FC = () => {
const {
auth: { enterpriseAccounts },
loginEnterprise,
loginWithOAuthApp: loginEnterprise,
} = useContext(AppContext);
const navigate = useNavigate();

Expand Down Expand Up @@ -129,7 +129,7 @@ export const LoginWithOAuthApp: FC = () => {

const login = useCallback(async (data: IValues) => {
try {
await loginEnterprise(data as AuthOptions);
await loginEnterprise(data as LoginOAuthAppOptions);
} catch (err) {
// Skip
}
Expand Down
Loading