Skip to content

Commit

Permalink
feat: register an account
Browse files Browse the repository at this point in the history
  • Loading branch information
maelgangloff committed Aug 5, 2024
1 parent b569083 commit 322ae44
Show file tree
Hide file tree
Showing 9 changed files with 255 additions and 108 deletions.
91 changes: 91 additions & 0 deletions assets/components/LoginForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import {Alert, Button, Form, Input, Space} from "antd";
import {t} from "ttag";
import React, {useContext, useEffect, useState} from "react";
import {getUser, login} from "../utils/api";
import {AuthenticatedContext} from "../pages/LoginPage";
import {useNavigate} from "react-router-dom";


type FieldType = {
username: string;
password: string;
}

export function LoginForm({ssoLogin}: { ssoLogin?: boolean }) {

const [error, setError] = useState<string>()
const navigate = useNavigate()
const {setIsAuthenticated} = useContext(AuthenticatedContext)


useEffect(() => {
getUser().then(() => {
setIsAuthenticated(true)
navigate('/home')
})

}, [])


const onFinish = (data: FieldType) => {
login(data.username, data.password).then(() => {
setIsAuthenticated(true)
navigate('/home')
}).catch((e) => {
setIsAuthenticated(false)
if (e.response.data.message !== undefined) {
setError(e.response.data.message)
} else {
setError(e.response.data['hydra:description'])
}
})
}
return <>
{error &&
<Alert
type='error'
message={t`Error`}
banner={true}
role='role'
description={error}
style={{marginBottom: '1em'}}
/>}
<Form
name="basic"
labelCol={{span: 8}}
wrapperCol={{span: 16}}
style={{maxWidth: 600}}
onFinish={onFinish}
autoComplete="off"
>
<Form.Item
label={t`E-mail`}
name="username"
rules={[{required: true, message: t`Required`}]}
>
<Input autoFocus/>
</Form.Item>

<Form.Item<FieldType>
label={t`Password`}
name="password"
rules={[{required: true, message: t`Required`}]}
>
<Input.Password/>
</Form.Item>

<Space>
<Form.Item wrapperCol={{offset: 8, span: 16}}>
<Button type="primary" htmlType="submit">
{t`Submit`}
</Button>
</Form.Item>
{ssoLogin && <Form.Item wrapperCol={{offset: 8, span: 16}}>
<Button type="dashed" htmlType="button" href="/login/oauth">
{t`Log in with SSO`}
</Button>
</Form.Item>}
</Space>
</Form>
</>
}
70 changes: 70 additions & 0 deletions assets/components/RegisterForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import {Alert, Button, Form, Input} from "antd";
import {t} from "ttag";
import React, {useState} from "react";
import {register} from "../utils/api";
import {useNavigate} from "react-router-dom";


type FieldType = {
username: string;
password: string;
}

export function RegisterForm() {

const [error, setError] = useState<string>()
const navigate = useNavigate()

const onFinish = (data: FieldType) => {
register(data.username, data.password).then(() => {
navigate('/home')
}).catch((e) => {
if (e.response.data.message !== undefined) {
setError(e.response.data.message)
} else {
setError(e.response.data['hydra:description'])
}
})
}
return <>
{error &&
<Alert
type='error'
message={t`Error`}
banner={true}
role='role'
description={error}
style={{marginBottom: '1em'}}
/>}
<Form
name="basic"
labelCol={{span: 8}}
wrapperCol={{span: 16}}
style={{maxWidth: 600}}
onFinish={onFinish}
autoComplete="off"
>
<Form.Item
label={t`E-mail`}
name="username"
rules={[{required: true, message: t`Required`}]}
>
<Input autoFocus/>
</Form.Item>

<Form.Item<FieldType>
label={t`Password`}
name="password"
rules={[{required: true, message: t`Required`}]}
>
<Input.Password/>
</Form.Item>

<Form.Item wrapperCol={{offset: 8, span: 16}}>
<Button block type="primary" htmlType="submit">
{t`Register`}
</Button>
</Form.Item>
</Form>
</>
}
89 changes: 17 additions & 72 deletions assets/pages/LoginPage.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import React, {createContext, useContext, useEffect, useState} from "react";
import {Alert, Button, Card, Form, Input} from "antd";
import {getConfiguration, getUser, InstanceConfig, login} from "../utils/api";
import {useNavigate} from "react-router-dom";
import React, {createContext, useEffect, useState} from "react";
import {Button, Card} from "antd";
import {t} from 'ttag'
import TextPage from "./TextPage";
import {LoginForm} from "../components/LoginForm";
import {getConfiguration, InstanceConfig} from "../utils/api";
import {RegisterForm} from "../components/RegisterForm";

type FieldType = {
username: string;
password: string;
}

