Skip to content
This repository was archived by the owner on Sep 15, 2023. It is now read-only.

Commit 7722a29

Browse files
committed
WIP refactor
1 parent 7d758c2 commit 7722a29

File tree

23 files changed

+2071
-132
lines changed

23 files changed

+2071
-132
lines changed

.vscode/launch.json

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,27 @@
11
{
22
"configurations": [
33
{
4-
"name": "Debug Example",
4+
"name": "Debug CLI Requests Example",
5+
"type": "node",
6+
"request": "launch",
7+
"cwd": "${workspaceRoot}/examples/cli-requests",
8+
"args": [
9+
"src/index.ts"
10+
],
11+
"runtimeArgs": [
12+
"--nolazy",
13+
"-r",
14+
"ts-node/register"
15+
],
16+
"env": {
17+
"TS_NODE_PROJECT": "${workspaceRoot}/examples/cli-requests/tsconfig.json"
18+
},
19+
"sourceMaps": true,
20+
"internalConsoleOptions": "openOnSessionStart",
21+
"preLaunchTask": "tsc: build - examples/cli-requests/tsconfig.json"
22+
},
23+
{
24+
"name": "Debug Redirect Flow Example",
525
"type": "node",
626
"request": "launch",
727
"cwd": "${workspaceRoot}/examples/redirect-flow",

.vscode/tasks.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,16 @@
1111
"label": "tsc: build - examples/redirect-flow/tsconfig.json",
1212
"dependsOn":[ "tsc: build - tsconfig.json" ]
1313
},
14+
{
15+
"type": "typescript",
16+
"tsconfig": "examples/cli-requests/tsconfig.json",
17+
"problemMatcher": [
18+
"$tsc"
19+
],
20+
"group": "build",
21+
"label": "tsc: build - examples/cli-requests/tsconfig.json",
22+
"dependsOn":[ "tsc: build - tsconfig.json" ],
23+
},
1424
{
1525
"type": "typescript",
1626
"tsconfig": "tsconfig.json",

examples/cli-requests/.env.example

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
PATREON_CLIENT_ID=
2+
PATREON_CLIENT_SECRET=
3+
PATREON_CAMPAIGN_ID=

examples/cli-requests/README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# CLI Requests Example
2+
3+
## Environment Setup
4+
5+
1. Fill out `.env.example` with your client id and client secret.
6+
2. Rename to `.env`.
7+
3. Because this is an example we don't need to worry about the Refresh Token
8+
but if your token is expired, make sure you refresh it from the Client's page
9+
before you start the example.

examples/cli-requests/src/index.ts

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import * as DotEnv from 'dotenv';
2+
import * as OAuth from 'simple-oauth2';
3+
// import * as Patreon from "../../../dist/patreon";
4+
// import * as QueryString from 'querystring';
5+
// import { Member } from '../../../dist/data';
6+
7+
DotEnv.config({ path: "./.env" });
8+
9+
const credentials: OAuth.ModuleOptions = {
10+
client:
11+
{
12+
id: process.env.PATREON_CLIENT_ID as string,
13+
secret: process.env.PATREON_CLIENT_SECRET as string
14+
},
15+
auth:
16+
{
17+
tokenHost: "https://www.patreon.com",
18+
tokenPath: "/api/oauth2/token",
19+
authorizePath: "/oauth2/authorize"
20+
}
21+
};
22+
23+
24+
async function run()
25+
{
26+
const EXPIRATION_WINDOW_IN_SECONDS = 300;
27+
28+
29+
if (accessToken.expired(EXPIRATION_WINDOW_IN_SECONDS))
30+
{
31+
const refreshParams =
32+
{
33+
scope: accessToken.token.scope,
34+
};
35+
try
36+
{
37+
accessToken = await accessToken.refresh(refreshParams);
38+
var accessTokenRefreshed = JSON.stringify(accessToken.token);
39+
console.log("refreshed: " + accessTokenRefreshed);
40+
}
41+
catch (error)
42+
{
43+
console.log('Error refreshing access token: ', error.message);
44+
}
45+
}
46+
47+
console.log(accessTokenJSONString);
48+
}
49+
50+
// Create the AuthorizatoinCode client.
51+
const client: OAuth.AuthorizationCode = new OAuth.AuthorizationCode(credentials);
52+
53+
// Restore a token with that grant type.
54+
const accessTokenJSONString = ``;
55+
let accessToken: OAuth.AccessToken = client.createToken(JSON.parse(accessTokenJSONString));
56+
57+
58+
run();
59+
60+
//
61+
// const client: OAuth.ClientCredentials = new OAuth.ClientCredentials(credentials);
62+
// const token: OAuth.Token =
63+
// {
64+
// // invalid // access_token: process.env.PATREON_CAMPAIGN_ACCESS_TOKEN,
65+
// };
66+
// const accessToken: OAuth.AccessToken = client.createToken(token)
67+
68+
// const MemberQueryObject: Patreon.Schemas.MemberSchema = new Patreon.Schemas.MemberSchema(Patreon.Schemas.complete_member_schema);
69+
70+
// const endpointQuery: QueryString.ParsedUrlQueryInput = Patreon.Endpoints.BuildEndpointQuery(MemberQueryObject);
71+
// console.log(endpointQuery);
72+
73+
// const query: string = Patreon.Endpoints.BuildComplexEndpoint(
74+
// Patreon.Endpoints.ComplexEndpoints.CampaignMembersById,
75+
// process.env.PATREON_CAMPAIGN_ID as string,
76+
// endpointQuery);
77+
78+
// Patreon.PatreonRequest(accessToken, query)
79+
// .then((result: string) =>
80+
// {
81+
// let base: Patreon.Data.Root = new Patreon.Data.Root(JSON.parse(result));
82+
// console.log(base);
83+
84+
// for (const item of base.data)
85+
// {
86+
// const member: Patreon.Data.Member = item as Member;
87+
// console.log(member.attributes.full_name);
88+
// }
89+
// });
90+
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
{
2+
"compilerOptions": {
3+
"target": "es2017",
4+
"module": "CommonJS",
5+
"lib": [
6+
"es2017"
7+
],
8+
"types": [
9+
"node"
10+
],
11+
"declaration": true,
12+
"declarationMap": true,
13+
"sourceMap": true,
14+
"outDir": "./dist",
15+
"rootDirs": [
16+
"./src",
17+
],
18+
"strict": true,
19+
"noImplicitAny": true,
20+
"strictNullChecks": true,
21+
"strictFunctionTypes": true,
22+
"strictBindCallApply": true,
23+
"strictPropertyInitialization": true,
24+
"noImplicitThis": true,
25+
"alwaysStrict": true,
26+
"noUnusedLocals": true,
27+
"noUnusedParameters": true,
28+
"noImplicitReturns": true,
29+
"noFallthroughCasesInSwitch": false,
30+
"esModuleInterop": true,
31+
"moduleResolution": "node",
32+
"experimentalDecorators": true,
33+
"emitDecoratorMetadata": true,
34+
"skipLibCheck": true,
35+
"forceConsistentCasingInFileNames": true
36+
}
37+
}

examples/redirect-flow/src/index.ts

Lines changed: 25 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,11 @@ import
1111

1212
import { AddressInfo } from 'net';
1313

14-
import
15-
{
16-
AccessToken,
17-
AuthorizationTokenConfig,
18-
create,
19-
ModuleOptions,
20-
OAuthClient,
21-
Token
22-
} from 'simple-oauth2';
14+
import * as OAuth from 'simple-oauth2';
2315

2416
import { format as formatUrl } from 'url';
2517

26-
import { PatreonRequest, Endpoints, Schemas } from "../../../dist/patreon";
18+
import { PatreonRequest, Endpoints, Schemas, Types, Data } from "../../../dist/patreon";
2719
import { ParsedUrlQueryInput } from 'querystring';
2820

2921
dotenv.config({ path: "./.env" });
@@ -32,18 +24,20 @@ const PATREON_HOST: string = "https://www.patreon.com";
3224
const PATREON_TOKEN_PATH: string = "/api/oauth2/token";
3325
const PATREON_AUTHORIZE_PATH: string = "/oauth2/authorize";
3426

27+
const PORT: number = 8085;
28+
3529
const authorizeRedirectUri: string = formatUrl({
3630
protocol: "http",
37-
host: "localhost:8081",
31+
host: `localhost:${PORT}`,
3832
pathname: "/oauth/redirect",
3933
});
4034

4135
const stateCheck: string = "chill";
4236
const scopes: string = "identity campaigns identity.memberships campaigns.members";
4337

44-
let accessTokenStore: AccessToken;
38+
let accessTokenStore: Types.PatreonToken;
4539

46-
const credentials: ModuleOptions = {
40+
const credentials: OAuth.ModuleOptions = {
4741
client:
4842
{
4943
id: process.env.PATREON_CLIENT_ID as string,
@@ -58,19 +52,21 @@ const credentials: ModuleOptions = {
5852
};
5953

6054
// Build the OAuth2 client.
61-
const client: OAuthClient<"patreon"> = create(credentials);
55+
const client: OAuth.AuthorizationCode<"patreon"> = new OAuth.AuthorizationCode(credentials);
6256

6357
export async function ShowPatronInformation(_req: Request, res: Response): Promise<void>
6458
{
6559
if (accessTokenStore)
6660
{
67-
const UserQueryObject: Schemas.User = new Schemas.User(
61+
var schemaObject =
62+
{
63+
attributes:
6864
{
69-
attributes:
70-
{
71-
about: Schemas.user_constants.attributes?.about,
72-
},
73-
});
65+
about: Schemas.user_constants.attributes?.about,
66+
}
67+
};
68+
69+
const UserQueryObject: Schemas.User = new Schemas.User(schemaObject);
7470

7571
const endpointQuery: ParsedUrlQueryInput = Endpoints.BuildEndpointQuery(UserQueryObject);
7672

@@ -79,7 +75,8 @@ export async function ShowPatronInformation(_req: Request, res: Response): Promi
7975
endpointQuery);
8076

8177
const result: string = await PatreonRequest(accessTokenStore, query);
82-
const obj: any = JSON.parse(result);
78+
79+
var userObject: Data.User = new Data.User(JSON.parse(result));
8380
res.send(`
8481
<html>
8582
<head>
@@ -88,10 +85,10 @@ export async function ShowPatronInformation(_req: Request, res: Response): Promi
8885
</style>
8986
</head>
9087
<body>
91-
<pre>${ JSON.stringify(obj, null, ' ')}</pre>
88+
<pre>${JSON.stringify(userObject, null, ' ')}</pre>
9289
</body>
9390
</html>`);
94-
console.log(JSON.stringify(obj, null, ' '));
91+
console.log(JSON.stringify(userObject, null, ' '));
9592
}
9693
else
9794
{
@@ -103,7 +100,7 @@ export async function ShowPatronInformation(_req: Request, res: Response): Promi
103100
export function PatreonAuthorizeMiddleware(_req: Request, res: Response): void
104101
{
105102
// Build AuthorizationUrl
106-
const authorizationUri: string = client.authorizationCode.authorizeURL(
103+
const authorizationUri: string = client.authorizeURL(
107104
{
108105
redirect_uri: authorizeRedirectUri,
109106
scope: scopes,
@@ -117,7 +114,7 @@ export function PatreonAuthorizeMiddleware(_req: Request, res: Response): void
117114
// Patreon Redirect Flow Entrypoint
118115
export async function PatreonRedirectMiddleware(req: Request, res: Response, next: NextFunction): Promise<void>
119116
{
120-
let tokenConfig: AuthorizationTokenConfig;
117+
let tokenConfig: OAuth.AuthorizationTokenConfig;
121118
let stateVar: string;
122119
{
123120
const
@@ -143,8 +140,9 @@ export async function PatreonRedirectMiddleware(req: Request, res: Response, nex
143140
// Save the access token
144141
try
145142
{
146-
const result: Token = await client.authorizationCode.getToken(tokenConfig);
147-
accessTokenStore = client.accessToken.create(result);
143+
const result: OAuth.Token = await client.getToken(tokenConfig);
144+
accessTokenStore = Types.CreatePatreonTokenFromOAuthToken(client.createToken(result));
145+
148146
console.log(accessTokenStore);
149147
res.redirect("/");
150148
}
@@ -156,7 +154,6 @@ export async function PatreonRedirectMiddleware(req: Request, res: Response, nex
156154
}
157155
}
158156

159-
const PORT: number = 8081;
160157
const app: express.Express = express();
161158
const server = app.listen(PORT, () =>
162159
{

0 commit comments

Comments
 (0)