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

Setup Appwrite #2

Merged
merged 4 commits into from
Nov 3, 2024
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
3 changes: 1 addition & 2 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
<title>Kneipolympics</title>
</head>
<body>
<div id="root"></div>
Expand Down
1,241 changes: 1,210 additions & 31 deletions package-lock.json

Large diffs are not rendered by default.

10 changes: 9 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,15 @@
"preview": "vite preview"
},
"dependencies": {
"@emotion/react": "^11.13.3",
"@emotion/styled": "^11.13.0",
"@fontsource/roboto": "^5.1.0",
"@mui/icons-material": "^6.1.6",
"@mui/material": "^6.1.6",
"appwrite": "^16.0.2",
"react": "^18.3.1",
"react-dom": "^18.3.1"
"react-dom": "^18.3.1",
"react-router-dom": "^6.27.0"
},
"devDependencies": {
"@eslint/js": "^9.13.0",
Expand All @@ -22,6 +29,7 @@
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.14",
"globals": "^15.11.0",
"sass-embedded": "^1.80.6",
"typescript": "~5.6.2",
"typescript-eslint": "^8.11.0",
"vite": "^5.4.10"
Expand Down
1 change: 0 additions & 1 deletion public/vite.svg

This file was deleted.

48 changes: 6 additions & 42 deletions src/App.css
Original file line number Diff line number Diff line change
@@ -1,42 +1,6 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}

.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}

@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}

.card {
padding: 2em;
}

.read-the-docs {
color: #888;
}
/* main { */
/* display: flex; */
/* flex-direction: column; */
/* justify-content: center; */
/* align-items: center; */
/* } */
37 changes: 12 additions & 25 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,33 +1,20 @@
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import { Container } from "@mui/material";
import "./App.css";

export function App() {
const [count, setCount] = useState(0);
import { AppwriteContextProvider } from "./contexts/appwrite";
import { AuthContextProvider } from "./contexts/auth";
import { Router } from "./routes";

export function App() {
return (
<>
<div>
<a href="https://vite.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.tsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
<AppwriteContextProvider>
<AuthContextProvider>
<Container maxWidth="lg">
<Router />
</Container>
</AuthContextProvider>
</AppwriteContextProvider>
</>
);
}
1 change: 0 additions & 1 deletion src/assets/react.svg

This file was deleted.

130 changes: 130 additions & 0 deletions src/components/navbar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import {
AppBar,
Box,
Container,
IconButton,
Menu,
MenuItem,
Toolbar,
Tooltip,
Typography,
} from "@mui/material";
import { AccountCircle, LocalBar } from "@mui/icons-material";
import { useState } from "react";
import { useAuth } from "../hooks/useAuth";
import { useNavigate } from "react-router-dom";

export function NavBar() {
const navigate = useNavigate();
const { user, loggedIn, logout } = useAuth();

const [anchorElUser, setAnchorElUser] = useState<null | HTMLElement>(null);

const handleOpenUserMenu = (event: React.MouseEvent<HTMLElement>) => {
setAnchorElUser(event.currentTarget);
};

const handleCloseUserMenu = () => {
setAnchorElUser(null);
};

return (
<AppBar>
<Container maxWidth="lg">
<Toolbar disableGutters>
<Box sx={{ flexGrow: 1, display: "flex", alignItems: "center" }}>
<LocalBar sx={{ mr: 1 }} />
<Typography
variant="h6"
noWrap
component="a"
sx={{
display: {
xs: "none",
md: "inline-flex",
},
mr: 2,
fontFamily: "monospace",
fontWeight: 700,
letterSpacing: ".3rem",
color: "inherit",
textDecoration: "none",
}}
>
Kneipolympics
</Typography>
</Box>
<Box sx={{ flexGrow: 0 }}>
<h4 style={{ display: "inline", marginRight: 10 }}>{user?.name}</h4>
<Tooltip title="Open settings">
<IconButton onClick={handleOpenUserMenu} sx={{ p: 0 }}>
<AccountCircle />
</IconButton>
</Tooltip>
<Menu
sx={{ mt: "45px" }}
id="menu-appbar"
anchorEl={anchorElUser}
anchorOrigin={{
vertical: "top",
horizontal: "right",
}}
keepMounted
transformOrigin={{
vertical: "top",
horizontal: "right",
}}
open={Boolean(anchorElUser)}
onClose={handleCloseUserMenu}
>
{loggedIn ? (
<Box>
<MenuItem
onClick={() => {
handleCloseUserMenu();
}}
>
<Typography sx={{ textAlign: "center" }}>
Profile
</Typography>
</MenuItem>
<MenuItem
onClick={() => {
handleCloseUserMenu();
logout()
.then(() => navigate("/"))
.catch(console.error);
}}
>
<Typography sx={{ textAlign: "center" }}>Logout</Typography>
</MenuItem>
</Box>
) : (
<Box>
<MenuItem
onClick={() => {
handleCloseUserMenu();
navigate("/login");
}}
>
<Typography sx={{ textAlign: "center" }}>Login</Typography>
</MenuItem>
<MenuItem
onClick={() => {
handleCloseUserMenu();
navigate("/register");
}}
>
<Typography sx={{ textAlign: "center" }}>
Register
</Typography>
</MenuItem>
</Box>
)}
</Menu>
</Box>
</Toolbar>
</Container>
</AppBar>
);
}
27 changes: 27 additions & 0 deletions src/contexts/appwrite.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Client } from "appwrite";
import { createContext, PropsWithChildren } from "react";

export type AppwriteContextValue = {
client: Client;
};

export const AppwriteContext = createContext<AppwriteContextValue>(

Check warning on line 8 in src/contexts/appwrite.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 8 in src/contexts/appwrite.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 8 in src/contexts/appwrite.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
{} as AppwriteContextValue,
);

type Props = PropsWithChildren;

export function AppwriteContextProvider({ children }: Props) {
const client = new Client();
client.setProject("67257b8d001f6f36d0be");

const value = {
client,
};

return (
<AppwriteContext.Provider value={value}>
{children}
</AppwriteContext.Provider>
);
}
91 changes: 91 additions & 0 deletions src/contexts/auth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import {
createContext,
PropsWithChildren,
useEffect,
useMemo,
useState,
} from "react";
import { useAppwrite } from "../hooks/useAppwrite";
import { Account, AppwriteException, ID, Models } from "appwrite";

export type AuthContextValue = {
session?: Models.Session;
user?: Models.User<Models.Preferences>;
loggedIn: boolean;
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

export function AuthContextProvider({ children }: PropsWithChildren) {
const { client } = useAppwrite();
const account = useMemo(() => new Account(client), [client]);

const [session, setSession] = useState<Models.Session | undefined>();
const [user, setUser] = useState<
Models.User<Models.Preferences> | undefined
>();

useEffect(() => {
account
.getSession("current")
.then((session) => {
account
.get()
.then((user) => {
setSession(session);
setUser(user);
})
.catch(() => account.deleteSession("current"));
})
.catch(() => {});
}, [account]);

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

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> {
try {
await account.deleteSession("current");
setSession(undefined);
setUser(undefined);
} catch (e) {
console.error(e);
}
}

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

const value = {
login,
logout,
register,
session,
user,
loggedIn: !!(session && user),
};

return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
6 changes: 6 additions & 0 deletions src/hooks/useAppwrite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { useContext } from "react";
import { AppwriteContext } from "../contexts/appwrite";

export function useAppwrite() {
return useContext(AppwriteContext);
}
Loading
Loading