const gridStyle: React.CSSProperties = {
width: '50%',
Expand All @@ -19,79 +16,27 @@ export const AuthenticatedContext = createContext<any>(null)

export default function LoginPage() {

const [error, setError] = useState<string>()
const [wantRegister, setWantRegister] = useState<boolean>(false)
const [configuration, setConfiguration] = useState<InstanceConfig>()
const navigate = useNavigate()
const {setIsAuthenticated} = useContext(AuthenticatedContext)

const onFinish = (data: FieldType) => {
login(data.username, data.password).then(() => {
setIsAuthenticated(true)
navigate('/home')
}).catch((e) => {
setIsAuthenticated(false)
if (e.response.data.message !== undefined) {
setError(e.response.data.message)
} else {
setError(e.response.data['hydra:description'])
}
})
const toggleWantRegister = () => {
setWantRegister(!wantRegister)
}

useEffect(() => {
getUser().then(() => {
setIsAuthenticated(true)
navigate('/home')
})
getConfiguration().then(setConfiguration)
}, [])

return <Card title={t`Log in`} style={{width: '100%'}}>
return <Card title={wantRegister ? t`Register` : t`Log in`} style={{width: '100%'}}>
<Card.Grid style={gridStyle} hoverable={false}>
{error &&
<Alert
type='error'
message={t`Error`}
banner={true}
role='role'
description={error}
style={{marginBottom: '1em'}}
/>}
<Form
name="basic"
labelCol={{span: 8}}
wrapperCol={{span: 16}}
style={{maxWidth: 600}}
onFinish={onFinish}
autoComplete="off"
>
<Form.Item
label={t`Username`}
name="username"
rules={[{required: true, message: t`Required`}]}
>
<Input autoFocus/>
</Form.Item>

<Form.Item<FieldType>
label={t`Password`}
name="password"
rules={[{required: true, message: t`Required`}]}
>
<Input.Password/>
</Form.Item>

<Form.Item wrapperCol={{offset: 8, span: 16}}>
<Button block type="primary" htmlType="submit">
{t`Submit`}
</Button>
</Form.Item>
{configuration?.ssoLogin && <Form.Item wrapperCol={{offset: 8, span: 16}}>
<Button type="dashed" htmlType="button" href="/login/oauth" block>
{t`Log in with SSO`}
</Button>
</Form.Item>}
</Form>
{wantRegister ? <RegisterForm/> : <LoginForm ssoLogin={configuration?.ssoLogin}/>}
{
configuration?.registerEnabled &&
<Button type='link'
block
style={{marginTop: '1em'}}
onClick={toggleWantRegister}>{wantRegister ? 'Login' : 'Create an account'}</Button>
}
</Card.Grid>
<Card.Grid style={gridStyle} hoverable={false}>
<TextPage resource='ads.md'/>
Expand Down
1 change: 1 addition & 0 deletions assets/utils/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export interface Watchlist {
export interface InstanceConfig {
ssoLogin: boolean
limtedFeatures: boolean
registerEnabled: boolean
}

export async function request<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig): Promise<R> {
Expand Down
10 changes: 10 additions & 0 deletions assets/utils/api/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ export async function login(email: string, password: string): Promise<boolean> {
return response.status === 200
}

export async function register(email: string, password: string): Promise<boolean> {
const response = await request({
method: 'POST',
url: 'register',
data: {email, password}
})
return response.status === 201
}


export async function getUser(): Promise<User> {
const response = await request<User>({
url: 'me'
Expand Down
3 changes: 2 additions & 1 deletion src/Controller/InstanceController.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ public function __invoke(): Instance

$instance
->setLimitedFeatures($this->getParameter('limited_features') ?? false)
->setOauthEnabled($this->getParameter('oauth_enabled'));
->setOauthEnabled($this->getParameter('oauth_enabled') ?? false)
->setRegisterEnabled($this->getParameter('registration_enabled') ?? false);

return $instance;
}
Expand Down
6 changes: 4 additions & 2 deletions src/Controller/RegistrationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
Expand All @@ -31,6 +32,7 @@ public function __construct(
private readonly EntityManagerInterface $em,
private readonly SerializerInterface $serializer,
private readonly LoggerInterface $logger,
private readonly KernelInterface $kernel
) {
}

Expand All @@ -54,7 +56,7 @@ public function register(Request $request, UserPasswordHasherInterface $userPass

$limiter = $this->userRegisterLimiter->create($request->getClientIp());

if (false === $limiter->consume()->isAccepted()) {
if (false === $this->kernel->isDebug() && false === $limiter->consume()->isAccepted()) {
$this->logger->warning('IP address {ip} was rate limited by the Registration API.', [
'ip' => $request->getClientIp(),
]);
Expand Down Expand Up @@ -90,7 +92,7 @@ public function register(Request $request, UserPasswordHasherInterface $userPass
->htmlTemplate('emails/success/confirmation_email.html.twig')
);

return $this->redirectToRoute('index');
return new Response(null, 201);
}

#[Route('/verify/email', name: 'app_verify_email')]
Expand Down
14 changes: 14 additions & 0 deletions src/Entity/Instance.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ class Instance
{
private ?bool $oauthEnabled = null;

private ?bool $registerEnabled = null;

private ?bool $limitedFeatures = null;

public function isSsoLogin(): ?bool
Expand All @@ -45,4 +47,16 @@ public function setLimitedFeatures(bool $limitedFeatures): static

return $this;
}

public function getRegisterEnabled(): ?bool
{
return $this->registerEnabled;
}

public function setRegisterEnabled(?bool $registerEnabled): static
{
$this->registerEnabled = $registerEnabled;

return $this;
}
}
Loading

0 comments on commit 322ae44

Please sign in to comment.