Skip to content

Commit

Permalink
✨ Upgrade to SvelteKit 1.0.0-next.211 and related fixes (#58)
Browse files Browse the repository at this point in the history
* ✨ Upgrade to SvelteKit 1.0.0-next.211 and related fixes

* 🚨 Fix some lint / formatter errors, ESLint plugin Svelte3 still not working

Co-authored-by: RaviAnand Mohabir <moravrav@gmail.com>
  • Loading branch information
lulzneko and Dan6erbond authored Jan 12, 2022
1 parent 7c3d02e commit 9a5dbe2
Show file tree
Hide file tree
Showing 11 changed files with 246 additions and 126 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ SvelteKitAuth also comes with first-class support for Typescript out of the box,

SvelteKitAuth is very easy to setup! All you need to do is instantiate the `SvelteKitAuth` class, and configure it with some default providers, as well as a JWT secret key used to verify the cookies:

_**Warning**: env variables prefixed with `VITE_` can be exposed and leaked into client-side bundles if they are referenced in any client-side code. Make sure this is not the case, or consider using an alternative method such as loading them via dotenv directly instead._
_**Warning**: env variables prefixed with `VITE_` can be exposed and leaked into client-side bundles if they are referenced in any client-side code. Make sure this is not the case, or consider using an alternative method such as loading them via dotenv directly instead.\_

```ts
export const appAuth = new SvelteKitAuth({
Expand Down
2 changes: 1 addition & 1 deletion app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"dev": "svelte-kit dev",
"build": "svelte-kit build",
"preview": "svelte-kit preview",
"lint": "prettier --check --plugin-search-dir=. . && eslint --ignore-path .gitignore .",
"lint": "prettier --check --plugin-search-dir=. . && eslint --ignore-path .gitignore --config .eslintrc.cjs .",
"format": "prettier --write --plugin-search-dir=. ."
},
"devDependencies": {
Expand Down
6 changes: 0 additions & 6 deletions app/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3441,12 +3441,6 @@ simple-swizzle@^0.2.2:
cookie "^0.4.1"
jsonwebtoken "^8.5.1"

"sk-auth@file:../":
version "0.3.7"
dependencies:
cookie "^0.4.1"
jsonwebtoken "^8.5.1"

slash@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634"
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
},
"devDependencies": {
"@rollup/plugin-typescript": "^8.2.1",
"@sveltejs/kit": "^1.0.0-next.107",
"@sveltejs/kit": "^1.0.0-next.211",
"@types/jsonwebtoken": "^8.5.1",
"@typescript-eslint/eslint-plugin": "^4.23.0",
"@typescript-eslint/parser": "^4.23.0",
Expand Down
27 changes: 14 additions & 13 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { GetSession, RequestHandler } from "@sveltejs/kit";
import type { EndpointOutput, ServerRequest } from "@sveltejs/kit/types/endpoint";
import type { Headers } from "@sveltejs/kit/types/helper";
import type { EndpointOutput } from "@sveltejs/kit/types/endpoint";
import { RequestHeaders } from "@sveltejs/kit/types/helper";
import { ServerRequest } from "@sveltejs/kit/types/hooks";
import cookie from "cookie";
import * as jsonwebtoken from "jsonwebtoken";
import type { JWT, Session } from "./interfaces";
Expand Down Expand Up @@ -43,7 +44,7 @@ export class Auth {
return "svelte_auth_secret";
}

async getToken(headers: Headers) {
async getToken(headers: RequestHeaders) {
if (!headers.cookie) {
return null;
}
Expand Down Expand Up @@ -82,7 +83,7 @@ export class Auth {
return new URL(pathname, this.getBaseUrl(host)).href;
}

setToken(headers: Headers, newToken: JWT | any) {
setToken(headers: RequestHeaders, newToken: JWT | any) {
const originalToken = this.getToken(headers);

return {
Expand Down Expand Up @@ -113,7 +114,7 @@ export class Auth {
request: ServerRequest,
provider: Provider,
): Promise<EndpointOutput> {
const { headers, host } = request;
const { headers, url } = request;
const [profile, redirectUrl] = await provider.callback(request, this);

let token = (await this.getToken(headers)) ?? { user: {} };
Expand All @@ -124,7 +125,7 @@ export class Auth {
}

const jwt = this.signToken(token);
const redirect = await this.getRedirectUrl(host, redirectUrl ?? undefined);
const redirect = await this.getRedirectUrl(url.host, redirectUrl ?? undefined);

return {
status: 302,
Expand All @@ -136,9 +137,9 @@ export class Auth {
}

async handleEndpoint(request: ServerRequest): Promise<EndpointOutput> {
const { path, headers, method, host } = request;
const { headers, method, url } = request;

if (path === this.getPath("signout")) {
if (url.pathname === this.getPath("signout")) {
const token = this.setToken(headers, {});
const jwt = this.signToken(token);

Expand All @@ -153,7 +154,7 @@ export class Auth {
};
}

const redirect = await this.getRedirectUrl(host);
const redirect = await this.getRedirectUrl(url.host);

return {
status: 302,
Expand All @@ -165,7 +166,7 @@ export class Auth {
}

const regex = new RegExp(join([this.basePath, `(?<method>signin|callback)/(?<provider>\\w+)`]));
const match = path.match(regex);
const match = url.pathname.match(regex);

if (match && match.groups) {
const provider = this.config?.providers?.find(
Expand All @@ -187,11 +188,11 @@ export class Auth {
}

get: RequestHandler = async (request) => {
const { path } = request;
const { url } = request;

if (path === this.getPath("csrf")) {
if (url.pathname === this.getPath("csrf")) {
return { body: "1234" }; // TODO: Generate real token
} else if (path === this.getPath("session")) {
} else if (url.pathname === this.getPath("session")) {
const session = await this.getSession(request);
return {
body: {
Expand Down
6 changes: 3 additions & 3 deletions src/client/signIn.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* import { goto } from "@sveltejs/kit/assets/runtime/app/navigation";
import { page } from "@sveltejs/kit/assets/runtime/app/stores"; */
import type { Page } from "@sveltejs/kit";
import type { LoadInput } from "@sveltejs/kit";

interface SignInConfig {
redirectUrl?: string;
Expand All @@ -23,10 +23,10 @@ export async function signIn(provider: string, data?: any, config?: SignInConfig
if (config?.redirectUrl) {
redirectUrl = config.redirectUrl;
} else {
let $val: Page | undefined;
let $val: LoadInput | undefined;
/* page.subscribe(($) => ($val = $))(); */
if ($val) {
redirectUrl = `${$val.host}${$val.path}?${$val.query}`;
redirectUrl = `${$val.url.host}${$val.url.pathname}?${$val.url.searchParams}`;
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/providers/base.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { EndpointOutput } from "@sveltejs/kit";
import type { ServerRequest } from "@sveltejs/kit/types/endpoint";
import { ServerRequest } from "@sveltejs/kit/types/hooks";
import type { Auth } from "../auth";
import type { CallbackResult } from "../types";

Expand Down
25 changes: 14 additions & 11 deletions src/providers/oauth2.base.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { EndpointOutput, ServerRequest } from "@sveltejs/kit/types/endpoint";
import type { EndpointOutput } from "@sveltejs/kit/types/endpoint";
import { ServerRequest } from "@sveltejs/kit/types/hooks";
import type { Auth } from "../auth";
import type { CallbackResult } from "../types";
import { Provider, ProviderConfig } from "./base";
Expand Down Expand Up @@ -33,24 +34,26 @@ export abstract class OAuth2BaseProvider<
abstract getUserProfile(tokens: any): ProfileType | Promise<ProfileType>;

async signin(request: ServerRequest, auth: Auth): Promise<EndpointOutput> {
const { method, host, query } = request;
const state = [`redirect=${query.get("redirect") ?? this.getUri(auth, "/", host)}`].join(",");
const { method, url } = request;
const state = [
`redirect=${url.searchParams.get("redirect") ?? this.getUri(auth, "/", url.host)}`,
].join(",");
const base64State = Buffer.from(state).toString("base64");
const nonce = Math.round(Math.random() * 1000).toString(); // TODO: Generate random based on user values
const url = await this.getAuthorizationUrl(request, auth, base64State, nonce);
const authUrl = await this.getAuthorizationUrl(request, auth, base64State, nonce);

if (method === "POST") {
return {
body: {
redirect: url,
redirect: authUrl,
},
};
}

return {
status: 302,
headers: {
Location: url,
Location: authUrl,
},
};
}
Expand All @@ -65,17 +68,17 @@ export abstract class OAuth2BaseProvider<
}
}

async callback({ query, host }: ServerRequest, auth: Auth): Promise<CallbackResult> {
const code = query.get("code");
const redirect = this.getStateValue(query, "redirect");
async callback({ url }: ServerRequest, auth: Auth): Promise<CallbackResult> {
const code = url.searchParams.get("code");
const redirect = this.getStateValue(url.searchParams, "redirect");

const tokens = await this.getTokens(code!, this.getCallbackUri(auth, host));
const tokens = await this.getTokens(code!, this.getCallbackUri(auth, url.host));
let user = await this.getUserProfile(tokens);

if (this.config.profile) {
user = await this.config.profile(user, tokens);
}

return [user, redirect ?? this.getUri(auth, "/", host)];
return [user, redirect ?? this.getUri(auth, "/", url.host)];
}
}
10 changes: 5 additions & 5 deletions src/providers/oauth2.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ServerRequest } from "@sveltejs/kit/types/endpoint";
import { ServerRequest } from "@sveltejs/kit/types/hooks";
import type { Auth } from "../auth";
import { ucFirst } from "../helpers";
import { OAuth2BaseProvider, OAuth2BaseProviderConfig, OAuth2Tokens } from "./oauth2.base";
Expand Down Expand Up @@ -37,19 +37,19 @@ export class OAuth2Provider<
});
}

getAuthorizationUrl({ host }: ServerRequest, auth: Auth, state: string, nonce: string) {
getAuthorizationUrl({ url }: ServerRequest, auth: Auth, state: string, nonce: string) {
const data = {
state,
nonce,
response_type: this.config.responseType,
client_id: this.config.clientId,
scope: Array.isArray(this.config.scope) ? this.config.scope.join(" ") : this.config.scope!,
redirect_uri: this.getCallbackUri(auth, host),
redirect_uri: this.getCallbackUri(auth, url.host),
...(this.config.authorizationParams ?? {}),
};

const url = `${this.config.authorizationUrl}?${new URLSearchParams(data)}`;
return url;
const authUrl = `${this.config.authorizationUrl}?${new URLSearchParams(data)}`;
return authUrl;
}

async getTokens(code: string, redirectUri: string): Promise<TokensType> {
Expand Down
20 changes: 10 additions & 10 deletions src/providers/twitter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ServerRequest } from "@sveltejs/kit/types/endpoint";
import { ServerRequest } from "@sveltejs/kit/types/hooks";
import type { Auth } from "../auth";
import type { CallbackResult } from "../types";
import { OAuth2BaseProvider, OAuth2BaseProviderConfig } from "./oauth2.base";
Expand Down Expand Up @@ -38,17 +38,17 @@ export class TwitterAuthProvider extends OAuth2BaseProvider<any, any, TwitterAut
};
}

async getAuthorizationUrl({ host }: ServerRequest, auth: Auth, state: string, nonce: string) {
async getAuthorizationUrl({ url }: ServerRequest, auth: Auth, state: string, nonce: string) {
const endpoint = "https://api.twitter.com/oauth/authorize";

const { oauthToken } = await this.getRequestToken(auth, host);
const { oauthToken } = await this.getRequestToken(auth, url.host);

const data = {
oauth_token: oauthToken,
};

const url = `${endpoint}?${new URLSearchParams(data)}`;
return url;
const authUrl = `${endpoint}?${new URLSearchParams(data)}`;
return authUrl;
}

async getTokens(oauthToken: string, oauthVerifier: string) {
Expand All @@ -71,10 +71,10 @@ export class TwitterAuthProvider extends OAuth2BaseProvider<any, any, TwitterAut
return await res.json();
}

async callback({ query, host }: ServerRequest, auth: Auth): Promise<CallbackResult> {
const oauthToken = query.get("oauth_token");
const oauthVerifier = query.get("oauth_verifier");
const redirect = this.getStateValue(query, "redirect");
async callback({ url }: ServerRequest, auth: Auth): Promise<CallbackResult> {
const oauthToken = url.searchParams.get("oauth_token");
const oauthVerifier = url.searchParams.get("oauth_verifier");
const redirect = this.getStateValue(url.searchParams, "redirect");

const tokens = await this.getTokens(oauthToken!, oauthVerifier!);
let user = await this.getUserProfile(tokens);
Expand All @@ -83,6 +83,6 @@ export class TwitterAuthProvider extends OAuth2BaseProvider<any, any, TwitterAut
user = await this.config.profile(user, tokens);
}

return [user, redirect ?? this.getUri(auth, "/", host)];
return [user, redirect ?? this.getUri(auth, "/", url.host)];
}
}
Loading

0 comments on commit 9a5dbe2

Please sign in to comment.