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 3 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
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
80 changes: 80 additions & 0 deletions frontend/src/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
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;
}

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();
Loading