Skip to content

Commit

Permalink
feat(auth): add possibility to register new users
Browse files Browse the repository at this point in the history
  • Loading branch information
H1ghBre4k3r committed Nov 3, 2024
1 parent 7218853 commit bc06a27
Show file tree
Hide file tree
Showing 7 changed files with 133 additions and 46 deletions.
4 changes: 0 additions & 4 deletions src/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,3 @@
/* justify-content: center; */
/* align-items: center; */
/* } */

main {
padding-top: 80px;
}
46 changes: 27 additions & 19 deletions src/contexts/auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ import {
useState,
} from "react";
import { useAppwrite } from "../hooks/useAppwrite";
import { Account, Models } from "appwrite";
import { Account, AppwriteException, ID, Models } from "appwrite";

export type AuthContextValue = {
session?: Models.Session;
user?: Models.User<Models.Preferences>;
loggedIn: boolean;
login(username: string, password: string): Promise<void>;
login(email: string, password: string): Promise<void>;
logout(): Promise<void>;
register(email: string, password: string, name: string): Promise<void>;
};

export const AuthContext = createContext({} as AuthContextValue);

Check warning on line 20 in src/contexts/auth.tsx

View workflow job for this annotation

GitHub Actions / build (20.x, ubuntu-latest)

Fast refresh only works when a file only exports components. Move your React context(s) to a separate file

Check warning on line 20 in src/contexts/auth.tsx

View workflow job for this annotation

GitHub Actions / build (20.x, macos-latest)

Fast refresh only works when a file only exports components. Move your React context(s) to a separate file

Check warning on line 20 in src/contexts/auth.tsx

View workflow job for this annotation

GitHub Actions / build (20.x, windows-latest)

Fast refresh only works when a file only exports components. Move your React context(s) to a separate file
Expand Down Expand Up @@ -42,23 +43,21 @@ export function AuthContextProvider({ children }: PropsWithChildren) {
.catch(() => {});
}, [account]);

async function login(username: string, password: string): Promise<void> {
try {
const session = await account.createEmailPasswordSession(
username,
password,
);
async function login(email: string, password: string): Promise<void> {
const session = await account.createEmailPasswordSession(email, password);

account
.get()
.then((user) => {
setSession(session);
setUser(user);
})
.catch(() => account.deleteSession("current"));
} catch (e) {
console.error(e);
}
account
.get()
.then((user) => {
if (!user.emailVerification) {
throw new AppwriteException(
"Please verify your email before logging in!",
);
}
setSession(session);
setUser(user);
})
.catch(() => account.deleteSession("current"));
}

async function logout(): Promise<void> {
Expand All @@ -71,10 +70,19 @@ export function AuthContextProvider({ children }: PropsWithChildren) {
}
}

async function register(
email: string,
password: string,
name: string,
): Promise<void> {
await account.create(ID.unique(), email, password, name);
}

const value = {
login,
session,
logout,
register,
session,
user,
loggedIn: !!(session && user),
};
Expand Down
9 changes: 9 additions & 0 deletions src/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
main {
padding-top: 60px;
}

form {
display: flex;
flex-direction: column;
gap: 20px;
}
15 changes: 11 additions & 4 deletions src/routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { useAuth } from "../hooks/useAuth";
import { Login } from "./login";
import ErrorPage from "./error";
import { Main } from "./main";
import { Register } from "./register";

export function Router() {
const { loggedIn } = useAuth();
Expand All @@ -19,10 +20,16 @@ export function Router() {
];

if (!loggedIn) {
children.push({
path: "/login",
element: <Login />,
});
children.push(
{
path: "/login",
element: <Login />,
},
{
path: "/register",
element: <Register />,
},
);
}

const routes: RouteObject[] = [
Expand Down
6 changes: 0 additions & 6 deletions src/routes/login.css

This file was deleted.

34 changes: 21 additions & 13 deletions src/routes/login.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { useState } from "react";
import { FormEvent, useState } from "react";
import { useAuth } from "../hooks/useAuth";
import { Button, FormControl, TextField } from "@mui/material";
import { Alert, Button, Container, TextField } from "@mui/material";
import { useNavigate } from "react-router-dom";

import "./login.css";
import { AppwriteException } from "appwrite";

export function Login() {
const navigate = useNavigate();
Expand All @@ -12,26 +11,35 @@ export function Login() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");

function onSubmit() {
const [err, setErr] = useState<string | undefined>();

function onSubmit(e: FormEvent) {
e.preventDefault();
auth
.login(username, password)
.then(() => {
navigate("/");
})
.catch(console.error);
.catch((e: AppwriteException | unknown) => {
if (e instanceof AppwriteException) {
setErr(e.message);
}
console.log(e);
});
}

return (
<>
<Container maxWidth="sm">
<h2>Login</h2>
<FormControl className="login-form">
<form onSubmit={onSubmit}>
{err && <Alert severity="error">{err}</Alert>}
<TextField
type="email"
name="username"
name="email"
value={username}
onChange={(e) => setUsername(e.target.value)}
variant="standard"
label="Username"
label="EMail"
/>
<TextField
type="password"
Expand All @@ -41,8 +49,8 @@ export function Login() {
onChange={(e) => setPassword(e.target.value)}
variant="standard"
/>
<Button onClick={() => onSubmit()}>Login</Button>
</FormControl>
</>
<Button type="submit">Login</Button>
</form>
</Container>
);
}
65 changes: 65 additions & 0 deletions src/routes/register.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { useNavigate } from "react-router-dom";
import { useAuth } from "../hooks/useAuth";
import { FormEvent, useState } from "react";
import { Alert, Button, Container, TextField } from "@mui/material";
import { AppwriteException } from "appwrite";

export function Register() {
const navigate = useNavigate();
const auth = useAuth();

const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [name, setName] = useState("");

const [err, setErr] = useState<string | undefined>();

function onSubmit(e: FormEvent) {
e.preventDefault();
auth
.register(email, password, name)
.then(() => {
navigate("/");
})
.catch((e: AppwriteException | unknown) => {
if (e instanceof AppwriteException) {
setErr(e.message);
}
console.log(e);
});
}

return (
<Container maxWidth="sm">
<h2>Register</h2>
<form onSubmit={onSubmit}>
{err && <Alert severity="error">{err}</Alert>}
<TextField
type="text"
name="username"
value={name}
onChange={(e) => setName(e.target.value)}
variant="standard"
label="Username"
/>
<TextField
type="email"
name="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
variant="standard"
label="EMail"
/>
<TextField
type="password"
name="password"
label="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
variant="standard"
/>
<Button type="submit">Register</Button>
</form>
</Container>
);
}

0 comments on commit bc06a27

Please sign in to comment.