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

Add all moderator pages to svelte #601

Merged
merged 3 commits into from
Sep 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 4 additions & 0 deletions app/digital/mail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import path from 'path';
import handlebars from 'handlebars';
import env from '../../env';
import type { SentMessageInfo } from 'nodemailer/lib/smtp-transport';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

type TemplateVars = {
from: string;
Expand Down
3 changes: 0 additions & 3 deletions app/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@ router.get('/admin*', checkAdmin, (req, res, next) => {

// Make sure all moderator routes are secure
router.get('/moderator*', checkModerator, (req, res, next) => {
if (env.NODE_ENV !== 'development') {
return res.render('moderatorIndex'); // Remove when migration is finished
}
next();
});

Expand Down
Binary file added src/lib/assets/deactivate.mp3
Binary file not shown.
38 changes: 31 additions & 7 deletions src/lib/utils/callApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,58 @@ const callApi = async <
input: string,
method: RequestInit['method'] = 'GET',
body?: ReqBody,
headers?: RequestInit['headers']
): Promise<{ status: number; body: ResBody }> => {
headers?: RequestInit['headers'],
fetchFunc = fetch
PeterJFB marked this conversation as resolved.
Show resolved Hide resolved
): Promise<
| {
result: 'success';
status: number;
body: ResBody;
}
| {
result: 'failure';
status: number;
body: {
message: string;
name: string;
};
}
> => {
let xsrfToken = get(xsrf);
if (!xsrfToken && method.toUpperCase() !== 'GET') {
await generateXSRFToken();
xsrfToken = get(xsrf);
}

const res = await fetch('/api' + input, {
const res = await fetchFunc('/api' + input, {
headers: {
...headers,
'Content-Type': body ? 'application/json' : undefined,
'content-type': body ? 'application/json' : undefined,
'X-XSRF-TOKEN': xsrfToken,
},
method,
body: body ? JSON.stringify(body) : undefined,
});

let resBody: ResBody;
let resBody: ResBody & { message: string; name: string };
if (res.headers.get('Content-Type')?.includes('application/json')) {
resBody = await res.json();
}
return { status: res.status, body: resBody };

if (res.status < 400) {
return { result: 'success', status: res.status, body: resBody };
} else {
return {
result: 'failure',
status: res.status,
body: resBody,
};
}
};

export const generateXSRFToken = async () => {
const res = await callApi<{ csrfToken: string }>('/auth/token');
if (res.status === 200) {
if (res.result === 'success') {
xsrf.set(res.body.csrfToken);
} else {
console.error('Could not retrieve csrf-token');
Expand Down
2 changes: 1 addition & 1 deletion src/lib/utils/cardKeyScanStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,11 @@ export const cardKeyScanStore = writable<{ cardKey: number; time: number }>(
};
}
} catch (e) {
console.error(e);
if (window.navigator.userAgent.includes('Android')) {
alerts.push(e, 'ERROR');
}
window.location.assign('/moderator/serial_error');
console.error(e);
}
}

Expand Down
13 changes: 10 additions & 3 deletions src/lib/utils/userApi.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,30 @@
import callApi from './callApi';

export const toggleUser = (cardKey: number | string) => {
return callApi('/user/' + cardKey + '/toggle_active', 'POST');
return callApi<{ active: boolean }>(
'/user/' + cardKey + '/toggle_active',
'POST'
);
};

export const createUser = (user: Record<string, unknown>) => {
return callApi('/user', 'POST', user);
};

export const generateUser = (user: Record<string, unknown>) => {
return callApi('/user/generate', 'POST', user);
return callApi<{ status: string; user: string }>(
'/user/generate',
'POST',
user
);
};

export const changeCard = (user: Record<string, unknown>) => {
return callApi('/user/' + user.username + '/change_card', 'PUT', user);
};

export const countActiveUsers = () => {
return callApi('/user/count?active=true');
return callApi<{ users: number }>('/user/count?active=true');
};

export const deactivateNonAdminUsers = () => {
Expand Down
19 changes: 6 additions & 13 deletions src/routes/(election)/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -21,30 +21,23 @@

let priorities: IAlternative[] = [];

type ErrorCode = {
name: string;
};
type ErrorMessage = {
message: string;
};

const getActiveElection = async (accessCode: string = '') => {
const res = await callApi<PopulatedElection & ErrorCode & ErrorMessage>(
const res = await callApi<PopulatedElection>(
'/election/active?accessCode=' + accessCode
);

if (res.status === 200) {
if (res.result === 'success') {
priorities = [];
electionExists = true;
activeElection = res.body;
errorCode = '';
} else {
errorCode = res.body.name;
if (res.status == 404) {
if (res.status === 404) {
electionExists = false;
activeElection = null;
accessCode = '';
} else if (res.status == 403) {
} else if (res.status === 403) {
electionExists = true;
activeElection = null;
accessCode = '';
Expand All @@ -62,7 +55,7 @@
election,
priorities,
});
if (res.status === 201) {
if (res.result === 'success') {
activeElection = null;
priorities = [];
electionExists = false;
Expand Down Expand Up @@ -203,10 +196,10 @@
<div class="access-code">
<form
class="form-group enter-code-form"
name="enterCodeForm"
on:submit|preventDefault={() => {
getActiveElection(accessCode);
}}
name="enterCodeForm"
>
<div class="form-group access-code">
<label for="accessCode">Kode</label>
Expand Down
4 changes: 1 addition & 3 deletions src/routes/(election)/retrieve/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,10 @@
const handleRetrieveVote: EventHandler<SubmitEvent, HTMLFormElement> = async (
e
) => {
e.preventDefault();

const res = await callApi<typeof vote>('/vote', 'GET', null, {
'Vote-Hash': voteHash,
});
if (res.status === 200) {
if (res.result === 'success') {
vote = res.body;
}
};
Expand Down
11 changes: 3 additions & 8 deletions src/routes/auth/login/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,15 @@
| null;

const handleLogin: EventHandler<SubmitEvent, HTMLFormElement> = async (e) => {
e.preventDefault();
const res = await callApi(
'/auth/login',
'POST',
Object.fromEntries(new FormData(e.currentTarget))
);

if (res.status == 200) {
if (res.result === 'success') {
window.location.assign('/');
} else if (res.status == 401) {
} else if (res.status === 401) {
feedback = 'authfailed';
} else {
feedback = 'unknownError';
Expand Down Expand Up @@ -103,11 +102,7 @@
<div class="col-md-6 text-center">
<video class="center" bind:this={camera} muted playsinline />
<br />
<form
action="/auth/login"
method="POST"
on:submit|preventDefault={handleLogin}
>
<form name="loginForm" on:submit|preventDefault={handleLogin}>
<label class="form-label" for="username">Brukernavn:</label>
<div class="input-group mb-3">
<input
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
if (firstCall || !cardKey) return (firstCall = false);
const res = await userApi.toggleUser(cardKey);

if (res.status === 200) {
if (res.result === 'success') {
const lastAlert = alerts.getLastAlert();

if (dingAudio) dingAudio.play();
Expand Down
79 changes: 79 additions & 0 deletions src/routes/moderator/(useCardKey)/change_card/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<script lang="ts">
import { alerts } from '$lib/stores';
import { cardKeyScanStore } from '$lib/utils/cardKeyScanStore';
import userApi from '$lib/utils/userApi';
import type { EventHandler } from 'svelte/elements';

let form: HTMLFormElement;
const handleChangeCard: EventHandler<SubmitEvent, HTMLFormElement> = async (
e
) => {
const res = await userApi.changeCard({
...Object.fromEntries(new FormData(e.currentTarget)),
cardKey: $cardKeyScanStore.cardKey,
});

if (res.result === 'success') {
alerts.push('Det nye kortet er nå registert.', 'SUCCESS');
form.reset();
} else {
switch (res.body.name) {
case 'DuplicateCardError':
alerts.push('Dette kortet er allerede blitt registrert.', 'ERROR');
break;
case 'InvalidRegistrationError':
alerts.push('Ugyldig brukernavn og/eller passord.', 'ERROR');
break;
default:
alerts.push('Noe gikk galt!', 'ERROR');
}
}
};
</script>

<div class="center text-center">
<form
class="form-group"
name="changeCardForm"
on:submit|preventDefault={handleChangeCard}
bind:this={form}
>
<div class="form-group">
<label for="card-number">Nytt kortnummer</label><input
class="form-control"
type="text"
name="cardKey"
value={$cardKeyScanStore.cardKey || ''}
placeholder="Vennligst skann kortet"
required
disabled
/>
</div>
<div class="form-group">
<label for="username">Brukernavn</label><input
class="form-control"
type="text"
name="username"
id="username"
required
placeholder="Skriv inn brukernavn"
/>
</div>
<div class="form-group">
<label for="password">Password</label><input
class="form-control"
type="password"
name="password"
id="password"
required
placeholder="Skriv inn passord"
/>
</div>
<button class="btn btn-outline-secondary" id="submit" type="submit"
>Registrer nytt kort</button
>
{#if !$cardKeyScanStore.cardKey}
<p class="text-danger">Kortnummer er påkrevd</p>
{/if}
</form>
</div>
Loading
Loading