Skip to content

Commit 6ece096

Browse files
Decouple Blitz RPC and Blitz Auth (#3943)
* inital unwrapping of blitz rpc from blitz auth * fix linr * Revert "fix linr" This reverts commit 000e2c7. * remove duplication of code and dynamically import blitz auth if plugin is used * return types to blitz-auth and import in rpc as types * remove excess files from git diff * remove todo ts-ignore * add changeset * better error messages * Update odd-cars-fry.md * switch from blitz log to console - due to import error. * Revert "Merge branch 'rpc-without-auth' of https://github.com/blitz-js/blitz into rpc-without-auth" This reverts commit 5b45d65, reversing changes made to b15dfa6. * Revert "switch from blitz log to console - due to import error." This reverts commit b15dfa6. * Revert "better error messages" This reverts commit 75922cb. * fix location of seting global variable * better error message due to dynamic import * allow setting csrf token in blitz rpc * cleanup * fix * pnpm lock fix and update csrf api * fix global.ts type definition * remove change to merge * fix pnpm-lock * update integration-tests to work without blitz-auth * initial working commit after switch to plugin system * fix pnpm-lock * readd the changeset * update hook names * Revert "readd the changeset" This reverts commit 796f3f5. * Revert "update hook names" This reverts commit fb127ed. * Revert "fix pnpm-lock" This reverts commit d7447b5. * Revert "Revert "fix pnpm-lock"" This reverts commit c2f21aa. * Revert "Revert "update hook names"" This reverts commit 4b66846. * Revert "Revert "readd the changeset"" This reverts commit c95d150. * add header to rpc plugin * pnpm lock fix * cleanup - change global hook names to prefix with __BLITZ * initial commit suggestion - TODO Fix types * fix most type assertions * fix error without blitz auth * add typea to events and middleware reducers * implement suggestion * Apply suggestions from code review Co-authored-by: Brandon Bayer <[email protected]> * move onSessionCreated event from blitz-auth to blitz-rpc * move globals to blitz core, move event listener to blitz-next * remove middlewareCtx to Ctx * fix imports * improve type definition of hook types * format * Revert "remove middlewareCtx to Ctx" This reverts commit 4259b4d. * Revert "fix imports" This reverts commit 7422bfa. * revert changes from MiddlewareCtx to Ctx * pnpm lock and other fixes * remove type assertion * merge to one `Array.reduce` * Apply suggestions from code review Co-authored-by: Brandon Bayer <[email protected]> * implement review suggestions * Update packages/blitz/src/types.ts * add unit tests * cleanup * Update packages/blitz/tests/plugin.test.ts * add providers to plugin reduce * add initial integration test for full blitz rpc+auth and custom client plugins * test commenting out playwright install * fixes * remove changes related to console.log checking * test * try with different command * comment * another try * try adding global install * change console.log to console.info for better identification * fix db * lowdb import fix * convert from lowdb to prisma * fix blitz build error * add custom plugin events to integration-tests * manipulate the timing of event firing * fix * check * add middleware tests * fix * fix commented test and cleanup * add the migration file Co-authored-by: Brandon Bayer <[email protected]>
1 parent a059627 commit 6ece096

File tree

77 files changed

+2168
-542
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

77 files changed

+2168
-542
lines changed

.changeset/eighty-apes-sleep.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
"blitz": minor
3+
"@blitzjs/auth": minor
4+
"@blitzjs/next": minor
5+
"@blitzjs/rpc": minor
6+
---
7+
8+
Decoupled Blitz RPC from Blitz Auth to allow independent use.

.github/workflows/main.yml

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,6 @@ concurrency:
88
group: ${{ github.workflow }}-${{ github.ref }}
99
cancel-in-progress: true
1010

11-
env:
12-
TURBO_TOKEN: 05de0230f01174d1f8cb4845a01dc6c895ce28f04ebef2318ab11615791b871c35eabbf8
13-
TURBO_TEAM: foo
14-
1511
jobs:
1612
lint:
1713
name: Lint
@@ -29,11 +25,6 @@ jobs:
2925
- name: Install dependencies
3026
run: pnpm install --frozen-lockfile
3127
- run: pnpm manypkg check
32-
- name: Turborepo local server
33-
uses: felixmosh/turborepo-gh-artifacts@v1
34-
with:
35-
repo-token: ${{ secrets.GITHUB_TOKEN }}
36-
server-token: ${{ env.TURBO_TOKEN }}
3728
- name: Build
3829
run: pnpm build
3930
- name: Lint
@@ -52,11 +43,6 @@ jobs:
5243
with:
5344
node-version: 16
5445
cache: "pnpm"
55-
- name: Turborepo local server
56-
uses: felixmosh/turborepo-gh-artifacts@v1
57-
with:
58-
repo-token: ${{ secrets.GITHUB_TOKEN }}
59-
server-token: ${{ env.TURBO_TOKEN }}
6046
- run: pnpm install --frozen-lockfile
6147
- name: Build
6248
run: pnpm build
@@ -89,12 +75,6 @@ jobs:
8975
node-version: 16
9076
cache: "pnpm"
9177

92-
- name: Turborepo local server
93-
uses: felixmosh/turborepo-gh-artifacts@v1
94-
with:
95-
repo-token: ${{ secrets.GITHUB_TOKEN }}
96-
server-token: ${{ env.TURBO_TOKEN }}
97-
9878
- name: Install dependencies
9979
run: pnpm install --frozen-lockfile
10080
shell: bash
@@ -154,18 +134,14 @@ jobs:
154134
node-version: ${{ matrix.NODE_VERSION }}
155135
cache: "pnpm"
156136

157-
- name: Turborepo local server
158-
uses: felixmosh/turborepo-gh-artifacts@v1
159-
with:
160-
repo-token: ${{ secrets.GITHUB_TOKEN }}
161-
server-token: ${{ env.TURBO_TOKEN }}
162-
163137
- name: Install dependencies
164138
run: pnpm install --frozen-lockfile
165139
shell: bash
166140

167141
- name: Install playwright
168-
run: npx playwright install --with-deps
142+
run: |
143+
npm i -g playwright
144+
PLAYWRIGHT_BROWSERS_PATH=$HOME/pw-browsers npx playwright install
169145
shell: bash
170146

171147
- name: Build

apps/toolkit-app/src/blitz-client.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
import { AuthClientPlugin } from "@blitzjs/auth"
22
import { setupBlitzClient } from "@blitzjs/next"
33
import { BlitzRpcPlugin } from "@blitzjs/rpc"
4+
import { BlitzCustomPlugin } from "./custom-plugin/plugin"
45

56
export const { withBlitz } = setupBlitzClient({
67
plugins: [
78
AuthClientPlugin({
89
cookiePrefix: "web-cookie-prefix",
910
}),
1011
BlitzRpcPlugin({}),
12+
BlitzCustomPlugin({}),
1113
],
1214
})
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { createClientPlugin } from "blitz"
2+
3+
type CustomPluginOptions = {
4+
// ... your options
5+
}
6+
7+
export const BlitzCustomPlugin = createClientPlugin<CustomPluginOptions, {}>(
8+
(options?: CustomPluginOptions) => {
9+
// ... your plugin code
10+
console.log("Custom plugin loaded")
11+
return {
12+
events: {
13+
onSessionCreated: async () => {
14+
// Called when a new session is created - Usually when the user logs in or logs out
15+
console.log("onSessionCreated in custom plugin")
16+
},
17+
onRpcError: async () => {
18+
// Called when an RPC call fails
19+
console.log("onRpcError in custom plugin")
20+
},
21+
},
22+
middleware: {
23+
beforeHttpRequest: (req) => {
24+
//make changes to the request options before RPC call
25+
req.headers = { ...req.headers, ...{ customHeader: "customHeaderValue" } }
26+
return req
27+
},
28+
beforeHttpResponse: (res) => {
29+
//make changes to the response before returning to the caller
30+
return res
31+
},
32+
},
33+
exports: () => ({
34+
// ... your exports
35+
}),
36+
}
37+
}
38+
)

integration-tests/auth-with-rpc/.env

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
SESSION_SECRET_KEY=hsdenhJfpLHrGjgdgg3jdF8g2bYD2PaQ
2+
HEADLESS=true
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
module.exports = require("@blitzjs/next/eslint")
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
node_modules
2+
# Keep environment variables out of version control
3+
*.sqlite
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import {enhancePrisma} from "blitz"
2+
import {PrismaClient} from "@prisma/client"
3+
4+
const EnhancedPrisma = enhancePrisma(PrismaClient)
5+
export * from "@prisma/client"
6+
const prisma = new EnhancedPrisma()
7+
export default prisma
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
-- CreateTable
2+
CREATE TABLE "User" (
3+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
4+
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
5+
"updatedAt" DATETIME NOT NULL,
6+
"name" TEXT,
7+
"email" TEXT NOT NULL,
8+
"hashedPassword" TEXT,
9+
"role" TEXT NOT NULL DEFAULT 'user'
10+
);
11+
12+
-- CreateTable
13+
CREATE TABLE "Session" (
14+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
15+
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
16+
"updatedAt" DATETIME NOT NULL,
17+
"expiresAt" DATETIME,
18+
"handle" TEXT NOT NULL,
19+
"userId" INTEGER,
20+
"hashedSessionToken" TEXT,
21+
"antiCSRFToken" TEXT,
22+
"publicData" TEXT,
23+
"privateData" TEXT,
24+
CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE SET NULL ON UPDATE CASCADE
25+
);
26+
27+
-- CreateTable
28+
CREATE TABLE "Token" (
29+
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
30+
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
31+
"updatedAt" DATETIME NOT NULL,
32+
"hashedToken" TEXT NOT NULL,
33+
"type" TEXT NOT NULL,
34+
"expiresAt" DATETIME NOT NULL,
35+
"sentTo" TEXT NOT NULL,
36+
"userId" INTEGER NOT NULL,
37+
CONSTRAINT "Token_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
38+
);
39+
40+
-- CreateIndex
41+
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
42+
43+
-- CreateIndex
44+
CREATE UNIQUE INDEX "Session_handle_key" ON "Session"("handle");
45+
46+
-- CreateIndex
47+
CREATE UNIQUE INDEX "Token_hashedToken_type_key" ON "Token"("hashedToken", "type");
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Please do not edit this file manually
2+
# It should be added in your version-control system (i.e. Git)
3+
provider = "sqlite"
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
datasource sqlite {
2+
provider = "sqlite"
3+
url = "file:./db.sqlite"
4+
}
5+
6+
generator client {
7+
provider = "prisma-client-js"
8+
}
9+
10+
model User {
11+
id Int @id @default(autoincrement())
12+
createdAt DateTime @default(now())
13+
updatedAt DateTime @updatedAt
14+
name String?
15+
email String @unique
16+
hashedPassword String?
17+
role String @default("user")
18+
19+
sessions Session[]
20+
tokens Token[]
21+
}
22+
23+
model Session {
24+
id Int @id @default(autoincrement())
25+
createdAt DateTime @default(now())
26+
updatedAt DateTime @updatedAt
27+
expiresAt DateTime?
28+
handle String @unique
29+
user User? @relation(fields: [userId], references: [id])
30+
userId Int?
31+
hashedSessionToken String?
32+
antiCSRFToken String?
33+
publicData String?
34+
privateData String?
35+
}
36+
37+
model Token {
38+
id Int @id @default(autoincrement())
39+
createdAt DateTime @default(now())
40+
updatedAt DateTime @updatedAt
41+
hashedToken String
42+
type String
43+
expiresAt DateTime
44+
sentTo String
45+
46+
user User @relation(fields: [userId], references: [id])
47+
userId Int
48+
49+
@@unique([hashedToken, type])
50+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import prisma from "./index"
2+
import {SecurePassword} from "@blitzjs/auth"
3+
4+
const seed = async () => {
5+
const hashedPassword = await SecurePassword.hash("abcd1234")
6+
await prisma.user.create({
7+
data: {
8+
9+
hashedPassword,
10+
role: "user",
11+
},
12+
})
13+
process.exit(0)
14+
}
15+
16+
seed()
17+
18+
export default seed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
/// <reference types="next" />
2+
/// <reference types="next/image-types/global" />
3+
4+
// NOTE: This file should not be edited
5+
// see https://nextjs.org/docs/basic-features/typescript for more information.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
const {withBlitz} = require("@blitzjs/next")
2+
module.exports = withBlitz({})
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
{
2+
"name": "test-full-auth-with-rpc",
3+
"version": "0.0.0",
4+
"private": true,
5+
"prisma": {
6+
"seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} db/seed.ts",
7+
"schema": "db/schema.prisma"
8+
},
9+
"scripts": {
10+
"start:dev": "pnpm run prisma:start && blitz dev",
11+
"test": "vitest run",
12+
"test-watch": "vitest",
13+
"start": "blitz start",
14+
"lint": "next lint",
15+
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf .next",
16+
"prisma:start": "blitz prisma migrate deploy",
17+
"prisma:studio": "prisma studio"
18+
},
19+
"dependencies": {
20+
"@blitzjs/auth": "workspace:2.0.0-beta.19",
21+
"@blitzjs/config": "workspace:2.0.0-beta.19",
22+
"@blitzjs/next": "workspace:2.0.0-beta.19",
23+
"@blitzjs/rpc": "workspace:2.0.0-beta.19",
24+
"@hookform/error-message": "2.0.0",
25+
"@hookform/resolvers": "2.9.10",
26+
"@prisma/client": "4.6.0",
27+
"blitz": "workspace:2.0.0-beta.19",
28+
"delay": "5.0.0",
29+
"next": "12.2.5",
30+
"prisma": "4.6.0",
31+
"react": "18.2.0",
32+
"react-dom": "18.2.0",
33+
"react-hook-form": "7.39.1",
34+
"ts-node": "10.9.1",
35+
"zod": "3.19.1"
36+
},
37+
"devDependencies": {
38+
"@next/bundle-analyzer": "12.0.8",
39+
"@testing-library/jest-dom": "5.16.5",
40+
"@testing-library/react": "13.4.0",
41+
"@testing-library/react-hooks": "8.0.1",
42+
"@types/node": "18.11.9",
43+
"@types/preview-email": "2.0.1",
44+
"@types/react": "18.0.25",
45+
"@typescript-eslint/eslint-plugin": "5.42.1",
46+
"@vitejs/plugin-react": "2.2.0",
47+
"eslint": "8.27.0",
48+
"eslint-config-next": "12.3.1",
49+
"eslint-config-prettier": "8.5.0",
50+
"husky": "8.0.2",
51+
"jsdom": "20.0.3",
52+
"lint-staged": "13.0.3",
53+
"playwright": "1.28.0",
54+
"prettier": "^2.7.1",
55+
"prettier-plugin-prisma": "4.4.0",
56+
"pretty-quick": "3.1.3",
57+
"preview-email": "3.0.7",
58+
"typescript": "^4.8.4",
59+
"vite-tsconfig-paths": "3.6.0",
60+
"vitest": "0.25.3"
61+
}
62+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import {AuthClientPlugin} from "@blitzjs/auth"
2+
import {setupBlitzClient} from "@blitzjs/next"
3+
import {BlitzRpcPlugin} from "@blitzjs/rpc"
4+
import {BlitzCustomPlugin} from "./custom-plugin/plugin"
5+
6+
export const {withBlitz} = setupBlitzClient({
7+
plugins: [
8+
AuthClientPlugin({
9+
cookiePrefix: "web-cookie-prefix",
10+
}),
11+
BlitzRpcPlugin({}),
12+
BlitzCustomPlugin({}),
13+
],
14+
})
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import type {BlitzCliConfig} from "blitz"
2+
import {setupBlitzServer} from "@blitzjs/next"
3+
import {AuthServerPlugin, PrismaStorage} from "@blitzjs/auth"
4+
import db from "../db"
5+
import {simpleRolesIsAuthorized} from "@blitzjs/auth"
6+
import {BlitzLogger} from "blitz"
7+
8+
const {gSSP, gSP, api} = setupBlitzServer({
9+
plugins: [
10+
AuthServerPlugin({
11+
cookiePrefix: "web-cookie-prefix",
12+
storage: PrismaStorage(db),
13+
isAuthorized: simpleRolesIsAuthorized,
14+
}),
15+
],
16+
logger: BlitzLogger({}),
17+
})
18+
19+
export {gSSP, gSP, api}
20+
21+
export const cliConfig: BlitzCliConfig = {
22+
customTemplates: "app/templates",
23+
}

0 commit comments

Comments
 (0)