-
Notifications
You must be signed in to change notification settings - Fork 0
/
oauth2-callback_pkce_plain.ts
76 lines (64 loc) · 1.83 KB
/
oauth2-callback_pkce_plain.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
// Copyright 2021 Twitter, Inc.
// SPDX-License-Identifier: Apache-2.0
import { config } from "std/dotenv/mod.ts";
import { cleanEnv, str } from "envalid";
import { Application, Router } from "oak";
import { auth, Client } from "../src/mod.ts";
await config({ export: true });
const env = cleanEnv(Deno.env.toObject(), {
CLIENT_ID: str(),
CLIENT_SECRET: str(),
});
const app = new Application();
const router = new Router();
const authClient = new auth.OAuth2User({
client_id: env.CLIENT_ID,
client_secret: env.CLIENT_SECRET,
callback: "http://127.0.0.1:3000/callback",
scopes: ["tweet.read", "users.read", "offline.access"],
});
const client = new Client(authClient);
const STATE = "my-state";
router.get("/callback", async (ctx) => {
try {
const { code, state } = Object.fromEntries(
ctx.request.url.searchParams.entries(),
);
if (state !== STATE) {
ctx.response.status = 500;
ctx.response.body = "State isn't matching";
return;
}
await authClient.requestAccessToken(code);
ctx.response.redirect("/tweets");
} catch (error) {
console.log(error);
}
});
router.get("/login", async (ctx) => {
const authUrl = await authClient.generateAuthURL({
state: STATE,
code_challenge_method: "plain",
code_challenge: "test",
});
ctx.response.redirect(authUrl);
});
router.get("/tweets", async (ctx) => {
try {
const tweets = await client.tweets.findTweetById("20");
ctx.response.body = tweets;
} catch (error) {
console.log("tweets error", error);
}
});
router.get("/revoke", async (ctx) => {
try {
const response = await authClient.revokeAccessToken();
ctx.response.body = response;
} catch (error) {
console.log(error);
}
});
app.use(router.routes());
console.log(`Go here to login: http://127.0.0.1:3000/login`);
await app.listen({ port: 3000 });