proper login flow

This commit is contained in:
Julian 2023-04-25 19:56:52 -04:00
parent 084a2f7618
commit d5ec97ed73
Signed by untrusted user: NotNite
GPG key ID: BD91A5402CCEB08A
6 changed files with 213 additions and 2 deletions

View file

@ -0,0 +1,41 @@
import * as ldap from "@/ldap";
import { createAuthTicket } from "@/auth";
type RequestBody = {
username: string;
password: string;
};
export async function POST(request: Request) {
const { username, password } = (await request.json()) as RequestBody;
if (
username == undefined ||
typeof username !== "string" ||
password == undefined ||
typeof password !== "string"
) {
return new Response(
JSON.stringify({
ok: false,
error: "invalidBody"
}),
{ status: 400 }
);
}
const valid = await ldap.validateUser(username, password);
if (!valid) {
return new Response(
JSON.stringify({
ok: false,
error: "invalidCredentials"
}),
{ status: 401 }
);
}
const ticket = await createAuthTicket(username);
// not confident if we can set-cookie and I cba to try
return new Response(JSON.stringify({ ok: true, ticket }));
}

52
src/app/login/page.tsx Normal file
View file

@ -0,0 +1,52 @@
"use client";
import styles from "@/app/page.module.css";
import React from "react";
// TODO: use input from register & un programmer art this
export default function Page() {
const usernameRef = React.useRef<HTMLInputElement>(null);
const passwordRef = React.useRef<HTMLInputElement>(null);
return (
<main className={styles.main}>
<form
style={{ display: "flex", flexDirection: "column" }}
onSubmit={async (e) => {
e.preventDefault();
const username = usernameRef.current?.value ?? "";
const password = passwordRef.current?.value ?? "";
const req = await fetch("/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username,
password
})
});
if (req.status === 200) {
const res: { ticket: string } = await req.json();
document.cookie = `ticket=${res.ticket}; path=/;`;
window.location.href = "/me";
} else {
// todo error handling lol
}
}}
>
<input type="text" placeholder="Username" ref={usernameRef} required />
<input
type="password"
placeholder="Password"
ref={passwordRef}
required
/>
<input type="submit" value="Login" />
</form>
</main>
);
}

View file

@ -6,8 +6,16 @@ export default function Home() {
<main className={styles.main}>
<Image src="/icon.svg" alt="gluestick logo" width="256" height="256" />
<p>
<a href="/oauth/discord/login">login debug</a>
<p
style={{
display: "flex",
flexDirection: "column"
}}
>
<a href="/login">login</a>
<a href="/me">me</a>
<a href="/oauth/discord/login">discord</a>
<a href="/register">register</a>
</p>
</main>
);

View file

@ -1,5 +1,6 @@
import prisma from "@/prisma";
import { cookies } from "next/dist/client/components/headers";
import { v4 } from "uuid";
export async function getUserFromRequest(request: Request) {
const authorization = request.headers
@ -41,3 +42,50 @@ export async function getUserFromPage() {
});
return user;
}
export async function createAuthTicket(username: string) {
let user = await prisma.user.findFirst({
where: {
username: username
}
});
// It's possible we haven't made a user yet (already existing accounts)
if (user === null) {
user = await prisma.user.create({
data: {
username: username
}
});
}
const authTicket = await prisma.authTicket.upsert({
where: {
userId: user!.id
},
create: {
userId: user!.id,
ticket: v4(),
expiresAt: new Date(Date.now() + 86400000)
},
update: {
ticket: v4(),
expiresAt: new Date(Date.now() + 86400000)
}
});
await prisma.user.update({
where: {
id: user!.id
},
data: {
authTicket: {
connect: {
id: authTicket.id
}
}
}
});
return authTicket.ticket;
}

View file

@ -152,3 +152,18 @@ export async function setPassword(user: string, password: string) {
await client.exop("1.3.6.1.4.1.4203.1.11.1", writer.buffer);
}
export async function validateUser(username: string, password: string) {
const client = new Client({
url: `ldap://${process.env.LDAP_HOST}:3890`
});
try {
const dn = `uid=${username},ou=people,${process.env.LDAP_DC}`;
await client.bind(dn, password);
await client.unbind();
return true;
} catch (e) {
return false;
}
}

View file

@ -1,3 +1,50 @@
import { PrismaClient } from "@prisma/client";
import { DiscordAccessTokenResponse } from "./app/oauth/discord/oauth";
const prisma = new PrismaClient();
// refresh 6 hours before expiry
async function refreshDiscordTokens() {
const refreshWindow = 6 * 60 * 60 * 1000;
const discordAuths = await prisma.discordAuth.findMany({
where: {
expiresAt: {
lte: new Date(Date.now() + refreshWindow)
}
}
});
for (const discordAuth of discordAuths) {
const req = await fetch("https://discord.com/api/oauth2/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: new URLSearchParams({
client_id: process.env.DISCORD_CLIENT_ID,
client_secret: process.env.DISCORD_CLIENT_SECRET,
grant_type: "refresh_token",
refresh_token: discordAuth.refreshToken
}).toString()
});
const res: DiscordAccessTokenResponse = await req.json();
await prisma.discordAuth.update({
where: {
id: discordAuth.id
},
data: {
accessToken: res.access_token,
refreshToken: res.refresh_token,
expiresAt: new Date(Date.now() + res.expires_in * 1000)
}
});
}
}
setInterval(async () => {
await refreshDiscordTokens();
}, 60 * 1000);
export default prisma;