Skip to content

turso test #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .astro/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -623,5 +623,5 @@ declare module 'astro:content' {

type AnyEntryMap = ContentEntryMap & DataEntryMap;

type ContentConfig = typeof import("../src/content/config");
export type ContentConfig = typeof import("../src/content/config.js");
}
87 changes: 56 additions & 31 deletions astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,40 +13,65 @@ import metaTags from "astro-meta-tags";
// https://astro.build/config
export default defineConfig({
// ...
integrations: [expressiveCode({
theme: ["dracula-soft"]
}), mdx(), react(), metaTags()],
integrations: [
expressiveCode({
theme: ["dracula-soft"],
}),
mdx(),
react(),
metaTags(),
],
markdown: {
remarkPlugins: [],
rehypePlugins: [rehypeSlug, [rehypeAutolinkHeadings, {
behavior: "wrap"
}], [rehypeToc, {
customizeTOC: toc => {
if (toc.children[0].children?.length > 0) {
return toc;
}
return false;
},
customizeTOCItem: (toc, heading) => {
const headingContent = heading.children?.[0];
if (headingContent.children.length > 1) {
toc.children[0].children = headingContent.children;
}
return toc;
}
}], [rehypeCustomEmoji, {
emojis: {
bobaparty: "/emojis/bobaparty.png",
bobatwt: "/emojis/bobatwt.png",
bobaeyes: "/emojis/bobaeyes.png"
},
className: "custom-emoji"
}], rehypeAddAltText]
rehypePlugins: [
rehypeSlug,
[
rehypeAutolinkHeadings,
{
behavior: "wrap",
},
],
[
rehypeToc,
{
customizeTOC: (toc) => {
if (toc.children[0].children?.length > 0) {
return toc;
}
return false;
},
customizeTOCItem: (toc, heading) => {
const headingContent = heading.children?.[0];
if (headingContent.children.length > 1) {
toc.children[0].children = headingContent.children;
}
return toc;
},
},
],
[
rehypeCustomEmoji,
{
emojis: {
bobaparty: "/emojis/bobaparty.png",
bobatwt: "/emojis/bobatwt.png",
bobaeyes: "/emojis/bobaeyes.png",
},
className: "custom-emoji",
},
],
rehypeAddAltText,
],
},
redirects: {
"/subscribe": "/support-me"
"/subscribe": "/support-me",
},
output: "hybrid",
output: "server",
adapter: vercel(),
site: "https://www.essentialrandomness.com"
});
site: "https://www.essentialrandomness.com",
vite: {
optimizeDeps: {
exclude: ["oslo"],
},
},
});
10 changes: 10 additions & 0 deletions drizzle.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { defineConfig } from "drizzle-kit";
export default defineConfig({
schema: "./src/db/schema.ts",
out: "./src/db/drizzle",
driver: "turso",
dbCredentials: {
url: process.env.TURSO_DB_LOGIN!,
authToken: process.env.TURSO_DB_AUTH,
},
});
10 changes: 8 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,21 @@
"@astrojs/mdx": "2.0.6",
"@astrojs/react": "3.0.9",
"@astrojs/rss": "^4.0.3",
"@astrojs/vercel": "^7.0.1",
"@astrojs/vercel": "^7.1.1",
"@libsql/client": "^0.4.3",
"@lucia-auth/adapter-drizzle": "^1.0.0",
"@paypal/paypal-js": "^7.0.0",
"@types/react": "^18.0.21",
"@types/react-dom": "^18.0.6",
"astro": "4.2.2",
"astro": "^4.3.2",
"astro-expressive-code": "^0.32.2",
"astro-icon": "^0.8.1",
"astro-meta-tags": "^0.2.1",
"clsx": "^2.0.0",
"drizzle-orm": "^0.29.3",
"lucia": "^3.0.1",
"marked": "^7.0.4",
"oslo": "^1.0.4",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-icons": "npm:@lorenzobloedow/react-icons",
Expand All @@ -37,6 +42,7 @@
"unist-util-select": "^5.1.0"
},
"devDependencies": {
"drizzle-kit": "^0.20.14",
"hast-util-from-html-isomorphic": "^2.0.0",
"postcss-nesting": "^12.0.1",
"prettier": "^3.0.1",
Expand Down
15 changes: 15 additions & 0 deletions src/auth/createUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// pages/api/signup.ts
import { generateId } from "lucia";
import { Argon2id } from "oslo/password";
import { db } from "../db";
import { users } from "../db/schema";

const userId = generateId(15);
const hashedPassword = await new Argon2id().hash("blorbos");

export const createUser = async () =>
await db.insert(users).values({
id: userId,
username: "bobatan",
hashed_password: hashedPassword,
});
30 changes: 30 additions & 0 deletions src/auth/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { DrizzleSQLiteAdapter } from "@lucia-auth/adapter-drizzle";
import { db } from "../db";
import { sessions, users } from "../db/schema";
import { Lucia } from "lucia";

declare module "lucia" {
interface Register {
Lucia: typeof Lucia;
DatabaseUserAttributes: DatabaseUserAttributes;
}
}

interface DatabaseUserAttributes {
username: string;
}

const adapter = new DrizzleSQLiteAdapter(db, sessions, users);
export const auth = new Lucia(adapter, {
sessionCookie: {
attributes: {
secure: import.meta.env.PROD,
},
},
getUserAttributes: (attributes) => {
return {
// attributes has the type of DatabaseUserAttributes
username: attributes.username,
};
},
});
9 changes: 9 additions & 0 deletions src/db/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { drizzle } from "drizzle-orm/libsql";
import { createClient } from "@libsql/client";

const client = createClient({
url: import.meta.env.TURSO_DB_LOGIN!,
authToken: import.meta.env.TURSO_DB_AUTH,
});

export const db = drizzle(client);
15 changes: 15 additions & 0 deletions src/db/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { text, integer, sqliteTable, int } from "drizzle-orm/sqlite-core";

export const users = sqliteTable("users", {
id: text("id").primaryKey().notNull(),
username: text("username").notNull().unique(),
hashed_password: text("hashed_password"),
});

export const sessions = sqliteTable("sessions", {
id: text("id").notNull().primaryKey(),
userId: text("user_id")
.notNull()
.references(() => users.id),
expiresAt: integer("expires_at").notNull(),
});
7 changes: 7 additions & 0 deletions src/env.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,9 @@
/// <reference path="../.astro/types.d.ts" />
/// <reference types="astro/client" />

declare namespace App {
interface Locals {
session: import("lucia").Session | null;
user: import("lucia").User | null;
}
}
19 changes: 17 additions & 2 deletions src/layouts/Layout.astro
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ const {
description = "Ms Boba's experimental website. Open for business while construction is ongoing.",
preview = "/og-image.png",
} = Astro.props;

const user = Astro.locals.user;
---

<!doctype html>
Expand Down Expand Up @@ -54,7 +56,20 @@ const {
src="https://plausible.io/js/script.js"></script>
</head>
<body>
<Nav />
<slot />
{
Astro.locals.user ? (
<div>Hello {Astro.locals.user.username}</div>
) : (
<form method="post" action="/api/login">
<label for="username">Username</label>
<input id="username" name="username" />
<label for="password">Password</label>
<input id="password" name="password" />
<button>Continue</button>
</form>
)
}
</body>
<Nav />
<slot />
</html>
47 changes: 47 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { auth } from "./auth";
import { verifyRequestOrigin } from "lucia";
import { defineMiddleware } from "astro:middleware";

export const onRequest = defineMiddleware(async (context, next) => {
if (context.request.method !== "GET") {
const originHeader = context.request.headers.get("Origin");
const hostHeader = context.request.headers.get("Host");
if (
!originHeader ||
!hostHeader ||
!verifyRequestOrigin(originHeader, [hostHeader])
) {
return new Response(null, {
status: 403,
});
}
}

const sessionId = context.cookies.get(auth.sessionCookieName)?.value ?? null;
if (!sessionId) {
context.locals.user = null;
context.locals.session = null;
return next();
}

const { session, user } = await auth.validateSession(sessionId);
if (session && session.fresh) {
const sessionCookie = auth.createSessionCookie(session.id);
context.cookies.set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
);
}
if (!session) {
const sessionCookie = auth.createBlankSessionCookie();
context.cookies.set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
);
}
context.locals.session = session;
context.locals.user = user;
return next();
});
43 changes: 43 additions & 0 deletions src/pages/api/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { auth } from "../../auth";
import { Argon2id } from "oslo/password";

