Compare commits

...

2 Commits

19 changed files with 196 additions and 48 deletions

View File

@ -140,6 +140,7 @@ impl Core {
.map(|user| UserOverview {
id: user.id,
name: user.name,
state: user.state,
is_admin: user.admin,
})
.collect()),
@ -152,15 +153,10 @@ impl Core {
user_id: UserId,
) -> ResultExt<Option<UserOverview>, AppError, FatalError> {
let users = return_error!(self.list_users().await);
let user = match users.into_iter().find(|user| user.id == user_id) {
Some(user) => user,
match users.into_iter().find(|user| user.id == user_id) {
Some(user) => ok(Some(user)),
None => return ok(None),
};
ok(Some(UserOverview {
id: user.id.clone(),
name: user.name,
is_admin: user.is_admin,
}))
}
}
pub async fn create_user(&self, username: &str) -> ResultExt<UserId, AppError, FatalError> {

View File

@ -52,14 +52,14 @@ impl From<crate::types::User> for User {
}
}
/*
#[derive(Deserialize, Serialize)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[typeshare]
pub struct UserOverview {
pub id: UserId,
pub name: String,
pub is_admin: bool,
pub state: AccountState,
pub games: Vec<crate::types::GameOverview>,
}
@ -76,8 +76,8 @@ impl From<crate::types::UserOverview> for UserOverview {
id: input.id,
name: input.name,
is_admin: input.is_admin,
state: AccountState::from(input.state),
games: vec![],
}
}
}
*/

View File

@ -10,6 +10,8 @@ use crate::{
types::{AppError, FatalError, User},
};
use super::UserOverview;
#[derive(Clone, Debug, Deserialize, Serialize)]
#[typeshare]
pub struct AuthRequest {
@ -106,21 +108,23 @@ pub async fn get_user(
core: Core,
headers: HeaderMap,
user_id: Option<UserId>,
) -> ResultExt<Option<crate::types::UserOverview>, AppError, FatalError> {
) -> ResultExt<Option<UserOverview>, AppError, FatalError> {
auth_required(core.clone(), headers, |user| async move {
match user_id {
Some(user_id) => core.user(user_id).await,
None => core.user(user.id).await,
}
}).await
.map(|maybe_user| maybe_user.map(|user| UserOverview::from(user)))
})
.await
}
pub async fn get_users(
core: Core,
headers: HeaderMap,
) -> ResultExt<Vec<crate::types::UserOverview>, AppError, FatalError> {
) -> ResultExt<Vec<UserOverview>, AppError, FatalError> {
auth_required(core.clone(), headers, |_user| async move {
core.list_users().await
core.list_users().await.map(|users| users.into_iter().map(|user| UserOverview::from(user)).collect::<Vec<UserOverview>>())
})
.await
}

View File

