Skip to content

Commit

Permalink
refactor(#25): supported platforms with public APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
sametcodes committed Mar 7, 2023
1 parent b092d7f commit 6596555
Show file tree
Hide file tree
Showing 12 changed files with 84 additions and 71 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"prepare": "husky install",
"prisma:generate": "prisma generate --schema=./services/prisma/schema.prisma",
"migrate:platform": "ts-node -r tsconfig-paths/register scripts/migrates/platform.ts",
"test:platform-api": "jest --coverage --config jest.config.js",
"test:platform-api": "jest --config jest.config.js",
"lint:ts": "tslint --fix -c tslint.json --project ./"
},
"dependencies": {
Expand Down
13 changes: 5 additions & 8 deletions pages/api/oauth/[...route].ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@ import { NextApiRequest, NextApiResponse, NextApiHandler } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "@/pages/api/auth/[...nextauth]";

import actions from "@/services/oauth/actions";
import passport from "passport";
import nextConnect from "next-connect";

import StackOverflowProvider from "@/services/oauth/providers/stackoverflow";
import GithubProvider from "@/services/oauth/providers/github";
import WakatimeProvider from "@/services/oauth/providers/wakatime";
import OAuthProviders from "@/services/oauth/providers";
import actions from "@/services/oauth/actions";

async function handler(req: NextApiRequest, res: NextApiResponse, next: any) {
const session = await getServerSession(req, res, authOptions);
Expand Down Expand Up @@ -78,9 +75,9 @@ async function handler(req: NextApiRequest, res: NextApiResponse, next: any) {
return res.status(404).send("Not Found");
}

passport.use("stackoverflow", StackOverflowProvider);
passport.use("github", GithubProvider);
passport.use("wakatime", WakatimeProvider);
passport.use("stackoverflow", OAuthProviders.StackOverflow);
passport.use("github", OAuthProviders.Github);
passport.use("wakatime", OAuthProviders.Wakatime);

export default nextConnect()
.use(passport.initialize())
Expand Down
6 changes: 3 additions & 3 deletions pages/api/platform/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import * as templates from "@/components/svgs/github";
import handlePlatformAPI from "@/services/api/handler";

import nextConnect from "next-connect";
import GithubProvider from "@/services/oauth/providers/github";
import OAuthProviders from "@/services/oauth/providers";
import passport from "passport";
import refresh from "passport-oauth2-refresh";

passport.use("github", GithubProvider);
refresh.use("github", GithubProvider);
passport.use("github", OAuthProviders.Github);
refresh.use("github", OAuthProviders.Github);
export default nextConnect()
.use(passport.initialize())
.get(handlePlatformAPI("github", services, templates));
6 changes: 3 additions & 3 deletions pages/api/platform/stackoverflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import * as templates from "@/components/svgs/stackoverflow";
import handlePlatformAPI from "@/services/api/handler";

import nextConnect from "next-connect";
import StackOverflowProvider from "@/services/oauth/providers/stackoverflow";
import OAuthProviders from "@/services/oauth/providers";
import passport from "passport";
import refresh from "passport-oauth2-refresh";

passport.use("stackoverflow", StackOverflowProvider);
refresh.use("stackoverflow", StackOverflowProvider);
passport.use("stackoverflow", OAuthProviders.StackOverflow);
refresh.use("stackoverflow", OAuthProviders.StackOverflow);
export default nextConnect()
.use(passport.initialize())
.get(handlePlatformAPI("stackoverflow", services, templates));
6 changes: 3 additions & 3 deletions pages/api/platform/wakatime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import * as templates from "@/components/svgs/wakatime";
import handlePlatformAPI from "@/services/api/handler";

import nextConnect from "next-connect";
import WakatimeProvider from "@/services/oauth/providers/wakatime";
import OAuthProviders from "@/services/oauth/providers";
import passport from "passport";
import refresh from "passport-oauth2-refresh";

passport.use("wakatime", WakatimeProvider);
refresh.use("wakatime", WakatimeProvider);
passport.use("wakatime", OAuthProviders.Wakatime);
refresh.use("wakatime", OAuthProviders.Wakatime);
export default nextConnect()
.use(passport.initialize())
.get(handlePlatformAPI("wakatime", services, templates));
98 changes: 51 additions & 47 deletions services/api/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
import { getPlatformResponse } from "@/services/platform/response";
import prisma from "@/services/prisma";

import { availableOAuthProviders } from "@/services/oauth/providers";
import { requestNewAccessToken } from "passport-oauth2-refresh";
import actions from "@/services/oauth/actions";
import { Connection } from "@prisma/client";
Expand Down Expand Up @@ -38,55 +39,58 @@ const handlePlatformAPI: PlatformAPIHandler = (
where: { userId: uid, platformId: platform.id },
});

let connection = await prisma.connection.findFirst({
where: { userId: uid, platformId: platform.id },
});

if (!connection)
return res
.status(404)
.json({ message: "User has no connection on this platform" });

// Refreshing access token
// TODO: refactor this
// it should work on the network request level, not on the API layers
if (connection.expires_at && Date.now() > connection.expires_at) {
const updated_connection = await new Promise<Connection | Error>(
(resolve, reject) => {
if (!connection) return reject("No connection found");
requestNewAccessToken(
platformCode,
connection.refresh_token,
async (
err: { statusCode: number; data?: any },
access_token: string,
refresh_token: string,
result: any
) => {
if (err) {
console.log(err);
res.status(err.statusCode).json({ message: err.data });
throw new Error(err.data);
var connection: Connection | null = null;
if (availableOAuthProviders.includes(platformCode)) {
connection = await prisma.connection.findFirst({
where: { userId: uid, platformId: platform.id },
});

if (!connection)
return res
.status(404)
.json({ message: "User has no connection on this platform" });

// Refreshing access token
// TODO: refactor this
// it should work on the network request level, not on the API layers
if (connection.expires_at && Date.now() > connection.expires_at) {
const updated_connection = await new Promise<Connection | Error>(
(resolve, reject) => {
if (!connection) return reject("No connection found");
requestNewAccessToken(
platformCode,
connection.refresh_token,
async (
err: { statusCode: number; data?: any },
access_token: string,
refresh_token: string,
result: any
) => {
if (err) {
console.log(err);
res.status(err.statusCode).json({ message: err.data });
throw new Error(err.data);
}

if (!connection) return reject("No connection found");

return actions
.updateConnection({
connection,
data: {
access_token,
expires_at: Date.now() + Number(result.expires_in) * 1000,
},
})
.then(resolve);
}
);
}
);

if (!connection) return reject("No connection found");

return actions
.updateConnection({
connection,
data: {
access_token,
expires_at: Date.now() + Number(result.expires_in) * 1000,
},
})
.then(resolve);
}
);
}
);

if (updated_connection instanceof Error) return;
connection = updated_connection;
if (updated_connection instanceof Error) return;
connection = updated_connection;
}
}

const result = await getPlatformResponse(
Expand Down
5 changes: 0 additions & 5 deletions services/oauth/index.ts

This file was deleted.

1 change: 1 addition & 0 deletions services/oauth/providers/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,5 @@ const strategy = new Strategy(
}
);

strategy.name = "github";
export default strategy;
14 changes: 14 additions & 0 deletions services/oauth/providers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import Github from "./github";
import StackOverflow from "./stackoverflow";
import Wakatime from "./wakatime";

const OAuthProviders = {
Github,
StackOverflow,
Wakatime,
};

export const availableOAuthProviders = Object.values(OAuthProviders).map(
(provider) => provider.name
);
export default OAuthProviders;
1 change: 1 addition & 0 deletions services/oauth/providers/stackoverflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,5 @@ const strategy = new Strategy(
}
);

strategy.name = "stackoverflow";
export default strategy;
1 change: 1 addition & 0 deletions services/oauth/providers/wakatime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,5 @@ const strategy = new OAuth2Strategy(
}
);

strategy.name = "wakatime";
export default strategy;
2 changes: 1 addition & 1 deletion services/platform/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const getPlatformResponse = async (
query: any,
services: any,
templates: any,
connection: Connection,
connection: Connection | null,
userConfig: any | undefined
) => {
const { method, returnType } = query;
Expand Down

0 comments on commit 6596555

Please sign in to comment.