Compare commits

...

3 Commits

Author SHA1 Message Date
Andreas Schaafsma
0410cc8655 add folder watchers for auto barrel export 2024-07-05 17:30:57 +02:00
Andreas Schaafsma
d829857378 bunch of refactoring 2024-07-05 17:30:33 +02:00
Andreas Schaafsma
8c6ef435b6 Moved Cookies.ts 2024-07-05 17:29:44 +02:00
16 changed files with 184 additions and 151 deletions

26
.vscode/settings.json vendored
View File

@ -8,8 +8,28 @@
"**/CVS": true, "**/CVS": true,
"**/.DS_Store": true, "**/.DS_Store": true,
"**/Thumbs.db": true, "**/Thumbs.db": true,
".**": true, "**/.next": true,
"node_modules": true, "**/.sqlite_queries": true,
"**/node_modules": true,
"**/.env.example": true,
"**/.vscode": true,
"**/.env**": true,
"**/.gitignore": true,
"**/.eslintrc.json": true,
"**/next-env.d.ts": true,
"**/package-lock.json": true,
"**/package.json": true,
"**/bucket": true,
}, },
"hide-files.files": [], "exportall.config.folderListener": [
"/src/util/api",
"/src/util/cookies",
"/src/util",
"/src/util/textgen"
],
"exportall.config.relExclusion": [
"/src/util/url",
"/src/util/api"
],
} }

View File

