Skip to content

Commit

Permalink
Decouple Blitz RPC and Blitz Auth (#3943)
Browse files Browse the repository at this point in the history
* 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]>
  • Loading branch information
siddhsuresh and flybayer authored Dec 13, 2022
1 parent a059627 commit 6ece096
Show file tree
Hide file tree
Showing 77 changed files with 2,168 additions and 542 deletions.
8 changes: 8 additions & 0 deletions .changeset/eighty-apes-sleep.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"blitz": minor
"@blitzjs/auth": minor
"@blitzjs/next": minor
"@blitzjs/rpc": minor
---

Decoupled Blitz RPC from Blitz Auth to allow independent use.
30 changes: 3 additions & 27 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@ concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

env:
TURBO_TOKEN: 05de0230f01174d1f8cb4845a01dc6c895ce28f04ebef2318ab11615791b871c35eabbf8
TURBO_TEAM: foo

jobs:
lint:
name: Lint
Expand All @@ -29,11 +25,6 @@ jobs:
- name: Install dependencies
run: pnpm install --frozen-lockfile
- run: pnpm manypkg check
- name: Turborepo local server
uses: felixmosh/turborepo-gh-artifacts@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
server-token: ${{ env.TURBO_TOKEN }}
- name: Build
run: pnpm build
- name: Lint
Expand All @@ -52,11 +43,6 @@ jobs:
with:
node-version: 16
cache: "pnpm"
- name: Turborepo local server
uses: felixmosh/turborepo-gh-artifacts@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
server-token: ${{ env.TURBO_TOKEN }}
- run: pnpm install --frozen-lockfile
- name: Build
run: pnpm build
Expand Down Expand Up @@ -89,12 +75,6 @@ jobs:
node-version: 16
cache: "pnpm"

- name: Turborepo local server
uses: felixmosh/turborepo-gh-artifacts@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
server-token: ${{ env.TURBO_TOKEN }}

- name: Install dependencies
run: pnpm install --frozen-lockfile
shell: bash
Expand Down Expand Up @@ -154,18 +134,14 @@ jobs:
node-version: ${{ matrix.NODE_VERSION }}
cache: "pnpm"

- name: Turborepo local server
uses: felixmosh/turborepo-gh-artifacts@v1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
server-token: ${{ env.TURBO_TOKEN }}

- name: Install dependencies
run: pnpm install --frozen-lockfile
shell: bash

- name: Install playwright
run: npx playwright install --with-deps
run: |
npm i -g playwright
PLAYWRIGHT_BROWSERS_PATH=$HOME/pw-browsers npx playwright install
shell: bash

- name: Build
Expand Down
2 changes: 2 additions & 0 deletions apps/toolkit-app/src/blitz-client.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { AuthClientPlugin } from "@blitzjs/auth"
import { setupBlitzClient } from "@blitzjs/next"
import { BlitzRpcPlugin } from "@blitzjs/rpc"
import { BlitzCustomPlugin } from "./custom-plugin/plugin"

export const { withBlitz } = setupBlitzClient({
plugins: [
AuthClientPlugin({
cookiePrefix: "web-cookie-prefix",
}),
BlitzRpcPlugin({}),
BlitzCustomPlugin({}),
],
})
38 changes: 38 additions & 0 deletions apps/toolkit-app/src/custom-plugin/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { createClientPlugin } from "blitz"

type CustomPluginOptions = {
// ... your options
}

export const BlitzCustomPlugin = createClientPlugin<CustomPluginOptions, {}>(
(options?: CustomPluginOptions) => {
// ... your plugin code
console.log("Custom plugin loaded")
return {
events: {
onSessionCreated: async () => {
// Called when a new session is created - Usually when the user logs in or logs out
console.log("onSessionCreated in custom plugin")
},
onRpcError: async () => {
// Called when an RPC call fails
console.log("onRpcError in custom plugin")
},
},
middleware: {
beforeHttpRequest: (req) => {
//make changes to the request options before RPC call
req.headers = { ...req.headers, ...{ customHeader: "customHeaderValue" } }
return req
},
beforeHttpResponse: (res) => {
//make changes to the response before returning to the caller
return res
},
},
exports: () => ({
// ... your exports
}),
}
}
)
2 changes: 2 additions & 0 deletions integration-tests/auth-with-rpc/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
SESSION_SECRET_KEY=hsdenhJfpLHrGjgdgg3jdF8g2bYD2PaQ
HEADLESS=true
1 change: 1 addition & 0 deletions integration-tests/auth-with-rpc/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require("@blitzjs/next/eslint")
3 changes: 3 additions & 0 deletions integration-tests/auth-with-rpc/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
# Keep environment variables out of version control
*.sqlite
7 changes: 7 additions & 0 deletions integration-tests/auth-with-rpc/db/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import {enhancePrisma} from "blitz"
import {PrismaClient} from "@prisma/client"

const EnhancedPrisma = enhancePrisma(PrismaClient)
export * from "@prisma/client"
const prisma = new EnhancedPrisma()
export default prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
-- CreateTable
CREATE TABLE "User" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
"name" TEXT,
"email" TEXT NOT NULL,
"hashedPassword" TEXT,
"role" TEXT NOT NULL DEFAULT 'user'
);

-- CreateTable
CREATE TABLE "Session" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
"expiresAt" DATETIME,
"handle" TEXT NOT NULL,
"userId" INTEGER,
"hashedSessionToken" TEXT,
"antiCSRFToken" TEXT,
"publicData" TEXT,
"privateData" TEXT,
CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE SET NULL ON UPDATE CASCADE
);

