Simple auth api (no db)

This commit is contained in:
2025-09-20 10:19:46 +02:00
parent 202a0420fa
commit 04eefcacfc
7 changed files with 414 additions and 1 deletions
+11
View File
@@ -0,0 +1,11 @@
import { StringMap } from "@/types/typeUtils";
type ServerAuth = {
server_ip: string;
user_id: number;
};
// { token: userid }
export const CLIENT_AUTH_TOKENS: StringMap<number> = {};
export const SERVER_AUTH_TOKENS: StringMap<ServerAuth> = { test: { server_ip: '10.7.1.21', user_id: 2323 } };
+64
View File
@@ -0,0 +1,64 @@
import { NextRequest, NextResponse } from "next/server";
import {
StatusCodes,
} from 'http-status-codes';
import { narrow } from "@/types/typeUtils";
import { CLIENT_AUTH_TOKENS, SERVER_AUTH_TOKENS } from "./auth";
type Intents = 'server' | 'client';
const narrowIntents = (intents?: string | null) => narrow(intents, 'client', 'server') as Intents;
export async function GET(req: NextRequest) {
const url = new URL(req.url);
const token = url.searchParams.get('token');
const intents = narrowIntents(url.searchParams.get('intents'));
if (!token)
return NextResponse.json({ message: "token parameter required" });
switch (intents) {
case "server":
{
const auth = SERVER_AUTH_TOKENS[token];
if (!auth)
return NextResponse.json({ message: "Invalid token" });
delete SERVER_AUTH_TOKENS[token];
return NextResponse.json({ message: "ok", ...auth });
}
case "client":
{
const auth = CLIENT_AUTH_TOKENS[token];
if (!auth)
return NextResponse.json({ message: "Invalid token" }, { status: StatusCodes.NOT_FOUND });
return NextResponse.json({ message: "ok", auth });
}
}
}
export async function POST(req: NextRequest) {
let { intents, server_ip } = await req.json();
intents = String(intents).split('/');
const token = crypto.randomUUID();
const user_id = 12;
switch (narrowIntents(intents[0])) {
case 'server':
SERVER_AUTH_TOKENS[token] = {
user_id, // placeholder
server_ip: String(server_ip),
};
return NextResponse.json({ message: "ok", token });
case 'client':
CLIENT_AUTH_TOKENS[token] = user_id;
return NextResponse.json({ message: "ok", token });
default:
return NextResponse.json({ message: 'Invalid intentions' }, { status: StatusCodes.BAD_REQUEST });
}
}
+5
View File
@@ -0,0 +1,5 @@
import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({ message: "ok", version: "0.0.1" });
}
+11
View File
@@ -0,0 +1,11 @@
import axios from "axios";
// Create a temp token
axios.post('http://localhost:3000/api/auth', {
intents: 'server',
server_ip: 'localhost'
}).then((r) => {
console.log(r.data);
}).catch((e) => {
console.log(e);
});
+11
View File
@@ -0,0 +1,11 @@
export type StringMap<T> = {
[key: string]: T;
};
export function narrow<T>(s: T, defd: T, ...allowed: T[]): T {
if (allowed.includes(s) || s == defd) {
return s;
} else {
return defd;
}
}