-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Start of sessions & authentication work
- Loading branch information
1 parent
6b8f78b
commit 722b6ac
Showing
26 changed files
with
1,344 additions
and
43 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 14 additions & 0 deletions
14
...ns/files/1700484202967_cf2e67f7-3008-4e7f-b3d6-a849bde83e30_create_auth_sessions_table.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
export function up(): string { | ||
return ` | ||
CREATE TABLE auth_sessions ( | ||
id text PRIMARY KEY NOT NULL, | ||
user_id text NOT NULL, | ||
expires_at timestamp NOT NULL, | ||
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE | ||
);` | ||
} | ||
|
||
export function down(): string | void { | ||
return 'DROP TABLE auth_sessions' | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import { z } from "zod"; | ||
|
||
import type { ApiHandlerArgs, ApiHandlerResponse } from "api/index.ts"; | ||
|
||
export function post({ payload }: ApiHandlerArgs): ApiHandlerResponse { | ||
let body = payloadParser(payload); | ||
let session = AuthSession.create(body); | ||
|
||
if (session.ok) { | ||
throw new Response("", { status: 404 }); | ||
} | ||
|
||
return new Response(JSON.stringify({}), { | ||
headers: { "content-type": "application/json" }, | ||
status: 400, | ||
}) | ||
} | ||
|
||
const sessionPayloadSchema = z.object({ | ||
email: z.string().email(), | ||
password: z.string().min(3).max(255), | ||
}); | ||
|
||
// used to parse the body of a request | ||
export const payloadParser = (raw: unknown, parser: typeof sessionPayloadSchema = sessionPayloadSchema) => { | ||
return parser.parse(raw); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,8 @@ | ||
/** @type {import('eslint').Linter.Config} */ | ||
module.exports = { | ||
extends: ["@remix-run/eslint-config", "@remix-run/eslint-config/node"], | ||
extends: ["@remix-run/eslint-config", "@remix-run/eslint-config/node", "prettier"], | ||
plugins: ["prettier"], | ||
rules: { | ||
"prettier/prettier": "error" | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import { Button as RAButton, ButtonProps } from "react-aria-components"; | ||
|
||
export default function Button({ children, className }: ButtonProps) { | ||
return ( | ||
<RAButton | ||
type="submit" | ||
className={`px-2 py-1 border border-gray-200 rounded-md ${className || ""}`} | ||
> | ||
{children} | ||
</RAButton> | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,29 @@ | ||
import {TextField, Label, Input as RAInput} from 'react-aria-components'; | ||
import { TextField, Label, Input as RAInput } from "react-aria-components"; | ||
|
||
export default function InputComponent({label, name, type, value, onChange}: InputProps) { | ||
type InputProps = { | ||
label: string; | ||
name: string; | ||
type: "email" | "password" | "text"; | ||
value?: string | number; | ||
}; | ||
|
||
export default function InputComponent({ | ||
label, | ||
name, | ||
type, | ||
value, | ||
}: InputProps) { | ||
return ( | ||
<TextField> | ||
<Label>Email</Label> | ||
<RAInput type='email' | ||
className="px-2 py-1 border border-gray-200 rounded-md" | ||
/> | ||
</TextField> | ||
) | ||
<TextField> | ||
<Label> | ||
{label} | ||
<RAInput | ||
type={type} | ||
name={name} | ||
className="block px-2 py-1 border border-gray-200 rounded-md" | ||
value={value} | ||
/> | ||
</Label> | ||
</TextField> | ||
); | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import type AuthSession from "../auth-session"; | ||
|
||
const Api = { | ||
postSession: async (session: AuthSession) => { | ||
try { | ||
let resp = await fetch("http://localhost:3008/api/sessions", { | ||
headers: { | ||
Accept: "application/json", | ||
"Content-Type": "application/json", | ||
}, | ||
method: "POST", | ||
body: JSON.stringify(session.attributes), | ||
}); | ||
|
||
if (resp.ok) { | ||
let data = await resp.json(); // ?.token; | ||
if (data) { | ||
return { isError: false, token: data.token }; | ||
} | ||
} | ||
return { isError: true, errors: { email: ["is required"] } }; | ||
} catch (e) { | ||
console.log(e); | ||
return { isError: true, errors: { networkError: e } }; | ||
} | ||
}, | ||
}; | ||
|
||
export default Api; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { Request, FormData } from "@remix-run/node"; | ||
import { expect, test, describe } from "vitest"; | ||
|
||
import AuthSession from "."; | ||
|
||
describe("AuthSession", () => { | ||
test("Should show errors when no email is provided", async () => { | ||
let req = new Request("http://example.com", { | ||
method: "POST", | ||
body: new FormData(), | ||
}); | ||
|
||
let session = new AuthSession(req); | ||
await session.create(); | ||
|
||
expect(session.isValid).toBeFalsy(); | ||
expect(session.errors.email).toEqual(["is required"]); | ||
}); | ||
|
||
test("it should show errors from requestJWTForSession", async () => { | ||
let fd = new FormData(); | ||
fd.set("email", "hey"); | ||
fd.set("password", "password"); | ||
|
||
let jwtRequest = async () => { | ||
return { isError: true, errors: { "*": ["Email/pw combo is invalid"] } }; | ||
}; | ||
|
||
let req = new Request("http://example.com", { | ||
method: "POST", | ||
body: fd, | ||
}); | ||
|
||
let session = new AuthSession(req, { requestJWTForSession: jwtRequest }); | ||
await session.create(); | ||
|
||
expect(session.isValid).toBeFalsy(); | ||
expect(session.errors["*"]).toEqual(["Email/pw combo is invalid"]); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
import type { ValidationErrors } from "../validate"; | ||
import validate from "../validate"; | ||
import Api from "../api"; | ||
|
||
type AuthSessionOptions = { | ||
validateData?: typeof validate; | ||
requestJWTForSession?: (session: AuthSession) => Promise<{ | ||
isError: boolean; | ||
errors?: any; | ||
token?: string; | ||
}>; | ||
}; | ||
|
||
export default class AuthSession { | ||
private request: Request; | ||
private requestJWTForSession: ( | ||
session: AuthSession, | ||
) => Promise<{ isError: boolean; errors?: any; token?: string }>; | ||
|
||
attributes: { email: string; password: string }; | ||
errors: ValidationErrors = {}; | ||
token: string = ""; | ||
validateData: typeof validate; | ||
|
||
constructor(req: Request, options?: AuthSessionOptions) { | ||
const { validateData = validate, requestJWTForSession = Api.postSession } = | ||
options || {}; | ||
|
||
this.attributes = { email: "", password: "" }; | ||
this.request = req; | ||
this.validateData = validateData; | ||
this.requestJWTForSession = requestJWTForSession; | ||
} | ||
|
||
static init(req: Request) { | ||
return new AuthSession(req); | ||
} | ||
|
||
async create() { | ||
let formData = await this.request.formData(); | ||
this.attributes = { | ||
email: String(formData.get("email")), | ||
password: String(formData.get("password")), | ||
}; | ||
|
||
let validationResult = this.validateData( | ||
{ email: true, password: true }, | ||
formData, | ||
); | ||
|
||
if (validationResult.isInValid) { | ||
this.errors = validationResult.errors; | ||
return this; | ||
} | ||
|
||
let tokenResult = await this.requestJWTForSession(this); | ||
if (tokenResult.isError) { | ||
this.errors = tokenResult.errors; | ||
return this; | ||
} | ||
|
||
if (tokenResult.token) { | ||
this.token = tokenResult.token; | ||
} | ||
|
||
return this; | ||
} | ||
|
||
get isValid() { | ||
return Object.keys(this.errors).length === 0; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import { expect, test, describe } from "vitest"; | ||
|
||
import { create } from "./session-token"; | ||
|
||
describe("create session token", () => { | ||
test("should return a jwt if email and password are valid", async () => { | ||
expect( | ||
create({ | ||
email: "ok", | ||
password: "ok", | ||
}) | ||
).toEqual("jwt"); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
type UserFields = { | ||
email: string; | ||
password: string; | ||
}; | ||
|
||
// export function create( |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
export default async function formDataFromRequest(req: Request) { | ||
const formData = await req.clone().formData(); | ||
const path = new URL(req.url).pathname; | ||
|
||
return ( | ||
path + | ||
"\n" + | ||
[...formData.entries()].map(([k, v]) => ` ${k}: ${v}`).join("\n") | ||
); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
export default class Logger { | ||
static debug(...args: any[]) { | ||
if (process.env.NODE_ENV !== "production") { | ||
console.debug(...args); | ||
} | ||
} | ||
} |
Oops, something went wrong.