import type { APIContext } from "astro";
import { db } from "../../db";
import { users } from "../../db/schema";
import { eq } from "drizzle-orm";

export async function POST(context: APIContext): Promise<Response> {
const formData = await context.request.formData();
const username = formData.get("username") as string;
const password = formData.get("password") as string;

const existingUser = (
await db
.select()
.from(users)
.where(eq(users.username, username))
.limit(1)
.execute()
)[0];

const validPassword = await new Argon2id().verify(
existingUser.hashed_password!,
password
);
console.log(validPassword);
if (!validPassword) {
return new Response("Incorrect username or password", {
status: 400,
});
}

const session = await auth.createSession(existingUser.id, {});
const sessionCookie = auth.createSessionCookie(session.id);
context.cookies.set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
);

return context.redirect("/");
}
2 changes: 2 additions & 0 deletions src/pages/posts/[...blogId].astro
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import { getCollection } from "astro:content";
import Layout from "../../layouts/Layout.astro";
import PostStatus from "../../components/PostStatus.astro";
import { users } from "../../db/schema";
import { db } from "../../db";

export async function getStaticPaths() {
const posts = await getCollection("posts");
Expand Down
1 change: 1 addition & 0 deletions src/pages/posts/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,4 @@ const displayPosts = requestedTags.length
}
}
</style>
../../db../../db/schema
Loading