Skip to content
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

Auth frontend #425

Merged
merged 5 commits into from
Dec 27, 2018
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
5 changes: 4 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,8 @@
"not dead",
"not ie <= 11",
"not op_mini all"
]
],
"devDependencies": {
"jest-fetch-mock": "^2.1.0"
}
}
3 changes: 3 additions & 0 deletions frontend/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<script>window.lookout = window.REPLACE_BY_SERVER || undefined;</script>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
Expand All @@ -36,5 +37,7 @@
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<!-- create react app removes comments during build that's why we need div -->
<div class="invisible-footer"></div>
</body>
</html>
111 changes: 100 additions & 11 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,106 @@
import React, { Component } from 'react';
import React, { Component, ReactElement } from 'react';
import Token from './services/token';
import * as api from './api';
import './App.css';

class App extends Component {
function Loader() {
return <div>loading...</div>;
}

interface ErrorProps {
errors: string[];
}

function Errors({ errors }: ErrorProps) {
return <div>{errors.join(',')}</div>;
}

function Login() {
return (
<header className="App-header">
<a className="App-link" href={api.loginUrl}>
Login using Github
</a>
</header>
);
}

interface HelloProps {
name: string;
}

function Hello({ name }: HelloProps) {
return <header className="App-header">Hello {name}!</header>;
}

interface AppState {
// we need undefined state for initial render
loggedIn: boolean | undefined;
name: string;
errors: string[];
}

class App extends Component<{}, AppState> {
constructor(props: {}) {
super(props);

this.fetchState = this.fetchState.bind(this);

this.state = {
loggedIn: undefined,
name: '',
errors: []
};
}

componentDidMount() {
// TODO: add router and use it instead of this "if"
if (window.location.pathname === '/callback') {
api
.callback(window.location.search)
.then(resp => {
Token.set(resp.token);
window.history.replaceState({}, '', '/');
})
.then(this.fetchState)
.catch(errors => this.setState({ errors }));
return;
}

if (!Token.exists()) {
this.setState({ loggedIn: false });
return;
}

// ignore error here, just ask user to re-login
// it would cover all cases like expired token, changes on backend and so on
this.fetchState().catch(err => console.error(err));
}

fetchState() {
return api
.me()
.then(resp => this.setState({ loggedIn: true, name: resp.name }))
.catch(err => {
this.setState({ loggedIn: false });

throw err;
});
}

render() {
return (
<div className="App">
<header className="App-header">
<a className="App-link" href="http://127.0.0.1:8080/login">
Login using Github
</a>
</header>
</div>
);
const { loggedIn, name, errors } = this.state;

let content: ReactElement<any>;
if (errors.length) {
content = <Errors errors={errors} />;
} else if (typeof loggedIn === 'undefined') {
content = <Loader />;
} else {
content = loggedIn ? <Hello name={name} /> : <Login />;
}

return <div className="App">{content}</div>;
}
}

Expand Down
67 changes: 67 additions & 0 deletions frontend/src/api.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { GlobalWithFetchMock } from 'jest-fetch-mock';
import Token from './services/token';
import { apiCall } from './api';

// can be moved to setupFiles later if needed
const customGlobal: GlobalWithFetchMock = global as GlobalWithFetchMock;
customGlobal.fetch = require('jest-fetch-mock');
customGlobal.fetchMock = customGlobal.fetch;

describe('api', () => {
beforeEach(() => {
fetchMock.resetMocks();
});

it('apiCall ok', () => {
Token.set('token');
fetchMock.mockResponseOnce(JSON.stringify({ data: 'result' }));

return apiCall('/test').then(resp => {
expect(resp).toEqual('result');

const call = fetchMock.mock.calls[0];
const [url, opts] = call;
expect(url).toEqual('http://127.0.0.1:8080/test');
expect(opts.headers.Authorization).toEqual('Bearer token');
});
});

it('apiCall http error', () => {
fetchMock.mockResponseOnce('', { status: 500 });

return apiCall('/test').catch(err => {
expect(err).toEqual(['Internal Server Error']);
});
});

it('apiCall http error with custom text', () => {
fetchMock.mockResponseOnce('', { status: 404, statusText: 'Custom text' });

return apiCall('/test').catch(err => {
expect(err).toEqual(['Custom text']);
});
});

it('apiCall http error with json response', () => {
fetchMock.mockResponseOnce(
JSON.stringify({ errors: [{ title: 'err1' }, { title: 'err2' }] }),
{
status: 500
}
);

return apiCall('/test').catch(err => {
expect(err).toEqual(['err1', 'err2']);
});
});

it('apiCall removes token on unauthorized response', () => {
Token.set('token');
fetchMock.mockResponseOnce('', { status: 401 });

return apiCall('/test').catch(err => {
expect(err).toEqual(['Unauthorized']);
expect(Token.get()).toBe(null);
});
});
});
83 changes: 83 additions & 0 deletions frontend/src/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import lookoutOptions from './services/options';
import TokenService from './services/token';

export const serverUrl = lookoutOptions.SERVER_URL || 'http://127.0.0.1:8080';

const apiUrl = (url: string) => `${serverUrl}${url}`;

interface ApiCallOptions {
method?: string;
body?: object;
}

interface ServerError {
title: string;
description: string;
}

export function apiCall<T>(
url: string,
options: ApiCallOptions = {}
): Promise<T> {
const token = TokenService.get();
const fetchOptions: RequestInit = {
credentials: 'include',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: null
};

if (options.body) {
fetchOptions.body = JSON.stringify(options.body);
}

return fetch(apiUrl(url), fetchOptions).then(response => {
if (!response.ok) {
// when server return Unauthorized we need to remove token
if (response.status === 401) {
TokenService.remove();
}

return response
.json()
.catch(() => {
throw [response.statusText];
})
.then(json => {
let errors: string[];

try {
errors = (json as { errors: ServerError[] }).errors.map(
e => e.title
);
} catch (e) {
errors = [e.toString()];
}

throw errors;
});
}

return response.json().then(json => (json as { data: T }).data);
});
}

export const loginUrl = apiUrl('/login');

interface AuthResponse {
token: string;
}

export function callback(queryString: string): Promise<AuthResponse> {
return apiCall<AuthResponse>(`/api/callback${queryString}`);
}

interface MeResponse {
name: string;
}

export function me(): Promise<MeResponse> {
return apiCall<MeResponse>('/api/me');
}
11 changes: 11 additions & 0 deletions frontend/src/services/options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
interface LookoutApiOptions {
SERVER_URL?: string;
}

declare global {
interface Window {
lookout: LookoutApiOptions;
}
}

export default window.lookout || {};
21 changes: 21 additions & 0 deletions frontend/src/services/token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const localStorageKey = 'token';

class TokenService {
get() {
return window.localStorage.getItem(localStorageKey);
}

set(token: string) {
return window.localStorage.setItem(localStorageKey, token);
}

remove() {
return window.localStorage.removeItem(localStorageKey);
}

exists() {
return !!window.localStorage.getItem(localStorageKey);
}
}

export default new TokenService();
31 changes: 31 additions & 0 deletions frontend/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2438,6 +2438,14 @@ create-hmac@^1.1.0, create-hmac@^1.1.2, create-hmac@^1.1.4:
safe-buffer "^5.0.1"
sha.js "^2.4.8"

cross-fetch@^2.2.2:
version "2.2.3"
resolved "https://registry.yarnpkg.com/cross-fetch/-/cross-fetch-2.2.3.tgz#e8a0b3c54598136e037f8650f8e823ccdfac198e"
integrity sha512-PrWWNH3yL2NYIb/7WF/5vFG3DCQiXDOVf8k3ijatbrtnwNuhMWLC7YF7uqf53tbTFDzHIUD8oITw4Bxt8ST3Nw==
dependencies:
node-fetch "2.1.2"
whatwg-fetch "2.0.4"

[email protected], cross-spawn@^6.0.0, cross-spawn@^6.0.5:
version "6.0.5"
resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-6.0.5.tgz#4a5ec7c64dfae22c3a14124dbacdee846d80cbc4"
Expand Down Expand Up @@ -5159,6 +5167,14 @@ jest-environment-node@^23.4.0:
jest-mock "^23.2.0"
jest-util "^23.4.0"

jest-fetch-mock@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/jest-fetch-mock/-/jest-fetch-mock-2.1.0.tgz#49c16451b82f311158ec897e467d704e0cb118f9"
integrity sha512-jrTNlxDsZZCq6tMhdyH7gIbt4iDUHRr6C4Jp+kXItLaaaladOm9/wJjIwU3tCAEohbuW/7/naOSfg2A8H6/35g==
dependencies:
cross-fetch "^2.2.2"
promise-polyfill "^7.1.1"

jest-get-type@^22.1.0:
version "22.4.3"
resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-22.4.3.tgz#e3a8504d8479342dd4420236b322869f18900ce4"
Expand Down Expand Up @@ -6196,6 +6212,11 @@ no-case@^2.2.0:
dependencies:
lower-case "^1.1.1"

[email protected]:
version "2.1.2"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.1.2.tgz#ab884e8e7e57e38a944753cec706f788d1768bb5"
integrity sha1-q4hOjn5X44qUR1POxwb3iNF2i7U=

[email protected]:
version "0.7.5"
resolved "https://registry.yarnpkg.com/node-forge/-/node-forge-0.7.5.tgz#6c152c345ce11c52f465c2abd957e8639cd674df"
Expand Down Expand Up @@ -7520,6 +7541,11 @@ promise-inflight@^1.0.1:
resolved "https://registry.yarnpkg.com/promise-inflight/-/promise-inflight-1.0.1.tgz#98472870bf228132fcbdd868129bad12c3c029e3"
integrity sha1-mEcocL8igTL8vdhoEputEsPAKeM=

promise-polyfill@^7.1.1:
version "7.1.2"
resolved "https://registry.yarnpkg.com/promise-polyfill/-/promise-polyfill-7.1.2.tgz#ab05301d8c28536301622d69227632269a70ca3b"
integrity sha512-FuEc12/eKqqoRYIGBrUptCBRhobL19PS2U31vMNTfyck1FxPyMfgsXyW4Mav85y/ZN1hop3hOwRlUDok23oYfQ==

[email protected]:
version "8.0.2"
resolved "https://registry.yarnpkg.com/promise/-/promise-8.0.2.tgz#9dcd0672192c589477d56891271bdc27547ae9f0"
Expand Down Expand Up @@ -9520,6 +9546,11 @@ whatwg-encoding@^1.0.1, whatwg-encoding@^1.0.3, whatwg-encoding@^1.0.5:
dependencies:
iconv-lite "0.4.24"

[email protected]:
version "2.0.4"
resolved "https://registry.yarnpkg.com/whatwg-fetch/-/whatwg-fetch-2.0.4.tgz#dde6a5df315f9d39991aa17621853d720b85566f"
integrity sha512-dcQ1GWpOD/eEQ97k66aiEVpNnapVj90/+R+SXTPYGHpYBBypfKJEQjLrvMZ7YXbKm21gXd4NcuxUTjiv1YtLng==

[email protected]:
version "3.0.0"
resolved "https://registry.yarnpkg.com/whatwg-fetch/-/whatwg-fetch-3.0.0.tgz#fc804e458cc460009b1a2b966bc8817d2578aefb"
Expand Down
Loading