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] Gitlab #252

Open
wants to merge 4 commits into
base: v1-alpha
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions api-module-library/gitlab/.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/gitlab/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/gitlab/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) 2023 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.
19 changes: 19 additions & 0 deletions api-module-library/gitlab/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# GitLab

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

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

### How to create a new App

1 - Go to [this url](https://gitlab.com/-/user_settings/applications).
2 - Click on "Add new application" under `Your Applications`.
3 - 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/)
- **Redirect URL**: http://localhost:3000/redirect/gitlab
- **Scopes**: api read_api read_repository read_user write_repository

3 - Click on the "Save 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.
162 changes: 162 additions & 0 deletions api-module-library/gitlab/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
const { OAuth2Requester } = require('@friggframework/module-plugin');
const { get } = require('@friggframework/assertions');

class Api extends OAuth2Requester {
constructor(params) {
super(params);
this.cachedUserData = undefined
this.expires_in = get(params, 'expires_in', null);
this.created_at = get(params, 'created_at', null);
this.refresh_token = get(params, 'refresh_token', null);
this.token_type = get(params, 'token_type', 'bearer');
this.access_token = get(params, 'access_token', null);
this.base_url = get(params, 'base_url', 'https://gitlab.com');
this.URLs = {
me: '/api/v4/user',
getProjects: (userId) => `/api/v4/users/${userId}/projects`,
getProjectIssues: (projectId) => `/api/v4/projects/${projectId}/issues`,
createProjectIssue: (projectId, searchParams) => `/api/v4/projects/${projectId}/issues?${searchParams.toString()}`,
deleteProjectIssue: (projectId, issueIid) => `/api/v4/projects/${projectId}/issues/${issueIid}`,
};
}

get tokenUri() {
return `${this.base_url}/oauth/token`
}

getAuthorizationUri() {
const searchParams = new URLSearchParams([
['client_id', this.client_id],
['redirect_uri', this.redirect_uri],
['scope', this.scope],
['response_type', 'code']
]);
return `${this.base_url}/oauth/authorize?${searchParams.toString()}`;
}

async setTokens(params) {
this.token_type = get(params, 'token_type', 'bearer');
this.created_at = get(params, 'created_at', Date.now());
this.expires_in = get(params, 'expires_in', Infinity);
await super.setTokens(params);
}

async getTokenFromCode(code) {
const body = new URLSearchParams([
['client_id', this.client_id],
['client_secret', this.client_secret],
['code', code],
['grant_type', 'authorization_code'],
['redirect_uri', this.redirect_uri]
]);
const options = {
body: body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Accept': 'application/json',
},
url: this.tokenUri,
};

const response = await this._post(options, false);
await this.setTokens(response);
return response;
}

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

async getUserDetails() {
const options = {
headers: this.getDefaultHeaders(),
url: this.base_url + this.URLs.me,
};

const response = await this._get(options);
this.userId = response.id;
return response;
}

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

/**
* Gets all of the repositories/projects for the user
*
* @returns {Promise<import('./types').Project[]>} - An array of projects of the current logged user.
*/
async getProjects() {
const userData = await this.getUserDetails();

const options = {
headers: this.getDefaultHeaders(),
url: this.base_url + this.URLs.getProjects(userData.id),
}
return this._get(options);
}

/**
* Gets all of the issues for a project by its id
*
* @param {`${number}` | number} projectId - The id of the project to get the issues for.
*
* @returns {Promise<import('./types').Issues[]>} - An array of issues for the project.
*/
async getProjectIssues(projectId) {
const options = {
headers: this.getDefaultHeaders(),
url: this.base_url + this.URLs.getProjectIssues(projectId),
}
return this._get(options);
}

/**
* Creates a new issue for a project by its id
*
* @param {`${number}` | number} projectId - The id of the project to create the issue for.
* @param {import('./types').CreateIssue} data - The data to create the issue.
*
* @returns {Promise<import('./types').Issues>} - The created issue.
*/
async createProjectIssue(projectId, data) {
if (Array.isArray(data.labels)) {
data.labels = data.labels.join(',');
}

const searchParams = new URLSearchParams(data);

const options = {
headers: this.getDefaultHeaders(),
url: this.base_url + this.URLs.createProjectIssue(projectId, searchParams),
}
return this._post(options);
}

/**
* Deletes an issue for a project by its id
*
* @param {`${number}` | number} projectId - The id of the project to delete the issue for.
* @param {`${number}` | number} issueIid - The iid of the issue to delete.
*
* @returns {Promise<void>} - Returns nothing.
*/
async deleteProjectIssue(projectId, issueIid) {
const options = {
headers: this.getDefaultHeaders(),
url: this.base_url + this.URLs.deleteProjectIssue(projectId, issueIid),
}
const response = await this._delete(options);

return response.status === 204 ? true : false;
}

}

module.exports = { Api };
9 changes: 9 additions & 0 deletions api-module-library/gitlab/defaultConfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "gitlab",
"label": "GitLab",
"productUrl": "",
"apiDocs": "",
"logoUrl": "https://images.ctfassets.net/xz1dnu24egyd/1IRkfXmxo8VP2RAE5jiS1Q/ea2086675d87911b0ce2d34c354b3711/gitlab-logo-500.png",
"categories": [],
"description": "GitLab"
}
49 changes: 49 additions & 0 deletions api-module-library/gitlab/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) {
return api.getTokenFromCode(get(params.data, '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', 'refresh_token', 'token_type', 'expires_in', 'created_at'],
entity: [],
},
getCredentialDetails: async function (api) {
const userDetails = await api.getTokenIdentity();
return {
identifiers: { externalId: userDetails.identifier },
details: {}
};
},
testAuthRequest: async function (api) {
return api.getUserDetails()
},
},
env: {
client_id: process.env.GITLAB_CLIENT_ID,
client_secret: process.env.GITLAB_CLIENT_SECRET,
redirect_uri: `${process.env.REDIRECT_URI}/gitlab`,
scope: process.env.GITLAB_SCOPE,
base_url: process.env.GITLAB_BASE_URL,
}
};

module.exports = { Definition };
13 changes: 13 additions & 0 deletions api-module-library/gitlab/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/gitlab/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/gitlab/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/gitlab/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',
};
27 changes: 27 additions & 0 deletions api-module-library/gitlab/models/credential.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const mongoose = require('mongoose');
const { Credential: Parent } = require('@friggframework/module-plugin');
const schema = new mongoose.Schema({
access_token: {
type: String,
trim: true,
lhEncrypt: true,
},
refresh_token: {
type: String,
trim: true,
lhEncrypt: true,
},
token_type: {
type: String,
trim: true,
},
expires_in: {
type: Number,
},
created_at: {
type: Number,
},
});
const name = 'GitlabCredential';
const Credential = Parent.discriminators?.[name] || Parent.discriminator(name, schema);
module.exports = { Credential };
8 changes: 8 additions & 0 deletions api-module-library/gitlab/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 = 'GitlabEntity';
const Entity =
Parent.discriminators?.[name] || Parent.discriminator(name, schema);
module.exports = { Entity };
28 changes: 28 additions & 0 deletions api-module-library/gitlab/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "@friggframework/api-module-gitlab",
"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