@ -1,101 +1,118 @@
'use server' "use server";
import { constructAPIUrl } from "@/util/url"; import { constructAPIUrl } from "@/util/url";
import { cookies } from "next/headers" import { cookies } from "next/headers";
import { parseSetCookie } from "@/util/parseSetCookie"; import { parseSetCookie } from "@/util/cookies";
import makeFetchCookie from 'fetch-cookie'; import makeFetchCookie from "fetch-cookie";
import fetchCookie from "fetch-cookie"; import fetchCookie from "fetch-cookie";
import { Attribute, Attributes } from "@sequelize/core";
import { User, Auth } from "@/models"; import { User, Auth } from "@/models";
import { AuthProps } from "@/providers/providers"; import { AuthProps } from "@/providers/providers";
import { ActionResult } from "./ActionResult";
type LoginReturn = { type LoginReturn = {
cookie?:unknown, cookie?: unknown;
errorMessage?: string; errorMessage?: string;
} };
async function attemptAPILogin(method:string,formData:FormData):Promise<LoginReturn|null> async function attemptAPILogin(
{ method: string,
formData: FormData
): Promise<LoginReturn | null> {
// Check if form data is present with required fields, return null if not // Check if form data is present with required fields, return null if not
if(!formData || !formData.get('input_username') || !formData.get('input_password')) return null; if (
!formData ||
!formData.get("input_username") ||
!formData.get("input_password")
)
return null;
// Instantiate header object // Instantiate header object
let headers: Headers = new Headers(); let headers: Headers = new Headers();
// Prepare fetchCookie // Prepare fetchCookie
const { CookieJar, Cookie } = fetchCookie.toughCookie; const { CookieJar, Cookie } = fetchCookie.toughCookie;
const jar = new CookieJar() const jar = new CookieJar();
const fetchWithCookie = makeFetchCookie(fetch, jar); const fetchWithCookie = makeFetchCookie(fetch, jar);
// Set Basic Auth // Set Basic Auth
headers.set('Authorization', `Basic ${Buffer.from(`${formData.get('input_username')}:${formData.get('input_password')}`).toString('base64')}`); headers.set(
"Authorization",
`Basic ${Buffer.from(
`${formData.get("input_username")}:${formData.get(
"input_password"
)}`
).toString("base64")}`
);
let res = await fetchWithCookie(constructAPIUrl("auth"), { let res = await fetchWithCookie(constructAPIUrl("auth"), {
method:'POST', method: "POST",
credentials: 'include', credentials: "include",
headers: headers, headers: headers,
}); });
console.log(jar.store.idx['localhost']['/']); console.log(jar.store.idx["localhost"]["/"]);
let koek = res.headers.getSetCookie(); let koek = res.headers.getSetCookie();
let cookieDict = parseSetCookie(koek); let cookieDict = parseSetCookie(koek);
await cookies().set('auth', cookieDict.auth); await cookies().set("auth", cookieDict.auth);
return { return {
cookie: cookieDict.auth, cookie: cookieDict.auth,
errorMessage:"" errorMessage: "",
}; };
// console.log(koek); // console.log(koek);
} }
export async function serverAttemptAuthenticateUser(_currentState: unknown, formData: FormData):Promise<LoginReturn|null> export async function serverAttemptAuthenticateUser(
{ _currentState: unknown,
formData: FormData
): Promise<LoginReturn | null> {
try { try {
const signInStatus = await attemptAPILogin('credentials', formData) const signInStatus = await attemptAPILogin("credentials", formData);
return signInStatus; return signInStatus;
} catch (error: any) { } catch (error: any) {
if (error) { if (error) {
switch (error.type) { switch (error.type) {
case 'CredentialsSignin': return { errorMessage: 'invalidCredentials' }; case "CredentialsSignin":
default: return { errorMessage: 'Something went wrong.' }; return { errorMessage: "invalidCredentials" };
default:
return { errorMessage: "Something went wrong." };
} }
} }
throw Error throw Error;
} }
} }
export async function serverValidateSessionCookie(koek:string):Promise<boolean> export async function serverValidateSessionCookie(
{ koek: string
): Promise<boolean> {
const validateSession = await fetch(constructAPIUrl("auth/validate"), { const validateSession = await fetch(constructAPIUrl("auth/validate"), {
method: "POST", method: "POST",
headers: { headers: {
Cookie: `auth=${koek};` Cookie: `auth=${koek};`,
} },
}); });
if(validateSession.status == 200) if (validateSession.status == 200) return true;
return true else return false;
else
return false
} }
export async function userIsAdmin():Promise<boolean> export async function userIsAdmin(): Promise<boolean> {
{ const cookieAuthValue = await cookies().get("auth")?.value;
const cookieAuthValue = await cookies().get('auth')?.value; const cookieAuthSanitized = cookieAuthValue
const cookieAuthSanitized = cookieAuthValue? JSON.parse(JSON.stringify(cookieAuthValue)) : ""; ? JSON.parse(JSON.stringify(cookieAuthValue))
: "";
if (!cookieAuthSanitized) return false; if (!cookieAuthSanitized) return false;
const parsedAuth = JSON.parse(cookieAuthSanitized); const parsedAuth = JSON.parse(cookieAuthSanitized);
if(!parsedAuth.id || !parsedAuth.token || !parsedAuth.user_id) return false if (!parsedAuth.id || !parsedAuth.token || !parsedAuth.user_id)
return false;
const p: AuthProps = { const p: AuthProps = {
auth: { auth: {
id: parsedAuth.id, id: parsedAuth.id,
token: parsedAuth.token, token: parsedAuth.token,
user_id:parsedAuth.user_id user_id: parsedAuth.user_id,
} },
}; };
const foundAuth = await Auth.findOne({ where: { id: p.auth?.id } }); const foundAuth = await Auth.findOne({ where: { id: p.auth?.id } });
@ -104,26 +121,30 @@ export async function userIsAdmin():Promise<boolean>
return true; return true;
} }
export async function getCookieAuth():Promise<AuthProps> export async function getCookieAuth(): Promise<AuthProps> {
{ const cookieAuthValue = await cookies().get("auth")?.value;
const cookieAuthValue = await cookies().get('auth')?.value; const cookieAuthSanitized = cookieAuthValue
const cookieAuthSanitized = cookieAuthValue? JSON.parse(JSON.stringify(cookieAuthValue)) : ""; ? JSON.parse(JSON.stringify(cookieAuthValue))
console.log("kanker koek") : "";
console.log("kanker koek");
if(!cookieAuthSanitized) return {} if (!cookieAuthSanitized) return {};
const kd = JSON.parse(cookieAuthSanitized); const kd = JSON.parse(cookieAuthSanitized);
if (!kd.id || !kd.token || !kd.user_id) return {}; if (!kd.id || !kd.token || !kd.user_id) return {};
const foundAuth = await Auth.findOne({where: { id: kd.id},include:{model:User}}); const foundAuth = await Auth.findOne({
where: { id: kd.id },
include: { model: User },
});
if (!foundAuth) return {}; if (!foundAuth) return {};
const authObject: AuthProps = { const authObject: AuthProps = {
auth: { auth: {
id: kd.id, id: kd.id,
token: kd.token, token: kd.token,
user_id:kd.user_id user_id: kd.user_id,
}, },
user: await foundAuth.user user: await foundAuth.user,
} };
return authObject; return authObject;
} }

View File

