-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathoauth2-callback.ts
60 lines (47 loc) · 1.4 KB
/
oauth2-callback.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
// Copyright 2021 Twitter, Inc.
// SPDX-License-Identifier: Apache-2.0
import { Client, auth } from "twitter-api-sdk";
import express from "express";
import dotenv from "dotenv";
dotenv.config();
const app = express();
const authClient = new auth.OAuth2User({
client_id: process.env.CLIENT_ID as string,
client_secret: process.env.CLIENT_SECRET as string,
callback: "http://127.0.0.1:3000/callback",
scopes: ["tweet.read", "users.read"],
});
const client = new Client(authClient);
const STATE = "my-state";
app.get("/callback", async function (req, res) {
try {
const { code, state } = req.query;
if (state !== STATE) return res.status(500).send("State isn't matching");
await authClient.requestAccessToken(code as string);
res.redirect("/tweets");
} catch (error) {
console.log(error);
}
});
app.get("/login", async function (req, res) {
const authUrl = authClient.generateAuthURL({
state: STATE,
code_challenge_method: "s256",
});
res.redirect(authUrl);
});
app.get("/tweets", async function (req, res) {
const tweets = await client.tweets.findTweetById("20");
res.send(tweets.data);
});
app.get("/revoke", async function (req, res) {
try {
const response = await authClient.revokeAccessToken();
res.send(response);
} catch (error) {
console.log(error);
}
});
app.listen(3000, () => {
console.log(`Go here to login: http://127.0.0.1:3000/login`);
});