-- CreateTable
CREATE TABLE "Token" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
"hashedToken" TEXT NOT NULL,
"type" TEXT NOT NULL,
"expiresAt" DATETIME NOT NULL,
"sentTo" TEXT NOT NULL,
"userId" INTEGER NOT NULL,
CONSTRAINT "Token_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);

-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");

-- CreateIndex
CREATE UNIQUE INDEX "Session_handle_key" ON "Session"("handle");

-- CreateIndex
CREATE UNIQUE INDEX "Token_hashedToken_type_key" ON "Token"("hashedToken", "type");
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "sqlite"
50 changes: 50 additions & 0 deletions integration-tests/auth-with-rpc/db/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
datasource sqlite {
provider = "sqlite"
url = "file:./db.sqlite"
}

generator client {
provider = "prisma-client-js"
}

model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
name String?
email String @unique
hashedPassword String?
role String @default("user")
sessions Session[]
tokens Token[]
}

model Session {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
expiresAt DateTime?
handle String @unique
user User? @relation(fields: [userId], references: [id])
userId Int?
hashedSessionToken String?
antiCSRFToken String?
publicData String?
privateData String?
}

model Token {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
hashedToken String
type String
expiresAt DateTime
sentTo String
user User @relation(fields: [userId], references: [id])
userId Int
@@unique([hashedToken, type])
}
18 changes: 18 additions & 0 deletions integration-tests/auth-with-rpc/db/seed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import prisma from "./index"
import {SecurePassword} from "@blitzjs/auth"

const seed = async () => {
const hashedPassword = await SecurePassword.hash("abcd1234")
await prisma.user.create({
data: {
email: "[email protected]",
hashedPassword,
role: "user",
},
})
process.exit(0)
}

seed()

export default seed
5 changes: 5 additions & 0 deletions integration-tests/auth-with-rpc/next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
2 changes: 2 additions & 0 deletions integration-tests/auth-with-rpc/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const {withBlitz} = require("@blitzjs/next")
module.exports = withBlitz({})
62 changes: 62 additions & 0 deletions integration-tests/auth-with-rpc/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"name": "test-full-auth-with-rpc",
"version": "0.0.0",
"private": true,
"prisma": {
"seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} db/seed.ts",
"schema": "db/schema.prisma"
},
"scripts": {
"start:dev": "pnpm run prisma:start && blitz dev",
"test": "vitest run",
"test-watch": "vitest",
"start": "blitz start",
"lint": "next lint",
"clean": "rm -rf .turbo && rm -rf node_modules && rm -rf .next",
"prisma:start": "blitz prisma migrate deploy",
"prisma:studio": "prisma studio"
},
"dependencies": {
"@blitzjs/auth": "workspace:2.0.0-beta.19",
"@blitzjs/config": "workspace:2.0.0-beta.19",
"@blitzjs/next": "workspace:2.0.0-beta.19",
"@blitzjs/rpc": "workspace:2.0.0-beta.19",
"@hookform/error-message": "2.0.0",
"@hookform/resolvers": "2.9.10",
"@prisma/client": "4.6.0",
"blitz": "workspace:2.0.0-beta.19",
"delay": "5.0.0",
"next": "12.2.5",
"prisma": "4.6.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-hook-form": "7.39.1",
"ts-node": "10.9.1",
"zod": "3.19.1"
},
"devDependencies": {
"@next/bundle-analyzer": "12.0.8",
"@testing-library/jest-dom": "5.16.5",
"@testing-library/react": "13.4.0",
"@testing-library/react-hooks": "8.0.1",
"@types/node": "18.11.9",
"@types/preview-email": "2.0.1",
"@types/react": "18.0.25",
"@typescript-eslint/eslint-plugin": "5.42.1",
"@vitejs/plugin-react": "2.2.0",
"eslint": "8.27.0",
"eslint-config-next": "12.3.1",
"eslint-config-prettier": "8.5.0",
"husky": "8.0.2",
"jsdom": "20.0.3",
"lint-staged": "13.0.3",
"playwright": "1.28.0",
"prettier": "^2.7.1",
"prettier-plugin-prisma": "4.4.0",
"pretty-quick": "3.1.3",
"preview-email": "3.0.7",
"typescript": "^4.8.4",
"vite-tsconfig-paths": "3.6.0",
"vitest": "0.25.3"
}
}
14 changes: 14 additions & 0 deletions integration-tests/auth-with-rpc/src/blitz-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import {AuthClientPlugin} from "@blitzjs/auth"
import {setupBlitzClient} from "@blitzjs/next"
import {BlitzRpcPlugin} from "@blitzjs/rpc"
import {BlitzCustomPlugin} from "./custom-plugin/plugin"

export const {withBlitz} = setupBlitzClient({
plugins: [
AuthClientPlugin({
cookiePrefix: "web-cookie-prefix",
}),
BlitzRpcPlugin({}),
BlitzCustomPlugin({}),
],
})
23 changes: 23 additions & 0 deletions integration-tests/auth-with-rpc/src/blitz-server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type {BlitzCliConfig} from "blitz"
import {setupBlitzServer} from "@blitzjs/next"
import {AuthServerPlugin, PrismaStorage} from "@blitzjs/auth"
import db from "../db"
import {simpleRolesIsAuthorized} from "@blitzjs/auth"
import {BlitzLogger} from "blitz"

const {gSSP, gSP, api} = setupBlitzServer({
plugins: [
AuthServerPlugin({
cookiePrefix: "web-cookie-prefix",
storage: PrismaStorage(db),
isAuthorized: simpleRolesIsAuthorized,
}),
],
logger: BlitzLogger({}),
})

export {gSSP, gSP, api}

export const cliConfig: BlitzCliConfig = {
customTemplates: "app/templates",
}
Loading

0 comments on commit 6ece096

Please sign in to comment.