feature: signup and login work

This commit is contained in:
Andy Burke 2025-06-25 20:51:29 -07:00
parent a4a750b35c
commit 3d42591ee5
18 changed files with 956 additions and 65 deletions

View file

@ -9,15 +9,15 @@ import { TOTP_ENTRIES } from '../../../models/totp_entry.ts';
import { verifyTotp } from 'jsr:@stdext/crypto/totp';
import { encodeBase64 } from 'jsr:@std/encoding/base64';
import parse_body from '../../../utils/bodyparser.ts';
import { SESSION_ID_TOKEN, SESSION_SECRET_TOKEN } from '../../../utils/prechecks.ts';
const DEFAULT_SESSION_TIME: number = 60 * 60; // 1 Hour
const DEFAULT_SESSION_TIME: number = 60 * 60 * 1_000; // 1 Hour
// POST /api/auth - Authenticate
export async function POST(req: Request, meta: Record<string, any>): Promise<Response> {
try {
const body = await parse_body(req);
const email: string = body.email?.toLowerCase().trim() ?? '';
const username: string = body.username?.toLowerCase() ?? '';
const password: string | undefined = body.password;
const password_hash: string | undefined = body.password_hash ?? (typeof password === 'string'
@ -27,11 +27,11 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
: undefined);
const totp: string | undefined = body.totp;
if ((!email.length && !username.length) || (email.length && username.length)) {
if (!username.length) {
return Response.json({
error: {
message: 'You must specify either an email or username to log in.',
cause: 'email_or_username_required'
message: 'You must specify a username to log in.',
cause: 'username_required'
}
}, {
status: 400
@ -51,20 +51,14 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
}
let user: USER | undefined = undefined;
if (email.length) {
user = (await USERS.find({
email
})).shift();
} else if (username.length) {
user = (await USERS.find({
username
})).shift();
}
user = (await USERS.find({
username
})).shift();
if (!user) {
return Response.json({
error: {
message: 'Could not locate an account with this email or username.',
message: `Could not locate an account with username: ${username}`,
cause: 'missing_account'
}
}, {
@ -105,7 +99,7 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
}, {
status: 202,
headers: {
'Set-Cookie': `checklist_observer_totp_user_id=${user.id}; Path=/; Max-Age=300`
'Set-Cookie': `totp_user_id=${user.id}; Path=/; Max-Age=300`
}
});
}
@ -123,7 +117,7 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
}
}
const session_result: SESSION_RESULT = await get_session({
const session_result: SESSION_RESULT = await create_new_session({
user,
expires: body.session?.expires
});
@ -164,7 +158,7 @@ export type SESSION_INFO = {
expires: string | undefined;
};
export async function get_session(session_settings: SESSION_INFO): Promise<SESSION_RESULT> {
export async function create_new_session(session_settings: SESSION_INFO): Promise<SESSION_RESULT> {
const now = new Date().toISOString();
const expires: string = session_settings.expires ??
new Date(new Date(now).valueOf() + DEFAULT_SESSION_TIME).toISOString();
@ -183,7 +177,13 @@ export async function get_session(session_settings: SESSION_INFO): Promise<SESSI
await SESSIONS.create(session);
const headers = new Headers();
headers.append('Set-Cookie', `checklist_observer_session_id=${session.id}; Path=/; Expires=${expires}`);
headers.append('Set-Cookie', `${SESSION_ID_TOKEN}=${session.id}; Path=/; Expires=${expires}`);
headers.append(`x-${SESSION_ID_TOKEN}`, session.id);
// TODO: this wasn't really intended to be persisted in a cookie, but we are using it to
// generate the TOTP for the call to /api/users/me
headers.append('Set-Cookie', `${SESSION_SECRET_TOKEN}=${session.secret}; Path=/; Expires=${expires}`);
return {
session,

View file

@ -1,19 +1,24 @@
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../utils/prechecks.ts';
import { PASSWORD_ENTRIES, PASSWORD_ENTRY } from '../../../../models/password_entry.ts';
import { SESSIONS } from '../../../../models/session.ts';
import { USER, USERS } from '../../../../models/user.ts';
import { PERMISSIONS_STORE, USER_PERMISSIONS } from '../../../../models/user_permissions.ts';
import parse_body from '../../../../utils/bodyparser.ts';
import { CANNED_RESPONSES } from '../../../../utils/canned_responses.ts';
export const PERMISSIONS: Record<string, (req: Request, meta: Record<string, any>) => Promise<boolean>> = {};
export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/users/:id - Get single user
PERMISSIONS.GET = (_req: Request, meta: Record<string, any>): Promise<boolean> => {
PRECHECKS.GET = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
const user_is_self = !!meta.user && !!meta.params && meta.user.id === meta.params.id;
const can_read_self = meta.user_permissions?.permissions.includes('self.read');
const can_read_others = meta.user_permissions?.permissions?.includes('users.read');
return can_read_others || (can_read_self && user_is_self);
};
const has_permission = can_read_others || (can_read_self && user_is_self);
if (!has_permission) {
return CANNED_RESPONSES.permission_denied();
}
}];
export async function GET(_req: Request, meta: Record<string, any>): Promise<Response> {
const user_id: string = meta.params?.id?.toLowerCase().trim() ?? '';
const user: USER | null = user_id.length === 49 ? await USERS.get(user_id) : null; // lurid is 49 chars as we use them, eg: "also-play-flow-want-form-wide-thus-work-burn-same"
@ -29,34 +34,22 @@ export async function GET(_req: Request, meta: Record<string, any>): Promise<Res
});
}
const user_is_self = meta.user?.id === user.id;
const has_permission_to_read = (user_is_self && meta.user_permissions?.permissions?.includes('self.read')) ||
(meta.user_permissions?.permissions?.includes('users.read'));
if (!has_permission_to_read) {
return Response.json({
error: {
message: 'Permission denied.',
cause: 'permission_denied'
}
}, {
status: 400
});
}
return Response.json(user, {
status: 200
});
}
// PUT /api/users/:id - Update user
PERMISSIONS.PUT = (_req: Request, meta: Record<string, any>): Promise<boolean> => {
PRECHECKS.PUT = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
const user_is_self = !!meta.user && !!meta.params && meta.user.id === meta.params.id;
const can_write_self = meta.user_permissions?.permissions.includes('self.write');
const can_write_others = meta.user_permissions?.permissions?.includes('users.write');
return can_write_others || (can_write_self && user_is_self);
};
const has_permission = can_write_others || (can_write_self && user_is_self);
if (!has_permission) {
return CANNED_RESPONSES.permission_denied();
}
}];
export async function PUT(req: Request, meta: { params: Record<string, any> }): Promise<Response> {
const now = new Date().toISOString();
const id: string = meta.params.id ?? '';
@ -101,13 +94,16 @@ export async function PUT(req: Request, meta: { params: Record<string, any> }):
}
// DELETE /api/users/:id - Delete user
PERMISSIONS.DELETE = (_req: Request, meta: Record<string, any>): Promise<boolean> => {
PRECHECKS.DELETE = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
const user_is_self = !!meta.user && !!meta.params && meta.user.id === meta.params.id;
const can_write_self = meta.user_permissions?.permissions.includes('self.write');
const can_write_others = meta.user_permissions?.permissions?.includes('users.write');
return can_write_others || (can_write_self && user_is_self);
};
const has_permission = can_write_others || (can_write_self && user_is_self);
if (!has_permission) {
return CANNED_RESPONSES.permission_denied();
}
}];
export async function DELETE(_req: Request, meta: { params: Record<string, any> }): Promise<Response> {
const user_id: string = meta.params.id ?? '';

View file

@ -6,28 +6,27 @@ import { hash } from 'jsr:@stdext/crypto/hash';
import lurid from 'jsr:@andyburke/lurid';
import { encodeBase64 } from 'jsr:@std/encoding';
import parse_body from '../../../utils/bodyparser.ts';
import { get_session, SESSION_RESULT } from '../auth/index.ts';
import { create_new_session, SESSION_RESULT } from '../auth/index.ts';
import { PRECHECKS } from './me/index.ts';
import { get_session, get_user, require_user } from '../../../utils/prechecks.ts';
import { CANNED_RESPONSES } from '../../../utils/canned_responses.ts';
// TODO: figure out a better solution for doling out permissions
const DEFAULT_USER_PERMISSIONS: string[] = [
'self.read',
'self.write',
'checklists.read',
'checklists.write',
'checklists.events.read',
'checklists.events.write'
'self.write'
];
export const PERMISSIONS: Record<string, (req: Request, meta: Record<string, any>) => Promise<boolean>> = {};
// GET /api/users - get users
// query parameters:
// partial_id: the partial id subset you would like to match (remember, lurids are lexigraphically sorted)
PERMISSIONS.GET = (_req: Request, meta: Record<string, any>): Promise<boolean> => {
PRECHECKS.GET = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
const can_read_others = meta.user_permissions?.permissions?.includes('users.read');
return can_read_others;
};
if (!can_read_others) {
return CANNED_RESPONSES.permission_denied();
}
}];
export async function GET(_req: Request, meta: Record<string, any>): Promise<Response> {
const query: URLSearchParams = meta.query;
const partial_id: string | undefined = query.get('partial_id')?.toLowerCase().trim();
@ -132,7 +131,7 @@ export async function POST(req: Request, meta: Record<string, any>): Promise<Res
await PERMISSIONS_STORE.create(user_permissions);
const session_result: SESSION_RESULT = await get_session({
const session_result: SESSION_RESULT = await create_new_session({
user,
expires: undefined
});

View file

@ -0,0 +1,7 @@
# /api/users/me
Get the current user.
## GET /api/users/me
Return the currently logged in user or an error.

View file

@ -0,0 +1,25 @@
import { CANNED_RESPONSES } from '../../../../utils/canned_responses.ts';
import { get_session, get_user, PRECHECK_TABLE, require_user } from '../../../../utils/prechecks.ts';
export const PERMISSIONS: Record<string, (req: Request, meta: Record<string, any>) => Promise<boolean>> = {};
export const PRECHECKS: PRECHECK_TABLE = {};
// GET /api/users/me - Get the current user
PRECHECKS.GET = [get_session, get_user, require_user, (_req: Request, meta: Record<string, any>): Response | undefined => {
const can_read_self = meta.user_permissions?.permissions.includes('self.read');
const has_permission = can_read_self;
console.dir({
meta,
can_read_self,
has_permission
});
if (!has_permission) {
return CANNED_RESPONSES.permission_denied();
}
}];
export function GET(_req: Request, meta: Record<string, any>): Response {
return Response.json(meta.user, {
status: 200
});
}