From 569d322f516ddb7271f89222f11ede68caf7fefb Mon Sep 17 00:00:00 2001 From: s-ol Date: Fri, 14 Jan 2022 16:53:47 +0100 Subject: login/logout --- client/src/ui/Menu.js | 109 ++++++++++++++++++++++++++++++++------------------ 1 file changed, 71 insertions(+), 38 deletions(-) (limited to 'client/src/ui') diff --git a/client/src/ui/Menu.js b/client/src/ui/Menu.js index 6f32280..f3e912d 100644 --- a/client/src/ui/Menu.js +++ b/client/src/ui/Menu.js @@ -1,17 +1,9 @@ import { h, Fragment } from 'preact'; -import { useState, useEffect } from 'preact/hooks'; +import { useState } from 'preact/hooks'; import cn from 'classnames'; -import { API_PREFIX } from '../config'; +import { useUser, useUserCtx } from '../user'; import css from './css'; -const fetchJSON = async (url) => { - const res = await fetch(API_PREFIX + url, { credentials: 'include' }); - if (res.status !== 200) - throw new Error("wrong status"); - - return res.json(); -}; - css` a.discussion { display: flex; @@ -52,8 +44,9 @@ a.discussion > a:hover { } `; -const DiscussionLink = ({ id, name, url, attributedTo, user }) => { - const writable = attributedTo && attributedTo.indexOf(user) > -1; +const DiscussionLink = ({ id, name, url, attributedTo }) => { + const { user } = useUser(); + const writable = user && attributedTo && attributedTo.indexOf(user.id) > -1; return ( @@ -79,34 +72,86 @@ ul.discussions > li { } `; -const DiscussionList = ({ discussions, user }) => { +const DiscussionList = ({ discussions }) => { return ( ); }; +css` +div.menu div.user { + display: flex; + align-items: baseline; + gap: 1em; +} +`; +const UserMenu = () => { + const [showLogin, setLogin] = useState(false); + const { state: { user }, dispatch } = useUserCtx(); + + if (showLogin) { + return ( +
{ + e.preventDefault(); + + const elem = e.target.elements; + const username = elem.namedItem('username').value; + const password = elem.namedItem('password').value; + + dispatch({ type: 'login', username, password }) + .then( + () => setLogin(false), + (err) => setLogin("error - wrong username/password?"), + ); + + }}> + {showLogin !== true ?

{showLogin}

: null} +
+ + +
+
+ + +
+ + +
+ ); + } + + return ( +
+ {user && user.name !== 'Guest' + ? ( + <> + logged in as {user.name} + + + ) + : ( + <> + not logged in + + + )} +
+ ); +}; + css` div.menu { margin: 1rem 2rem; } `; export const Menu = () => { - const [user, setUser] = useState(null); - const [discussions, setDiscussions] = useState([]); - - useEffect(() => { - fetchJSON('/discdag/list') - .then(({ user, discussions }) => { - setUser(user ?? null); - setDiscussions(discussions); - }); - }, []); + const { user, discussions } = useUser(); if (user === null) { return ( @@ -120,20 +165,8 @@ export const Menu = () => { return ( ); }; -- cgit v1.2.3