-
Notifications
You must be signed in to change notification settings - Fork 70
/
auth.ts
226 lines (186 loc) · 5.82 KB
/
auth.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import type { GetSession, RequestHandler } from "@sveltejs/kit";
import type { EndpointOutput } from "@sveltejs/kit/types/endpoint";
import { RequestEvent } from "@sveltejs/kit/types/hooks";
import cookie from "cookie";
import * as jsonwebtoken from "jsonwebtoken";
import type { JWT, Session } from "./interfaces";
import { join } from "./path";
import type { Provider } from "./providers";
interface AuthConfig {
providers: Provider[];
callbacks?: AuthCallbacks;
jwtSecret?: string;
jwtExpiresIn?: string | number;
host?: string;
protocol?: string;
basePath?: string;
}
interface AuthCallbacks {
signIn?: () => boolean | Promise<boolean>;
jwt?: (token: JWT, profile?: any) => JWT | Promise<JWT>;
session?: (token: JWT, session: Session) => Session | Promise<Session>;
redirect?: (url: string) => string | Promise<string>;
}
export class Auth {
constructor(private readonly config?: AuthConfig) {}
get basePath() {
return this.config?.basePath ?? "/api/auth";
}
getJwtSecret() {
if (this.config?.jwtSecret) {
return this.config?.jwtSecret;
}
if (this.config?.providers?.length) {
const provs = this.config?.providers?.map((provider) => provider.id).join("+");
return Buffer.from(provs).toString("base64");
}
return "svelte_auth_secret";
}
async getToken(headers: any) {
if (!headers.get("cookie")) {
return null;
}
const cookies = cookie.parse(headers.get("cookie"));
if (!cookies.svelteauthjwt) {
return null;
}
let token: JWT;
try {
token = (jsonwebtoken.verify(cookies.svelteauthjwt, this.getJwtSecret()) || {}) as JWT;
} catch {
return null;
}
if (this.config?.callbacks?.jwt) {
token = await this.config.callbacks.jwt(token);
}
return token;
}
getBaseUrl(host?: string) {
const protocol = this.config?.protocol ?? "https";
host = this.config?.host ?? host;
return `${protocol}://${host}`;
}
getPath(path: string) {
const pathname = join([this.basePath, path]);
return pathname;
}
getUrl(path: string, host?: string) {
const pathname = this.getPath(path);
return new URL(pathname, this.getBaseUrl(host)).href;
}
setToken(headers: any, newToken: JWT | any) {
const originalToken = this.getToken(headers);
return {
...(originalToken ?? {}),
...newToken,
};
}
signToken(token: JWT) {
const opts = !token.exp
? {
expiresIn: this.config?.jwtExpiresIn ?? "30d",
}
: {};
const jwt = jsonwebtoken.sign(token, this.getJwtSecret(), opts);
return jwt;
}
async getRedirectUrl(host: string, redirectUrl?: string) {
let redirect = redirectUrl || this.getBaseUrl(host);
if (this.config?.callbacks?.redirect) {
redirect = await this.config.callbacks.redirect(redirect);
}
return redirect;
}
async handleProviderCallback(event: RequestEvent, provider: Provider): Promise<EndpointOutput> {
const { headers } = event.request;
const { url } = event;
const [profile, redirectUrl] = await provider.callback(event, this);
let token = (await this.getToken(headers)) ?? { user: {} };
if (this.config?.callbacks?.jwt) {
token = await this.config.callbacks.jwt(token, profile);
} else {
token = this.setToken(headers, { user: profile });
}
const jwt = this.signToken(token);
const redirect = await this.getRedirectUrl(url.host, redirectUrl ?? undefined);
return {
status: 302,
headers: {
"set-cookie": `svelteauthjwt=${jwt}; Path=/; HttpOnly`,
Location: redirect,
},
};
}
async handleEndpoint(event: RequestEvent): Promise<EndpointOutput> {
const { headers, method } = event.request;
const { url } = event;
if (url.pathname === this.getPath("signout")) {
const token = this.setToken(event.request.headers, {});
const jwt = this.signToken(token);
if (method === "POST") {
return {
headers: {
"set-cookie": `svelteauthjwt=${jwt}; Path=/; HttpOnly`,
},
body: {
signout: true,
},
};
}
const redirect = await this.getRedirectUrl(url.host);
return {
status: 302,
headers: {
"set-cookie": `svelteauthjwt=${jwt}; Path=/; HttpOnly`,
Location: redirect,
},
};
}
const regex = new RegExp(join([this.basePath, `(?<method>signin|callback)/(?<provider>\\w+)`]));
const match = url.pathname.match(regex);
if (match && match.groups) {
const provider = this.config?.providers?.find(
(provider) => provider.id === match.groups!.provider,
);
if (provider) {
if (match.groups.method === "signin") {
return await provider.signin(event, this);
} else {
return await this.handleProviderCallback(event, provider);
}
}
}
return {
status: 404,
body: "Not found.",
};
}
GET: RequestHandler = async (event: RequestEvent): Promise<any> => {
const { url } = event;
if (url.pathname === this.getPath("csrf")) {
return { body: "1234" }; // TODO: Generate real token
} else if (url.pathname === this.getPath("session")) {
const session = await this.getSession(event);
return {
body: {
session,
},
};
}
return await this.handleEndpoint(event);
};
POST: RequestHandler = async (event: RequestEvent) => {
return await this.handleEndpoint(event);
};
getSession: GetSession = async (event: RequestEvent) => {
const { request } = event;
const token = await this.getToken(request.headers);
if (token) {
if (this.config?.callbacks?.session) {
return await this.config.callbacks.session(token, { user: token.user });
}
return { user: token.user };
}
return {};
};
}