-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(login): add login redirect (#5)
* use alias * add LoginButton, cookie handling * get code verifier on query param * fix styles * add config, url found * minor change * moved * update to @lib * add test and fix * mock cookies and fixes * clean up * refactor and add test * fix test * update test env * linter fix
- Loading branch information
Showing
26 changed files
with
446 additions
and
196 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
VITE_AUTH_URL=http://test-auth-api/api/authorize | ||
VITE_TOKEN_URL=http://test-token-api/api/oauth/token | ||
VITE_BASE_URL=http://test-base-url |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,6 +11,7 @@ node_modules | |
dist | ||
dist-ssr | ||
*.local | ||
!.env.test.local | ||
|
||
# Editor directories and files | ||
.vscode/* | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +0,0 @@ | ||
# React + TypeScript + Vite | ||
|
||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. | ||
|
||
Currently, two official plugins are available: | ||
|
||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh | ||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh | ||
|
||
## Expanding the ESLint configuration | ||
|
||
If you are developing a production application, we recommend updating the configuration to enable type aware lint rules: | ||
|
||
- Configure the top-level `parserOptions` property like this: | ||
|
||
```js | ||
export default { | ||
// other rules... | ||
parserOptions: { | ||
ecmaVersion: 'latest', | ||
sourceType: 'module', | ||
project: ['./tsconfig.json', './tsconfig.node.json'], | ||
tsconfigRootDir: __dirname, | ||
}, | ||
} | ||
``` | ||
|
||
- Replace `plugin:@typescript-eslint/recommended` to `plugin:@typescript-eslint/recommended-type-checked` or `plugin:@typescript-eslint/strict-type-checked` | ||
- Optionally add `plugin:@typescript-eslint/stylistic-type-checked` | ||
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends` list | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
import { describe, test, expect, beforeAll, afterAll, vi, afterEach } from 'vitest' | ||
import { saveCookie, getCookie, deleteCookie, clearAllCookies } from '../cookie' | ||
|
||
describe('cookie', () => { | ||
let mockCookie = [] | ||
beforeAll(() => { | ||
vi.stubGlobal('document', { | ||
get cookie() { | ||
return mockCookie.join(';') | ||
}, | ||
set cookie(value) { | ||
mockCookie = mockCookie.filter(c => !c.startsWith(value.split('=')[0])) | ||
mockCookie.push(value) | ||
}, | ||
}) | ||
}) | ||
|
||
afterEach(() => { | ||
mockCookie = [] | ||
}) | ||
|
||
afterAll(() => { | ||
vi.unstubAllGlobals() | ||
}) | ||
|
||
describe('saveCookie', () => { | ||
test('throws error on empty name', () => { | ||
expect(() => saveCookie()).toThrowError('Cookie name is required') | ||
}) | ||
|
||
test('saves empty value', () => { | ||
saveCookie('a', '') | ||
expect(document.cookie).toMatch('a=;') | ||
}) | ||
|
||
test('saves cookie', () => { | ||
saveCookie('a', '1234') | ||
expect(document.cookie).toMatch('a=1234;') | ||
}) | ||
|
||
test('saves cookie with latest value', () => { | ||
saveCookie('a', '1234') | ||
saveCookie('a', '124') | ||
expect(document.cookie).toMatch('a=124;') | ||
expect(document.cookie).not.toMatch('a=1234;') | ||
}) | ||
}) | ||
|
||
describe('getCookie', () => { | ||
test('gets none', () => { | ||
saveCookie('b', '54321') | ||
expect(getCookie('c')).toBeUndefined() | ||
}) | ||
|
||
test('gets cookie', () => { | ||
saveCookie('b', '54321') | ||
expect(getCookie('b')).toBe('54321') | ||
}) | ||
}) | ||
|
||
describe('deleteCookie', () => { | ||
test('deletes cookie', () => { | ||
saveCookie('a', '12345') | ||
expect(document.cookie).toMatch('a=12345;') | ||
|
||
deleteCookie('a') | ||
expect(document.cookie).toMatch('a=;') | ||
}) | ||
|
||
test('deletes cookie without affecting others', () => { | ||
saveCookie('a', '12345') | ||
expect(document.cookie).toMatch('a=12345;') | ||
|
||
saveCookie('b', '54321') | ||
expect(document.cookie).toMatch('b=54321;') | ||
|
||
deleteCookie('a') | ||
expect(document.cookie).toMatch('a=;') | ||
expect(document.cookie).toMatch('b=54321;') | ||
}) | ||
|
||
test('deletes none', () => { | ||
saveCookie('a', '12345') | ||
saveCookie('b', '54321') | ||
deleteCookie('c') | ||
expect(document.cookie).toMatch('a=12345;') | ||
expect(document.cookie).toMatch('b=54321;') | ||
}) | ||
}) | ||
|
||
describe('clearAllCookies', () => { | ||
test('clears all cookies', () => { | ||
saveCookie('a', '12345') | ||
saveCookie('b', '54321') | ||
clearAllCookies() | ||
expect(document.cookie).toMatch('a=;') | ||
expect(document.cookie).toMatch('b=;') | ||
}) | ||
}) | ||
}) |
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
export const saveCookie = (name: string, value: string, mins: number = 60) => { | ||
if (!name) | ||
throw new Error('Cookie name is required') | ||
|
||
const date = new Date() | ||
date.setTime(date.getTime() + mins * 60 * 1000) | ||
document.cookie = | ||
`${name}=${value};Expires=${date.toUTCString()}; \ | ||
path=/; Secure; SameSite=Strict` | ||
} | ||
|
||
export const getCookie = (name: string) => { | ||
const value = `; ${document.cookie}` | ||
const parts = value.split(`; ${name}=`) | ||
if (parts.length === 2) return parts.pop()?.split(';').shift() | ||
} | ||
|
||
export const deleteCookie = (name: string) => { | ||
document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT` | ||
} | ||
|
||
export const clearAllCookies = () => { | ||
const cookies = document.cookie.split(";") | ||
for (let i = 0; i < cookies.length; i++) { | ||
const cookie = cookies[i] | ||
const eqPos = cookie.indexOf("=") | ||
const name = eqPos > -1 ? cookie.substring(0, eqPos) : cookie | ||
document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT` | ||
} | ||
} |
File renamed without changes.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import useInitPKCE from '@/hooks/useInitPKCE' | ||
|
||
const LoginButton = () => { | ||
const { error, onLogin } = useInitPKCE() | ||
|
||
return ( | ||
<> | ||
<button type="submit" onClick={onLogin}> | ||
Login | ||
</button> | ||
<pre> | ||
{error} | ||
</pre> | ||
<pre> | ||
{document.cookie} | ||
</pre> | ||
</> | ||
) | ||
} | ||
|
||
export default LoginButton |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
const BASE_URL = import.meta.env.VITE_BASE_URL | ||
const LOGIN_URL = import.meta.env.VITE_AUTH_URL | ||
const TOKEN_URL = import.meta.env.VITE_TOKEN_URL | ||
|
||
const STATE_COOKIE_PREFIX = "app.txs." | ||
|
||
export default { | ||
BASE_URL, | ||
LOGIN_URL, | ||
TOKEN_URL, | ||
|
||
STATE_COOKIE_PREFIX | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import { beforeAll, expect, describe, test, vi, afterAll } from 'vitest' | ||
import { renderHook } from '@testing-library/react' | ||
|
||
import useInitPKCE from '../useInitPKCE' | ||
import config from '@/config' | ||
|
||
describe('useInitPKCE', () => { | ||
const redirect = vi.fn() | ||
beforeAll(() => { | ||
vi.stubGlobal('location', { replace: redirect }) | ||
}) | ||
|
||
afterAll(() => { | ||
vi.unstubAllGlobals() | ||
}) | ||
|
||
test('returns empty error and onLogin', () => { | ||
const { result } = renderHook(() => useInitPKCE()) | ||
expect(result.current).toMatchObject({ | ||
error: '', | ||
onLogin: expect.any(Function), | ||
}) | ||
}) | ||
|
||
test('redirects to login url', async () => { | ||
const { result } = renderHook(() => useInitPKCE()) | ||
await result.current.onLogin() | ||
|
||
expect(redirect).toHaveBeenCalled() | ||
const url = redirect.mock.calls[0][0] | ||
const query = new URLSearchParams(url.split('?')[1]) | ||
|
||
expect(query.get('response_type')).toBe('code,id_token') | ||
expect(query.get('redirect_uri')).toBe(config.BASE_URL) | ||
expect(query.get('state')).toEqual(expect.any(String)) | ||
expect(query.get('code_challenge')).toEqual(expect.any(String)) | ||
}) | ||
}) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import { useCallback, useState } from 'react' | ||
import { createPKCECodes, redirectToLogin } from '@/utils/auth' | ||
|
||
const useInitPKCE = () => { | ||
const [error, setError] = useState('') | ||
|
||
const onLogin = useCallback(async () => { | ||
try { | ||
const codes = await createPKCECodes() | ||
redirectToLogin(codes.state, codes.codeChallenge) | ||
} catch (error) { | ||
if (error instanceof Error) | ||
setError(error.message) | ||
else setError('An unknown error occurred') | ||
} | ||
}, []) | ||
|
||
return { error, onLogin } | ||
} | ||
|
||
export default useInitPKCE |
Oops, something went wrong.