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

♻️ Rewrite LoginView to TypeScript #271

Merged
merged 1 commit into from
Jun 15, 2022
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
7 changes: 1 addition & 6 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,6 @@ const TickerViewWrapper: FC = () => {
return <TickerView id={tickerId} />
}

//TODO: Can be removed if LoginView is rewritten
const LoginViewWrapper: FC = () => {
return <LoginView />
}

const App: FC = () => {
const queryClient = new QueryClient()

Expand All @@ -35,7 +30,7 @@ const App: FC = () => {
<BrowserRouter>
<Switch>
<Route component={HomeView} exact path="/" />
<Route component={LoginViewWrapper} exact path="/login" />
<Route component={LoginView} exact path="/login" />
<Route component={TickerViewWrapper} path="/ticker/:tickerId" />
<Route component={UsersView} path="/users" />
<Route component={SettingsView} path="/settings" />
Expand Down
30 changes: 30 additions & 0 deletions src/api/Auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { ApiUrl } from './Api'

interface LoginResponse {
code: number
expire: Date
token: string
}

export function login(
username: string,
password: string
): Promise<LoginResponse> {
return fetch(`${ApiUrl}/admin/login`, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
method: 'post',
body: JSON.stringify({ username, password }),
})
.then(response => {
if (response.status === 401) throw new Error('Authentication failed')
if (!response.ok) throw new Error('Login failed')

return response.json()
})
.catch(error => {
throw new Error('Login failed')
})
}
19 changes: 2 additions & 17 deletions src/components/AuthService.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,8 @@ class AuthService {
setInterval(() => this.refreshToken(), 60000)
}

/**
* @param {string} username
* @param {string} password
* @returns {Promise<Response>}
*/
login(username, password) {
return this.fetch(`${ApiUrl}/admin/login`, {
method: 'POST',
body: JSON.stringify({
username,
password,
}),
}).then(response => {
this.setToken(response.token)

return Promise.resolve(response)
})
login(token) {
this.setToken(token)
}

/**
Expand Down
113 changes: 0 additions & 113 deletions src/views/LoginView.js

This file was deleted.

109 changes: 109 additions & 0 deletions src/views/LoginView.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import React, { FC, FormEvent, useCallback, useEffect } from 'react'
import { SubmitHandler, useForm } from 'react-hook-form'
import { useHistory } from 'react-router'
import {
Button,
Container,
Form,
Grid,
Header,
Icon,
InputOnChangeData,
Message,
} from 'semantic-ui-react'
import { login } from '../api/Auth'
import AuthSingleton from '../components/AuthService'

const Auth = AuthSingleton.getInstance()

interface FormValues {
email: string
password: string
}

const LoginView: FC = () => {
const {
formState: { errors },
register,
handleSubmit,
setValue,
setError,
} = useForm<FormValues>()
const history = useHistory()

const onChange = useCallback(
(e: FormEvent, { name, value }: InputOnChangeData) => {
setValue(name, value)
},
[setValue]
)

const onSubmit: SubmitHandler<FormValues> = data => {
login(data.email, data.password)
.then(response => {
Auth.login(response.token)
history.push('/')
})
.catch((error: Error) =>
setError('email', { type: 'custom', message: error.message })
)
}

useEffect(() => {
if (Auth.loggedIn()) history.replace('/')

register('email')
register('password')
})

return (
<Container>
<Container className="app">
<Grid centered>
<Grid.Column computer={6} mobile={16}>
<Grid.Row>
<Header icon size="huge" textAlign="center">
<Icon name="browser" size="small" />
<Header.Content>Login</Header.Content>
</Header>
</Grid.Row>
<Grid.Row>
<Form onSubmit={handleSubmit(onSubmit)}>
{errors.email ? (
<Message
content={errors.email.message}
negative
size="small"
/>
) : null}
<Form.Input
icon="user"
iconPosition="left"
name="email"
onChange={onChange}
placeholder="Email"
required
type="text"
/>
<Form.Input
icon="lock"
iconPosition="left"
name="password"
onChange={onChange}
placeholder="Password"
required
type="password"
/>
<Button color="teal" fluid type="submit">
Login
</Button>
</Form>
</Grid.Row>
</Grid.Column>
</Grid>
</Container>
</Container>
)
}

export default LoginView