Compare commits

..

No commits in common. "0410cc8655dfb9b6d3d12dc03fc61be20dddb939" and "5f97af3f96c9a139f89015a36d75f6d4f3c3e125" have entirely different histories.

16 changed files with 151 additions and 184 deletions

26
.vscode/settings.json vendored
View File

@ -8,28 +8,8 @@
"**/CVS": true, "**/CVS": true,
"**/.DS_Store": true, "**/.DS_Store": true,
"**/Thumbs.db": true, "**/Thumbs.db": true,
"**/.next": true, ".**": true,
"**/.sqlite_queries": true, "node_modules": 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,
}, },
"exportall.config.folderListener": [ "hide-files.files": [],
"/src/util/api",
"/src/util/cookies",
"/src/util",
"/src/util/textgen"
],
"exportall.config.relExclusion": [
"/src/util/url",
"/src/util/api"
],
} }

View File

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

View File

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

View File

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

View File

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

10
src/util/gens.ts Normal file
View File

@ -0,0 +1,10 @@
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,6 +1,10 @@
export * from './DeepPartial'; export * from './api';
export * from './aifa';
export * from './auth'; export * from './auth';
export * from './cookies'; export * from './Cookies';
export * from './DeepPartial';
export * from './gens';
export * from './getAPIEnv';
export * from './parseSetCookie';
export * from './state'; export * from './state';
export * from './strings'; export * from './url';
export * from './utils';

View File

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

View File

@ -1,6 +0,0 @@
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

@ -1,7 +0,0 @@
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 "../api/getAPIEnv"; import { getAPIEnv } from "../getAPIEnv";
export function constructAPIUrl(endpoint:string){ export function constructAPIUrl(endpoint:string){
const { schema, host, port, basepath } = getAPIEnv(); const { schema, host, port, basepath } = getAPIEnv();

14
src/util/utils.ts Normal file
View File

@ -0,0 +1,14 @@
'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);