@ -8,7 +8,7 @@ import Link from "next/link";
import { redirect } from 'next/navigation'; import { redirect } from 'next/navigation';
import { Router } from "next/router"; import { Router } from "next/router";
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { truncateString } from "@/util/utils"; import { truncateString } from "@/util/strings";
// @ts-ignore // @ts-ignore
import { MDXRemote } from "next-mdx-remote/rsc"; import { MDXRemote } from "next-mdx-remote/rsc";
import { ExampleComponent } from "./article"; import { ExampleComponent } from "./article";

3
src/util/aifa.ts Normal file
View File

@ -0,0 +1,3 @@
import { ReactNode } from "react";
export const aifa = (a: ReactNode, b: ReactNode) => (a ? a : b);

View File

@ -1,2 +1,3 @@
export * from './error'; export * from './error';
export * from './getAPIEnv';
export * from './user'; export * from './user';

View File

@ -0,0 +1,2 @@
export * from './Cookies';
export * from './parseSetCookie';

View File

@ -1,10 +0,0 @@
class Gens{
public static loremipsum():String
{
return 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer egestas eros a imperdiet ultrices. Maecenas tincidunt tristique dolor, vitae dignissim ligula faucibus sit amet. Ut hendrerit elit eu elit molestie, vel consectetur leo accumsan. Phasellus ex mi, dignissim at aliquam at, rutrum eget mi. Curabitur pellentesque auctor nulla sed pulvinar. Maecenas scelerisque orci at sem finibus tincidunt. Mauris viverra pulvinar nibh. Etiam ornare purus leo, at cursus elit ornare nec. Suspendisse potenti. Sed nisl libero, sollicitudin vitae dignissim sit amet, laoreet sit amet odio. Duis rhoncus felis ut erat facilisis, vitae rutrum odio sollicitudin. Praesent et scelerisque eros. Praesent laoreet eu orci ut blandit. Morbi dapibus nibh urna, eget blandit quam aliquet vitae. Nulla quam metus, volutpat et vulputate vel, viverra sed diam.'
}
}
export default Gens;

View File

@ -1,10 +1,6 @@
export * from './api';
export * from './auth';
export * from './Cookies';
export * from './DeepPartial'; export * from './DeepPartial';
export * from './gens'; export * from './aifa';
export * from './getAPIEnv'; export * from './auth';
export * from './parseSetCookie'; export * from './cookies';
export * from './state'; export * from './state';
export * from './url'; export * from './strings';
export * from './utils';

View File

@ -0,0 +1 @@
export * from './loremipsum';

View File

@ -0,0 +1,6 @@
export function loremipsum():String
{
return 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer egestas eros a imperdiet ultrices. Maecenas tincidunt tristique dolor, vitae dignissim ligula faucibus sit amet. Ut hendrerit elit eu elit molestie, vel consectetur leo accumsan. Phasellus ex mi, dignissim at aliquam at, rutrum eget mi. Curabitur pellentesque auctor nulla sed pulvinar. Maecenas scelerisque orci at sem finibus tincidunt. Mauris viverra pulvinar nibh. Etiam ornare purus leo, at cursus elit ornare nec. Suspendisse potenti. Sed nisl libero, sollicitudin vitae dignissim sit amet, laoreet sit amet odio. Duis rhoncus felis ut erat facilisis, vitae rutrum odio sollicitudin. Praesent et scelerisque eros. Praesent laoreet eu orci ut blandit. Morbi dapibus nibh urna, eget blandit quam aliquet vitae. Nulla quam metus, volutpat et vulputate vel, viverra sed diam.'
}

View File

@ -0,0 +1,7 @@
export function truncateString(str:string = '', num:number = 255) {
if (str.length > num) {
return str.slice(0, num) + "...";
} else {
return str;
}
}

View File

@ -1,6 +1,6 @@
'use server' 'use server'
import { getAPIEnv } from "../getAPIEnv"; import { getAPIEnv } from "../api/getAPIEnv";
export function constructAPIUrl(endpoint:string){ export function constructAPIUrl(endpoint:string){
const { schema, host, port, basepath } = getAPIEnv(); const { schema, host, port, basepath } = getAPIEnv();

View File

@ -1,14 +0,0 @@
'server only'
import { ReactNode } from "react";
import Gens from "./gens";
function truncateString(str:string = '', num:number = 255) {
if (str.length > num) {
return str.slice(0, num) + "...";
} else {
return str;
}
}
export { Gens, truncateString }
export const aifa = (a: ReactNode, b: ReactNode) => (a ? a : b);