feat: store random public ID and IP with session data for #1
This commit is contained in:
parent
ec42bf7bc8
commit
db4eaef079
@ -5,15 +5,16 @@ import { users } from './db';
|
||||
type SessionData = {
|
||||
userId: string;
|
||||
userAgent: string;
|
||||
ip: string;
|
||||
};
|
||||
|
||||
const sessions: Map<string, SessionData> = new Map();
|
||||
const sessions: Map<string, SessionData & { publicId: string }> = new Map();
|
||||
|
||||
export function createSession(data: SessionData) {
|
||||
const token = nanoid();
|
||||
sessions.set(token, data);
|
||||
setTimeout(() => sessions.delete(token), parseInt(env.SESSION_LIFETIME) * 1000 || 86_400_000);
|
||||
return token;
|
||||
const sessionId = nanoid();
|
||||
sessions.set(sessionId, { ...data, publicId: nanoid() });
|
||||
setTimeout(() => sessions.delete(sessionId), parseInt(env.SESSION_LIFETIME) * 1000 || 86_400_000);
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
export async function getUserFromSession(sessionId?: string) {
|
||||
@ -25,7 +26,26 @@ export async function getUserFromSession(sessionId?: string) {
|
||||
return await users.getById(data.userId);
|
||||
}
|
||||
|
||||
export function deleteSession(sessionId?: string) {
|
||||
if (!sessionId) return;
|
||||
sessions.delete(sessionId);
|
||||
export function deleteSession(criteria: { sessionId?: string; publicId?: string }) {
|
||||
let deleted = false;
|
||||
|
||||
if (criteria.sessionId) {
|
||||
deleted = sessions.delete(criteria.sessionId);
|
||||
} else {
|
||||
for (let [k, v] of sessions) {
|
||||
if (v.publicId == criteria.publicId) {
|
||||
// surprisingly, deleting while iterating is fine with ES6 iterables
|
||||
deleted = sessions.delete(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return deleted;
|
||||
}
|
||||
|
||||
export function getUserSessions(userId: string) {
|
||||
return sessions
|
||||
.values()
|
||||
.filter((s) => s.userId == userId)
|
||||
.toArray();
|
||||
}
|
||||
|
||||
@ -91,6 +91,7 @@ export const actions = {
|
||||
createSession({
|
||||
userAgent: request.headers.get('user-agent') ?? 'UNKNOWN',
|
||||
userId: user.id,
|
||||
ip,
|
||||
}),
|
||||
{
|
||||
path: '/',
|
||||
|
||||
@ -2,7 +2,7 @@ import { deleteSession } from '$lib/server/sessions';
|
||||
import { redirect, type ServerLoad } from '@sveltejs/kit';
|
||||
|
||||
export const load: ServerLoad = async ({ cookies }) => {
|
||||
deleteSession(cookies.get('session'));
|
||||
deleteSession({ sessionId: cookies.get('session') });
|
||||
cookies.delete('session', { path: '/' });
|
||||
redirect(302, '/login');
|
||||
};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user