Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Api Module] Github #251

Open
wants to merge 9 commits into
base: v1-alpha
Choose a base branch
from
3 changes: 3 additions & 0 deletions api-module-library/github/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "@friggframework/eslint-config"
}
5 changes: 5 additions & 0 deletions api-module-library/github/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# v0.0.1 (Feb 10 2024)

#### Generated

- Initialized from challenge
9 changes: 9 additions & 0 deletions api-module-library/github/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) 2024 Left Hook Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
18 changes: 18 additions & 0 deletions api-module-library/github/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Github

This is the API Module for Github that allows the [Frigg](https://friggframework.org) code to talk to the Github API.

Read more on the [Frigg documentation site](https://docs.friggframework.org/api-modules/list/github)

### How to create a new App

1- Go to [this url](https://github.com/settings/applications/new).
2- Fill in the form with the following information:

- **GitHub App name**: The name of your app
- **Homepage URL**: [The URL of your app](https://lefthook.com/)
- **User authorization callback URL**: http://localhost:3000/redirect/github

3 - Click on the "Register application" button.
4 - You will be redirected to the app settings page. Copy the **Client ID** and **Client Secret** and paste them in your `.env` file.
5 - `GITHUB_SCOPE` can default to **repo** and **user** for now like this: `GITHUB_SCOPE=repo user`
157 changes: 157 additions & 0 deletions api-module-library/github/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
const { OAuth2Requester } = require('@friggframework/module-plugin');
const { get } = require('@friggframework/assertions');

class Api extends OAuth2Requester {
constructor(params) {
super(params);
this.cachedUserData = undefined
this.scope = get(params, 'scope', 'user');
this.token_type = get(params, 'token_type', 'bearer');
this.access_token = get(params, 'access_token', null);

this.baseUrl = 'https://api.github.com';
this.meUrl = 'https://api.github.com/user'
this.URLs = {
me: '/user',
getIssues: (owner, repoName) => `/repos/${owner}/${repoName}/issues`,
getIssue: (owner, repoName, issueNumber) => `/repos/${owner}/${repoName}/issues/${issueNumber}`
};
this.tokenUri = 'https://github.com/login/oauth/access_token';
}

getAuthorizationUri() {
const searchParams = new URLSearchParams([[
'client_id', this.client_id
], [
'redirect_uri', this.redirect_uri
], [
'scope', this.scope
]]);
return `https://github.com/login/oauth/authorize?${searchParams.toString()}`;
}

async getTokenFromCode(code) {
const options = {
body: {
client_id: this.client_id,
client_secret: this.client_secret,
code: code,
},
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
url: this.tokenUri,
};
const response = await this._post(options, true);
await this.setTokens(response);
return response;
}

/**
* Retrieves the authenticated user details from the API.
*
* @returns {Promise<import('./types').User>} - The user data. We use that to get the urls to fetch to retrieve that that is assigned to the user.
*/
async getUserDetails() {
const options = {
headers: {
'Authorization': `${(this.token_type || '').toUpperCase()} ${this.access_token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
url: this.baseUrl + this.URLs.me,
};
return await this._get(options);;
}

async getDefaultHeaders() {
return {
'Authorization': `${(this.token_type || '').toUpperCase()} ${this.access_token}`,
'Content-Type': 'application/json',
'Accept': 'application/json',
}
}

async getTokenIdentity() {
const userInfo = await this.getUserDetails();
return { identifier: userInfo.id, name: userInfo.name }
}

/**
* Retrieves all repositories for the authenticated user.
*
* @returns {Promise<import('./types').Repository[]>} - All of the repositories found for the user.
*/
async getRepos() {
const userData = await this.getUserDetails();
if (userData.repos_url) {
const options = {
headers: this.getDefaultHeaders(),
url: userData.repos_url,
};
return this._get(options);
}
return [];
}

/**
* Retrieves all issues from a repository.
*
* @param {string} owner The account owner of the repository. The name is not case sensitive.
* @param {string} repoName - The name of the repository without the .git extension. The name is not case sensitive.
*
* @returns {Promise<import('./types').Issue[]>} - All of the issues found in the repository.
*/
async getIssues(owner, repoName) {
const options = {
headers: this.getDefaultHeaders(),
url: `${this.baseUrl}${this.URLs.getIssues(owner, repoName)}`,
};
return this._get(options);
}

/**
* Retrieves a single issue from a repository.
*
* @param {string} owner The account owner of the repository. The name is not case sensitive.
* @param {string} repoName - The name of the repository without the .git extension. The name is not case sensitive.
* @param {string} issueNumber - The number that identifies the issue. Usually you will find this right after the issue title for example: "Issue Title #123" #123 is the issue number
*
* @returns {Promise<import('./types').Issue>} - The found issue by it's id.
*/
async getIssue(owner, repoName, issueNumber) {
const options = {
headers: this.getDefaultHeaders(),
url: `${this.baseUrl}${this.URLs.getIssue(owner, repoName, issueNumber)}`,
};
return this._get(options);
}

/**
* Updates an existing issue.
*
* @param {string} owner The account owner of the repository. The name is not case sensitive.
* @param {string} repoName - The name of the repository without the .git extension. The name is not case sensitive.
* @param {string} issueNumber - The number that identifies the issue. Usually you will find this right after the issue title for example: "Issue Title #123" #123 is the issue number
* @param {object} data - The data to update the issue with
* @param {string | null | number} [data.title=undefined] - The title of the issue
* @param {string | null} [data.body=undefined] - The body of the issue
* @param {string | null} [data.state_reason=undefined] - The reason for the state change. Ignored unless state is changed.
* @param {string | null} [data.milestone=undefined] - The `number` of the milestone to associate this issue with or use `null` to remove the current milestone.
* Only users with push access can set the milestone for issues. Without push access to the repository, milestone changes are silently dropped.
* @param {string[]} [data.labels=undefined] - Labels to associate with this issue. Pass one or more labels to replace the set of labels on this issue. Send an empty array ([]) to clear all
* labels from the issue. Only users with push access can set labels for issues. Without push access to the repository, label changes are silently dropped.
* @returns {Promise<import('./types').Issue>} - The updated issue.
*/
async updateIssue(owner, repoName, issueNumber, data) {
const options = {
body: data,
headers: this.getDefaultHeaders(),
url: `${this.baseUrl}${this.URLs.getIssue(owner, repoName, issueNumber)}`,
};
return this._patch(options);
}
}

module.exports = { Api };
9 changes: 9 additions & 0 deletions api-module-library/github/defaultConfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "github",
"label": "GitHub",
"productUrl": "",
"apiDocs": "",
"logoUrl": "https://github.githubassets.com/assets/GitHub-Mark-ea2971cee799.png",
"categories": [],
"description": "GitHub"
}
49 changes: 49 additions & 0 deletions api-module-library/github/definition.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
require('dotenv').config();
const { Api } = require('./api');
const { Credential } = require('./models/credential');
const { Entity } = require('./models/entity');
const { get } = require("@friggframework/assertions");
const config = require('./defaultConfig.json')

const Definition = {
API: Api,
getName: function () { return config.name },
moduleName: config.name,
Credential,
Entity,
requiredAuthMethods: {
getToken: async function (api, params) {
const code = get(params.data, 'code');
return api.getTokenFromCode(code);
},
getEntityDetails: async function (api, _callbackParams, _tokenResponse, userId) {
const entityDetails = await api.getTokenIdentity();
return {
identifiers: { externalId: entityDetails.identifier, user: userId },
details: { name: entityDetails.name },
}
},
apiPropertiesToPersist: {
credential: ['access_token', 'token_type', 'scope'],
entity: [],
},
getCredentialDetails: async function (api) {
const userDetails = await api.getTokenIdentity();
return {
identifiers: { externalId: userDetails.identifier },
details: {}
};
},
testAuthRequest: async function (api) {
return await api.getUserDetails()
},
},
env: {
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET,
redirect_uri: `${process.env.REDIRECT_URI}/github`,
scope: process.env.GITHUB_SCOPE,
}
};

module.exports = { Definition };
13 changes: 13 additions & 0 deletions api-module-library/github/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const { Api } = require('./api');
const { Credential } = require('./models/credential');
const { Entity } = require('./models/entity');
const Config = require('./defaultConfig');
const { Definition } = require('./definition');

module.exports = {
Api,
Credential,
Entity,
Config,
Definition
};
2 changes: 2 additions & 0 deletions api-module-library/github/jest-setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const { globalSetup } = require('@friggframework/test-environment');
module.exports = globalSetup;
2 changes: 2 additions & 0 deletions api-module-library/github/jest-teardown.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const { globalTeardown } = require('@friggframework/test-environment');
module.exports = globalTeardown;
21 changes: 21 additions & 0 deletions api-module-library/github/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/

module.exports = {
// preset: '@friggframework/test-environment',
coverageThreshold: {
global: {
statements: 13,
branches: 0,
functions: 1,
lines: 13,
},
},
// A path to a module which exports an async function that is triggered once before all test suites
globalSetup: './jest-setup.js',

// A path to a module which exports an async function that is triggered once after all test suites
globalTeardown: './jest-teardown.js',
};
20 changes: 20 additions & 0 deletions api-module-library/github/models/credential.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const mongoose = require('mongoose');
const { Credential: Parent } = require('@friggframework/module-plugin');
const schema = new mongoose.Schema({
access_token: {
type: String,
trim: true,
lhEncrypt: true,
},
token_type: {
type: String,
trim: true,
},
scope: {
type: String,
trim: true,
},
});
const name = 'GithubCredential';
const Credential = Parent.discriminators?.[name] || Parent.discriminator(name, schema);
module.exports = { Credential };
8 changes: 8 additions & 0 deletions api-module-library/github/models/entity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const mongoose = require('mongoose');
const { Entity: Parent } = require('@friggframework/module-plugin');

const schema = new mongoose.Schema({});
const name = 'GithubEntity';
const Entity =
Parent.discriminators?.[name] || Parent.discriminator(name, schema);
module.exports = { Entity };
28 changes: 28 additions & 0 deletions api-module-library/github/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "@friggframework/api-module-github",
"version": "0.0.1-v1-alpha",
"prettier": "@friggframework/prettier-config",
"description": "",
"main": "index.js",
"scripts": {
"lint:fix": "prettier --write --loglevel error . && eslint . --fix",
"test": "jest"
},
"author": "",
"license": "MIT",
"devDependencies": {
"@friggframework/assertions": "^1.0.22-v1-alpha.6",
"@friggframework/eslint-config": "^1.0.21-v1-alpha.4",
"@friggframework/logs": "^1.0.24-v1-alpha.4",
"@friggframework/module-plugin": "^1.1.16-v1-alpha.7",
"@friggframework/test-environment": "^1.1.21-v1-alpha.4",
"dotenv": "^16.3.1",
"eslint": "^8.45.0",
"jest": "^29.6.1",
"prettier": "^3.0.0",
"sinon": "^15.2.0"
},
"publishConfig": {
"access": "public"
}
}
Loading
Loading