Add user login, signup, and session.
This commit is contained in:
parent
3be05a9752
commit
f5466faa70
6 changed files with 101 additions and 36 deletions
|
|
@ -1,18 +1,24 @@
|
|||
export async function getUsers() {
|
||||
const response = await fetch("/api/users");
|
||||
if (!response.ok) {
|
||||
throw new Error(`Response status: ${response.status}`);
|
||||
}
|
||||
import { cmFetch } from "../cmFetch";
|
||||
import { Token, User } from "../types";
|
||||
|
||||
return response.json();
|
||||
export async function getUsers() {
|
||||
return cmFetch<User[]>(`/api/users`);
|
||||
}
|
||||
|
||||
export async function getUser(id: number) {
|
||||
const response = await fetch(`/api/users/${id}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Response status: ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
return cmFetch<User>(`/api/users/${id}`);
|
||||
}
|
||||
|
||||
export async function loginUser(user: FormData) {
|
||||
return cmFetch<Token>(`/api/users/login`, {
|
||||
method: "POST",
|
||||
body: user,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createUser(user: FormData) {
|
||||
return cmFetch<Token>(`/api/users`, {
|
||||
method: "POST",
|
||||
body: user,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,12 @@ export interface User {
|
|||
authority: number;
|
||||
}
|
||||
|
||||
export interface Token {
|
||||
access_token: string;
|
||||
|
||||
token_type: string;
|
||||
}
|
||||
|
||||
export interface Service {
|
||||
id: number | null;
|
||||
|
||||
|
|
|
|||
32
lib/server_functions/userAuth.ts
Normal file
32
lib/server_functions/userAuth.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { cookies } from "next/headers";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { createUser, loginUser } from "../api/helpers/users";
|
||||
import { Token } from "../api/types";
|
||||
|
||||
export async function login(formData: FormData) {
|
||||
"use server";
|
||||
const token = await loginUser(formData);
|
||||
await createSession(token);
|
||||
redirect("/admin/overview");
|
||||
}
|
||||
|
||||
export async function signup(formData: FormData) {
|
||||
// Technically same code as login for now but will do different stuff with it later so separating it early on
|
||||
"use server";
|
||||
const token = await createUser(formData);
|
||||
await createSession(token);
|
||||
redirect("/admin/overview");
|
||||
}
|
||||
|
||||
export async function createSession(token: Token) {
|
||||
const access_token = token.access_token;
|
||||
const cookieStore = await cookies();
|
||||
|
||||
cookieStore.set("access_token", access_token, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
});
|
||||
}
|
||||
Loading…
Reference in a new issue