diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 241e576..5a10cf0 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -4,11 +4,11 @@ import WebSocketComponent from './components/WebsocketComponent'; import UserInfo from './components/UserInfo'; import api from './services/api'; import Feeds from './components/Feeds'; +import Logout from './components/Logout'; function App() { - const [name, setName] = useState(); - const [password, setPassword] = useState(); - const [token, setToken] = useState(); + const [name, setName] = useState(''); + const [password, setPassword] = useState(''); const [isLoggedIn, setIsLoggedIn] = useState(); const [loginError, setLoginError] = useState(); @@ -27,15 +27,20 @@ function App() { api .login(name, password) - .then((resp) => { + .then(() => { setIsLoggedIn(true); - setToken(resp.token); }) .catch((err) => { - setLoginError(err); + setLoginError(err.message); }); }, [name, password]); + const logout = useCallback(() => { + api.logout().then(() => { + setIsLoggedIn(false); + }); + }, []); + return (
@@ -64,8 +69,9 @@ function App() { {loginError} )} - {isLoggedIn && token && ( + {isLoggedIn && (
+ diff --git a/frontend/src/components/Logout.tsx b/frontend/src/components/Logout.tsx new file mode 100644 index 0000000..d99cead --- /dev/null +++ b/frontend/src/components/Logout.tsx @@ -0,0 +1,15 @@ +import React from 'react'; + +interface Props { + logout: () => void; +} + +const Logout = ({ logout }: Props) => { + return ( +
+ +
+ ); +}; + +export default Logout; diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 0c08e55..75214fd 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -47,14 +47,36 @@ class API { } } + _saveToken(token: string) { + this.token = token; + window.localStorage.setItem('authToken', token); + } + login(name: string, password: string): Promise { return this._doRequest('/auth/login', { method: 'POST', body: JSON.stringify({ name, password }), - }).then((resp: any) => { - window.localStorage.setItem('authToken', resp.token); - return resp; - }) as any; + }) + .then((resp: any) => { + this._saveToken(resp.token); + return resp; + }) + .catch((err) => { + console.log('caught error', err); + const errorParsed = JSON.parse(err.message); + + if (errorParsed.message) { + throw new Error(errorParsed.message); + } + console.log({ errorParsed }); + throw new Error('invalid username or password'); + }) as any; + } + + logout(): Promise { + return this._doRequest('/auth/logout').then(() => { + this._saveToken(''); + }); } me(): Promise { @@ -96,8 +118,6 @@ class API { const api = new API(); -// api.login = api.login.bind(api); -// api.me = api.me.bind(api); -// api.connectWs = api.connectWs.bind(api); +api._init(); export default api;