@ -64,7 +64,13 @@ pub fn routes(core: Core) -> Router {
let Json(req) = req;
wrap_handler(|| create_user(core, headers, req))
}
}),
})
.layer(
CorsLayer::new()
.allow_methods([Method::PUT])
.allow_headers([AUTHORIZATION, CONTENT_TYPE])
.allow_origin(Any),
),
)
.route(
"/api/v1/users",

View File

@ -167,16 +167,15 @@ pub enum Message {
UpdateTabletop(Tabletop),
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[typeshare]
#[derive(Clone, Debug)]
pub struct UserOverview {
pub id: UserId,
pub name: String,
pub is_admin: bool,
pub state: AccountState,
}
#[derive(Deserialize, Serialize)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[typeshare]
pub struct GameOverview {

View File

@ -3,11 +3,11 @@ import './App.css'
import { Client } from './client'
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
import { DesignPage } from './views/Design/Design'
import { Admin } from './views/Admin/Admin'
import Candela from './plugins/Candela'
import { Authentication } from './views/Authentication/Authentication'
import { StateContext, StateProvider } from './providers/StateProvider/StateProvider'
import { MainView } from './views'
import { AdminView } from './views/Admin/Admin'
const TEST_CHARSHEET_UUID = "12df9c09-1f2f-4147-8eda-a97bd2a7a803"
@ -62,7 +62,7 @@ const App = ({ client }: AppProps) => {
},
{
path: "/admin",
element: <Admin client={client} />
element: <AdminView client={client} />
},
{
path: "/candela",

View File

@ -50,7 +50,7 @@ export class Client {
async users(sessionId: string) {
const url = new URL(this.base);
url.pathname = '/api/v1/users/';
url.pathname = '/api/v1/users';
return fetch(url, {
method: 'GET',
headers: [['Authorization', `Bearer ${sessionId}`]]
@ -63,6 +63,17 @@ export class Client {
return fetch(url).then((response) => response.json());
}
async createUser(sessionId: string, username: string) {
const url = new URL(this.base);
url.pathname = '/api/v1/user';
return fetch(url, {
method: 'PUT',
headers: [['Authorization', `Bearer: ${sessionId}`],
['Content-Type', 'application/json']],
body: JSON.stringify({ username }),
}).then((response) => response.json())
}
async setPassword(password_1: string, password_2: string) {
const url = new URL(this.base);
url.pathname = `/api/v1/user/password`;

View File

@ -0,0 +1,24 @@
.modal {
z-index: 1;
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(128, 128, 128, 0.8);
display: flex;
justify-content: center;
align-items: center;
}
.modal_window {
border: 1px solid black;
border-radius: 5px;
padding: 1em;
}
.modal_title {
background-color: skyblue;
}
.modal_cta {
margin-top: var(--margin-s);
}

View File

@ -0,0 +1,33 @@
import { PropsWithChildren } from "react";
import "./Modal.css";
export type Action = {
name: string
action: () => void
}
export interface ModalProps {
title: string
onCancel: Action
onPrimary: Action
onSecondary?: Action
}
export const Modal = ({ title, children, onCancel, onPrimary, onSecondary }: PropsWithChildren<ModalProps>) => (
<div className="modal">
<div className="modal_window">
<h1 className="modal_title"> {title} </h1>
<div className="modal_body">
{children}
</div>
<footer className="modal_cta">
<button onClick={() => onCancel.action()}>{onCancel.name}</button>
{onSecondary ? <button onClick={() => onSecondary.action()}>{onSecondary.name}</button> : <></>}
<button onClick={() => onPrimary.action()}>{onPrimary.name}</button>
</footer>
</div>
</div>
)

View File

@ -2,11 +2,3 @@
margin: var(--margin-s);
}
.profile_columns {
display: flex;
justify-content: space-between;
}
.profile_columns > div {
width: 45%;
}

View File

@ -10,7 +10,7 @@ interface ProfileProps {
export const ProfileElement = ({ profile, games }: ProfileProps) => {
const adminNote = profile.isAdmin ? <div> <i>Note: this user is an admin</i> </div> : <></>;
return (<div className="profile">
return (<div className="profile profile_columns">
<CardElement name={profile.name}>
<div>Games: {games.map((game) => {
return <span key={game.id}>{game.name} ({game.type})</span>;

View File

@ -1,16 +1,36 @@
import { UserOverview } from "visions-types"
import { CardElement } from ".."
import { PropsWithChildren, useState } from "react"
import { AccountState, UserOverview } from "visions-types"
import { CardElement} from ".."
interface UserManagementProps {
users: UserOverview[]
onShowCreateUser: () => void
}
export const UserManagementElement = ({ users }: UserManagementProps ) => {
export const UserManagementElement = ({ users, onShowCreateUser }: UserManagementProps) => {
return (
<CardElement>
<ul>
{users.map((user) => <li key={user.id}>{user.name}</li>)}
</ul>
<>
<CardElement name="Users">
<table>
<thead>
</thead>
<tbody>
{users.map((user) => <tr key={user.id}>
<td> {user.name} </td>
<td> {formatAccountState(user.state)} </td>
</tr>)}
</tbody>
</table>
<button onClick={() => onShowCreateUser()}>Create User</button>
</CardElement>
</>
)
}
const formatAccountState = (state: AccountState): string => {
switch (state.type) {
case "Normal": return "";
case "PasswordReset": return "password reset";
case "Locked": return "locked";
}
}

View File

@ -1,9 +1,10 @@
import { CardElement } from './Card/Card'
import { GameOverviewElement } from './GameOverview/GameOverview'
import { Modal, ModalProps } from './Modal/Modal'
import { ProfileElement } from './Profile/Profile'
import { SimpleGuage } from './Guages/SimpleGuage'
import { ThumbnailElement } from './Thumbnail/Thumbnail'
import { TabletopElement } from './Tabletop/Tabletop'
import { UserManagementElement } from './UserManagement/UserManagement'
export { CardElement, GameOverviewElement, UserManagementElement, ProfileElement, ThumbnailElement, TabletopElement, SimpleGuage }
export { CardElement, GameOverviewElement, Modal, type ModalProps, UserManagementElement, ProfileElement, ThumbnailElement, TabletopElement, SimpleGuage }

View File

@ -97,12 +97,15 @@ class StateManager {
break;
}
}
/*
}
async createUser(username: string) {
if (!this.client || !this.dispatch) return;
const sessionId = window.localStorage.getItem("sessionId");
if (sessionId) {
window.localStorage.setItem("sessionId", sessionId);
this.dispatch({ type: "SetAuthState", content: { type: "Authed", sessionId } });
let createUserResponse = await this.client.createUser(sessionId, username);
}
*/
}
}

View File

@ -45,7 +45,7 @@ interface AdminProps {
client: Client,
}
export const Admin = ({ client }: AdminProps) => {
export const AdminView = ({ client }: AdminProps) => {
const [users, setUsers] = useState<Array<User>>([]);
useEffect(() => {

View File

@ -3,6 +3,7 @@ import { UserOverview } from 'visions-types';
import { Client } from '../../client';
import { ProfileElement } from '../../components';
import { getSessionId, StateContext, StateProvider } from '../../providers/StateProvider/StateProvider';
import { ProfileView } from '../Profile/Profile';
interface MainProps {
client: Client
@ -17,13 +18,16 @@ export const MainView = ({ client }: MainProps) => {
useEffect(() => {
if (sessionId) {
client.profile(sessionId, undefined).then((profile) => setProfile(profile))
client.users(sessionId).then((users) => setUsers(users))
client.users(sessionId).then((users) => {
console.log(users);
setUsers(users);
})
}
}, [sessionId, client])
return (
<div>
{profile && <ProfileElement profile={profile} games={[]} />}
{profile && <ProfileView profile={profile} users={users} games={[]} />}
</div>
)
}

View File

@ -0,0 +1,9 @@
.profile-view_columns {
display: flex;
justify-content: space-between;
}
.profile-view_columns > div {
width: 45%;
}

View File

@ -0,0 +1,45 @@
import { useContext, useState } from "react"
import { GameOverview, UserOverview } from "visions-types"
import { Modal, ModalProps, ProfileElement, UserManagementElement } from "../../components"
import { StateContext } from "../../providers/StateProvider/StateProvider"
import "./Profile.css"
interface ProfileProps {
profile: UserOverview,
users: UserOverview[],
games: GameOverview[],
}
interface CreateUserModalProps {
onCancel: () => void
onCreateUser: (name: string) => void
}
const CreateUserModal = ({ onCancel, onCreateUser }: CreateUserModalProps) => {
const [userName, setUserName] = useState("");
return <Modal title="Create User" onCancel={{ name: "Cancel", action: onCancel }}
onPrimary={{ name: "Create User", action: () => onCreateUser(userName) }}>
<input type="text" placeholder="username" onChange={(evt) => {
setUserName(evt.target.value);
}} />
</Modal>
}
export const ProfileView = ({ profile, users, games, }: ProfileProps) => {
const [_state, manager] = useContext(StateContext)
const [showUser, setShowUser] = useState(false)
const userList = profile.isAdmin && <UserManagementElement users={users} onShowCreateUser={() => setShowUser(true)} />
return (
<div className="profile-view">
{showUser && <CreateUserModal onCancel={() => setShowUser(false)} onCreateUser={(username) => manager.createUser(username)} />}
<div className="profile-view_columns">
<ProfileElement profile={profile} games={games} />
{userList}
</div>
</div>
)
}

View File

@ -1,3 +1,4 @@
import { MainView } from './Main/Main'
import { ProfileView } from './Profile/Profile'
export { MainView }
export { MainView, ProfileView }