next-tinacms-github
Advanced tools
Comparing version 0.0.2-canary4.0 to 0.0.2-canary4.1
@@ -6,4 +6,12 @@ # Change Log | ||
## [0.0.2-canary4.1](https://github.com/tinacms/tinacms/compare/next-tinacms-github@0.0.2-canary4.0...next-tinacms-github@0.0.2-canary4.1) (2020-04-14) | ||
**Note:** Version bump only for package next-tinacms-github | ||
## 0.0.2-canary4.0 (2020-04-07) | ||
**Note:** Version bump only for package next-tinacms-github |
@@ -1,18 +0,1 @@ | ||
/** | ||
Copyright 2019 Forestry.io Inc | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
export declare const createProxy: (authTokenKey: string) => (req: any, res: any) => void; | ||
export declare const apiProxy: (req: any, res: any) => void; |
@@ -19,4 +19,4 @@ /** | ||
export * from './next/preview'; | ||
export * from './github/create-access-token'; | ||
export * from './github/create-auth-handler'; | ||
export * from './github/proxy'; | ||
export * from './github/content'; |
@@ -27,12 +27,31 @@ 'use strict'; | ||
*/ | ||
var createPreviewFn = function createPreviewFn(forkCookieKey, headBranchCookieKey, githubAccessTokenCookieKey) { | ||
return function (req, res) { | ||
var previewData = { | ||
fork_full_name: req.cookies[forkCookieKey], | ||
github_access_token: req.cookies[githubAccessTokenCookieKey], | ||
head_branch: req.cookies[headBranchCookieKey] || 'master' | ||
}; | ||
res.setPreviewData(previewData); | ||
res.status(200).end(); | ||
var ACCESS_TOKEN_KEY = 'github_access_token'; | ||
var FORK_KEY = 'fork_full_name'; | ||
var HEAD_BRANCH_KEY = 'head_branch'; | ||
/** | ||
Copyright 2019 Forestry.io Inc | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
var previewHandler = function previewHandler(req, res) { | ||
var previewData = { | ||
fork_full_name: req.cookies[FORK_KEY], | ||
github_access_token: req.cookies[ACCESS_TOKEN_KEY], | ||
head_branch: req.cookies[HEAD_BRANCH_KEY] || 'master' | ||
}; | ||
res.setPreviewData(previewData); | ||
res.status(200).end(); | ||
}; | ||
@@ -57,2 +76,3 @@ | ||
*/ | ||
var qs = | ||
@@ -65,3 +85,3 @@ /*#__PURE__*/ | ||
require('axios'); | ||
var createCreateAccessTokenFn = function createCreateAccessTokenFn(clientId, secret) { | ||
var createAuthHandler = function createAuthHandler(clientId, secret) { | ||
return function (req, res) { | ||
@@ -78,3 +98,3 @@ createAccessToken(clientId, secret, req.query.code, req.query.state).then(function (tokenResp) { | ||
} else { | ||
res.setHeader('Set-Cookie', cookie.serialize('github_access_token', access_token, { | ||
res.setHeader('Set-Cookie', cookie.serialize(ACCESS_TOKEN_KEY, access_token, { | ||
path: '/', | ||
@@ -221,19 +241,2 @@ httpOnly: true | ||
/** | ||
Copyright 2019 Forestry.io Inc | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
var axios$1 = | ||
@@ -243,18 +246,16 @@ /*#__PURE__*/ | ||
var createProxy = function createProxy(authTokenKey) { | ||
return function (req, res) { | ||
var _JSON$parse = JSON.parse(req.body), | ||
headers = _JSON$parse.headers, | ||
data = _objectWithoutPropertiesLoose(_JSON$parse, ["headers"]); | ||
var apiProxy = function apiProxy(req, res) { | ||
var _JSON$parse = JSON.parse(req.body), | ||
headers = _JSON$parse.headers, | ||
data = _objectWithoutPropertiesLoose(_JSON$parse, ["headers"]); | ||
axios$1(_extends({}, data, { | ||
headers: _extends({}, headers, { | ||
Authorization: 'token ' + req.cookies[authTokenKey] | ||
}) | ||
})).then(function (resp) { | ||
res.status(resp.status).json(resp.data); | ||
})["catch"](function (err) { | ||
res.status(err.response.status).json(err.response.data); | ||
}); | ||
}; | ||
axios$1(_extends({}, data, { | ||
headers: _extends({}, headers, { | ||
Authorization: 'token ' + req.cookies[ACCESS_TOKEN_KEY] | ||
}) | ||
})).then(function (resp) { | ||
res.status(resp.status).json(resp.data); | ||
})["catch"](function (err) { | ||
res.status(err.response.status).json(err.response.data); | ||
}); | ||
}; | ||
@@ -502,5 +503,4 @@ | ||
exports.GithubError = GithubError; | ||
exports.createCreateAccessTokenFn = createCreateAccessTokenFn; | ||
exports.createPreviewFn = createPreviewFn; | ||
exports.createProxy = createProxy; | ||
exports.apiProxy = apiProxy; | ||
exports.createAuthHandler = createAuthHandler; | ||
exports.getContent = getContent; | ||
@@ -510,2 +510,3 @@ exports.getFiles = getFiles; | ||
exports.getMarkdownFile = getMarkdownFile; | ||
exports.previewHandler = previewHandler; | ||
//# sourceMappingURL=next-tinacms-github.cjs.development.js.map |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e=require("cookie"),r=(t=require("gray-matter"))&&"object"==typeof t&&"default"in t?t.default:t,n=require("qs"),o=require("axios");function a(){return(a=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function i(t,e){return(i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function c(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}function s(t,e,r){return(s=c()?Reflect.construct:function(t,e,r){var n=[null];n.push.apply(n,e);var o=new(Function.bind.apply(t,n));return r&&i(o,r.prototype),o}).apply(null,arguments)}function f(t){var e="function"==typeof Map?new Map:void 0;return(f=function(t){if(null===t||-1===Function.toString.call(t).indexOf("[native code]"))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return s(t,arguments,u(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),i(r,t)})(t)}var l=require("axios"),p=require("axios"),h=function(t,e,r,n){try{return Promise.resolve(p({method:"GET",url:"https://api.github.com/repos/"+t+"/contents/"+r+"?ref="+e,headers:{Authorization:"token "+n}}))}catch(t){return Promise.reject(t)}};function y(t,e){try{var r=t()}catch(t){return e(t)}return r&&r.then?r.then(void 0,e):r}"undefined"!=typeof Symbol&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator"))),"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator")));var d=function(t){var e,r;function n(e,r){var n;return(n=t.call(this,e)||this).message=e,n.status=r,n}return r=t,(e=n).prototype=Object.create(r.prototype),e.prototype.constructor=e,e.__proto__=r,n}(f(Error)),m=require("atob"),v=function(t,e,r,n){try{var o=function(t){return u?t:a({},i,{content:(e=i.content,decodeURIComponent(m(e).split("").map((function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})).join("")))});var e},u=!1,i=null,c=y((function(){return Promise.resolve(h(t,e,r,n)).then((function(t){i=t.data}))}),(function(t){var e,r=(null===(e=t.response)||void 0===e?void 0:e.status)||500;throw new d("Failed to get data.",r)}));return Promise.resolve(c&&c.then?c.then(o):o(c))}catch(t){return Promise.reject(t)}};exports.GithubError=d,exports.createCreateAccessTokenFn=function(t,r){return function(a,u){(function(t,e,r,a){return o.post("https://github.com/login/oauth/access_token",n.stringify({client_id:t,client_secret:e,code:r,state:a}))})(t,r,a.query.code,a.query.state).then((function(t){var r=n.parse(t.data),o=r.access_token,a=r.error;a?u.status(400).json({error:a}):(u.setHeader("Set-Cookie",e.serialize("github_access_token",o,{path:"/",httpOnly:!0})),u.status(200).json({}))}))}},exports.createPreviewFn=function(t,e,r){return function(n,o){o.setPreviewData({fork_full_name:n.cookies[t],github_access_token:n.cookies[r],head_branch:n.cookies[e]||"master"}),o.status(200).end()}},exports.createProxy=function(t){return function(e,r){var n=JSON.parse(e.body),o=n.headers,u=function(t,e){if(null==t)return{};var r,n,o={},a=Object.keys(t);for(n=0;n<a.length;n++)e.indexOf(r=a[n])>=0||(o[r]=t[r]);return o}(n,["headers"]);l(a({},u,{headers:a({},o,{Authorization:"token "+e.cookies[t]})})).then((function(t){r.status(t.status).json(t.data)})).catch((function(t){r.status(t.response.status).json(t.response.data)}))}},exports.getContent=h,exports.getFiles=function(t,e,r){try{var n,o=function(t){return a?t:n.filter((function(t){return"file"===t.type})).map((function(t){return t.path}))},a=!1,u=y((function(){return Promise.resolve(h(e.forkFullName,e.headBranch||"master",t,r)).then((function(t){n=t.data}))}),(function(t){var e,r=(null===(e=t.response)||void 0===e?void 0:e.status)||500;throw new d("Failed to get data.",r)}));return Promise.resolve(u&&u.then?u.then(o):o(u))}catch(t){return Promise.reject(t)}},exports.getJsonFile=function(t,e,r){try{return Promise.resolve(v(e.forkFullName,e.headBranch||"master",t,r)).then((function(e){return{sha:e.sha,fileRelativePath:t,data:JSON.parse(e.content)}}))}catch(t){return Promise.reject(t)}},exports.getMarkdownFile=function(t,e,n){try{return Promise.resolve(v(e.forkFullName,e.headBranch||"master",t,n)).then((function(e){var n=r(e.content);return{sha:e.sha,fileRelativePath:t,data:{frontmatter:n.data,markdownBody:n.content}}}))}catch(t){return Promise.reject(t)}}; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e=require("cookie"),r=(t=require("gray-matter"))&&"object"==typeof t&&"default"in t?t.default:t,n=require("qs"),o=require("axios");function a(){return(a=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t}).apply(this,arguments)}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function i(t,e){return(i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function c(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(t){return!1}}function s(t,e,r){return(s=c()?Reflect.construct:function(t,e,r){var n=[null];n.push.apply(n,e);var o=new(Function.bind.apply(t,n));return r&&i(o,r.prototype),o}).apply(null,arguments)}function f(t){var e="function"==typeof Map?new Map:void 0;return(f=function(t){if(null===t||-1===Function.toString.call(t).indexOf("[native code]"))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return s(t,arguments,u(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),i(r,t)})(t)}var l=require("axios"),p=require("axios"),h=function(t,e,r,n){try{return Promise.resolve(p({method:"GET",url:"https://api.github.com/repos/"+t+"/contents/"+r+"?ref="+e,headers:{Authorization:"token "+n}}))}catch(t){return Promise.reject(t)}};function d(t,e){try{var r=t()}catch(t){return e(t)}return r&&r.then?r.then(void 0,e):r}"undefined"!=typeof Symbol&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator"))),"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator")));var y=function(t){var e,r;function n(e,r){var n;return(n=t.call(this,e)||this).message=e,n.status=r,n}return r=t,(e=n).prototype=Object.create(r.prototype),e.prototype.constructor=e,e.__proto__=r,n}(f(Error)),m=require("atob"),v=function(t,e,r,n){try{var o=function(t){return u?t:a({},i,{content:(e=i.content,decodeURIComponent(m(e).split("").map((function(t){return"%"+("00"+t.charCodeAt(0).toString(16)).slice(-2)})).join("")))});var e},u=!1,i=null,c=d((function(){return Promise.resolve(h(t,e,r,n)).then((function(t){i=t.data}))}),(function(t){var e,r=(null===(e=t.response)||void 0===e?void 0:e.status)||500;throw new y("Failed to get data.",r)}));return Promise.resolve(c&&c.then?c.then(o):o(c))}catch(t){return Promise.reject(t)}};exports.GithubError=y,exports.apiProxy=function(t,e){var r=JSON.parse(t.body),n=r.headers,o=function(t,e){if(null==t)return{};var r,n,o={},a=Object.keys(t);for(n=0;n<a.length;n++)e.indexOf(r=a[n])>=0||(o[r]=t[r]);return o}(r,["headers"]);l(a({},o,{headers:a({},n,{Authorization:"token "+t.cookies.github_access_token})})).then((function(t){e.status(t.status).json(t.data)})).catch((function(t){e.status(t.response.status).json(t.response.data)}))},exports.createAuthHandler=function(t,r){return function(a,u){(function(t,e,r,a){return o.post("https://github.com/login/oauth/access_token",n.stringify({client_id:t,client_secret:e,code:r,state:a}))})(t,r,a.query.code,a.query.state).then((function(t){var r=n.parse(t.data),o=r.access_token,a=r.error;a?u.status(400).json({error:a}):(u.setHeader("Set-Cookie",e.serialize("github_access_token",o,{path:"/",httpOnly:!0})),u.status(200).json({}))}))}},exports.getContent=h,exports.getFiles=function(t,e,r){try{var n,o=function(t){return a?t:n.filter((function(t){return"file"===t.type})).map((function(t){return t.path}))},a=!1,u=d((function(){return Promise.resolve(h(e.forkFullName,e.headBranch||"master",t,r)).then((function(t){n=t.data}))}),(function(t){var e,r=(null===(e=t.response)||void 0===e?void 0:e.status)||500;throw new y("Failed to get data.",r)}));return Promise.resolve(u&&u.then?u.then(o):o(u))}catch(t){return Promise.reject(t)}},exports.getJsonFile=function(t,e,r){try{return Promise.resolve(v(e.forkFullName,e.headBranch||"master",t,r)).then((function(e){return{sha:e.sha,fileRelativePath:t,data:JSON.parse(e.content)}}))}catch(t){return Promise.reject(t)}},exports.getMarkdownFile=function(t,e,n){try{return Promise.resolve(v(e.forkFullName,e.headBranch||"master",t,n)).then((function(e){var n=r(e.content);return{sha:e.sha,fileRelativePath:t,data:{frontmatter:n.data,markdownBody:n.content}}}))}catch(t){return Promise.reject(t)}},exports.previewHandler=function(t,e){e.setPreviewData({fork_full_name:t.cookies.fork_full_name,github_access_token:t.cookies.github_access_token,head_branch:t.cookies.head_branch||"master"}),e.status(200).end()}; | ||
//# sourceMappingURL=next-tinacms-github.cjs.production.min.js.map |
@@ -21,12 +21,31 @@ import { serialize } from 'cookie'; | ||
*/ | ||
var createPreviewFn = function createPreviewFn(forkCookieKey, headBranchCookieKey, githubAccessTokenCookieKey) { | ||
return function (req, res) { | ||
var previewData = { | ||
fork_full_name: req.cookies[forkCookieKey], | ||
github_access_token: req.cookies[githubAccessTokenCookieKey], | ||
head_branch: req.cookies[headBranchCookieKey] || 'master' | ||
}; | ||
res.setPreviewData(previewData); | ||
res.status(200).end(); | ||
var ACCESS_TOKEN_KEY = 'github_access_token'; | ||
var FORK_KEY = 'fork_full_name'; | ||
var HEAD_BRANCH_KEY = 'head_branch'; | ||
/** | ||
Copyright 2019 Forestry.io Inc | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
var previewHandler = function previewHandler(req, res) { | ||
var previewData = { | ||
fork_full_name: req.cookies[FORK_KEY], | ||
github_access_token: req.cookies[ACCESS_TOKEN_KEY], | ||
head_branch: req.cookies[HEAD_BRANCH_KEY] || 'master' | ||
}; | ||
res.setPreviewData(previewData); | ||
res.status(200).end(); | ||
}; | ||
@@ -51,2 +70,3 @@ | ||
*/ | ||
var qs = | ||
@@ -59,3 +79,3 @@ /*#__PURE__*/ | ||
require('axios'); | ||
var createCreateAccessTokenFn = function createCreateAccessTokenFn(clientId, secret) { | ||
var createAuthHandler = function createAuthHandler(clientId, secret) { | ||
return function (req, res) { | ||
@@ -72,3 +92,3 @@ createAccessToken(clientId, secret, req.query.code, req.query.state).then(function (tokenResp) { | ||
} else { | ||
res.setHeader('Set-Cookie', serialize('github_access_token', access_token, { | ||
res.setHeader('Set-Cookie', serialize(ACCESS_TOKEN_KEY, access_token, { | ||
path: '/', | ||
@@ -215,19 +235,2 @@ httpOnly: true | ||
/** | ||
Copyright 2019 Forestry.io Inc | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
var axios$1 = | ||
@@ -237,18 +240,16 @@ /*#__PURE__*/ | ||
var createProxy = function createProxy(authTokenKey) { | ||
return function (req, res) { | ||
var _JSON$parse = JSON.parse(req.body), | ||
headers = _JSON$parse.headers, | ||
data = _objectWithoutPropertiesLoose(_JSON$parse, ["headers"]); | ||
var apiProxy = function apiProxy(req, res) { | ||
var _JSON$parse = JSON.parse(req.body), | ||
headers = _JSON$parse.headers, | ||
data = _objectWithoutPropertiesLoose(_JSON$parse, ["headers"]); | ||
axios$1(_extends({}, data, { | ||
headers: _extends({}, headers, { | ||
Authorization: 'token ' + req.cookies[authTokenKey] | ||
}) | ||
})).then(function (resp) { | ||
res.status(resp.status).json(resp.data); | ||
})["catch"](function (err) { | ||
res.status(err.response.status).json(err.response.data); | ||
}); | ||
}; | ||
axios$1(_extends({}, data, { | ||
headers: _extends({}, headers, { | ||
Authorization: 'token ' + req.cookies[ACCESS_TOKEN_KEY] | ||
}) | ||
})).then(function (resp) { | ||
res.status(resp.status).json(resp.data); | ||
})["catch"](function (err) { | ||
res.status(err.response.status).json(err.response.data); | ||
}); | ||
}; | ||
@@ -495,3 +496,3 @@ | ||
export { GithubError, createCreateAccessTokenFn, createPreviewFn, createProxy, getContent, getFiles, getJsonFile, getMarkdownFile }; | ||
export { GithubError, apiProxy, createAuthHandler, getContent, getFiles, getJsonFile, getMarkdownFile, previewHandler }; | ||
//# sourceMappingURL=next-tinacms-github.esm.js.map |
@@ -18,2 +18,2 @@ /** | ||
*/ | ||
export declare const createPreviewFn: (forkCookieKey: string, headBranchCookieKey: string, githubAccessTokenCookieKey: string) => (req: any, res: any) => void; | ||
export declare const previewHandler: (req: any, res: any) => void; |
{ | ||
"name": "next-tinacms-github", | ||
"version": "0.0.2-canary4.0", | ||
"version": "0.0.2-canary4.1", | ||
"description": "", | ||
@@ -25,3 +25,3 @@ "main": "dist/index.js", | ||
}, | ||
"gitHead": "c2663fa2c089a599d6c031967b972a577d4994fa" | ||
"gitHead": "1b64eb2e2236e7df68827b806413b2fe990f8332" | ||
} |
138
README.md
# next-tinacms-github | ||
This package provides helpers for managing the github auth token on the server. | ||
When used with Next.js in the `pages/api` directory, these functions are mapped to `/api/*` endpoints. | ||
This package provides helpers for managing the github auth token for requests, as well as | ||
providing helpers for loading content from the Github API. | ||
# `createCreateAccessTokenFn` | ||
Helper for creating a createCreateAccessToken server function. | ||
## Installation | ||
## Implementation | ||
``` | ||
npm install --save next-tinacms-github | ||
``` | ||
or | ||
``` | ||
yarn add next-tinacms-github | ||
``` | ||
## Getting Started | ||
Any functions in the `pages/api` directory are are mapped to `/api/*` endpoints. | ||
### `createCreateAccessTokenFn` | ||
Helper for creating a `createCreateAccessToken` server function. | ||
``` | ||
// pages/api/create-github-access-token.ts | ||
import { createCreateAccessTokenFn } from 'next-tinacms-github' | ||
import { createAuthHandler } from 'next-tinacms-github' | ||
export default createCreateAccessTokenFn( | ||
export default createAuthHandler( | ||
process.env.GITHUB_CLIENT_ID, | ||
@@ -22,20 +38,21 @@ process.env.GITHUB_CLIENT_SECRET | ||
# `createProxy` | ||
Helper for creating a proxy which attaches this Github access token to the request | ||
_See [Next's documentation](https://nextjs.org/docs/api-reference/next.config.js/environment-variables) for adding environment variables_ | ||
## Implementation | ||
[See below](#github-oauth-app) for instructions on creating a Github OAuth App to generate these **Client ID** & **Client Secret** variables. | ||
### `apiProxy` | ||
Proxies requests to GitHub, attaching the GitHub access token in the process | ||
``` | ||
// pages/api/proxy-github.ts | ||
import { createProxy } from 'next-tinacms-github' | ||
import { GITHUB_ACCESS_TOKEN_COOKIE_KEY } from './constants' | ||
import { apiProxy } from 'next-tinacms-github' | ||
export default createProxy(GITHUB_ACCESS_TOKEN_COOKIE_KEY) | ||
export default apiProxy | ||
``` | ||
# `createPreviewFn` | ||
Helper for creating a preview function which will set the preview data from Github cookies | ||
### `previewHandler` | ||
## Implementation | ||
Handles setting the the Nextjs [preview data](https://nextjs.org/docs/advanced-features/preview-mode) from your cookie data. | ||
@@ -45,10 +62,85 @@ ``` | ||
import { createPreviewFn } from 'next-tinacms-github' | ||
import { previewHandler } from 'next-tinacms-github' | ||
export default createPreviewFn( | ||
'fork_full_name', | ||
'head_branch', | ||
'github_access_token' | ||
) | ||
export default previewHandler | ||
``` | ||
``` | ||
### Loading content from Github | ||
The `preview` data, which gets set by calling your [preview function](#previewhandler), will be accesible through `getStaticProps` throughout your app. | ||
```ts | ||
//Blog template [slug].ts | ||
import { | ||
getMarkdownFile as getGithubMarkdownFile, | ||
} from 'next-tinacms-github' | ||
// ... | ||
export const getStaticProps: GetStaticProps = async function({ | ||
preview, | ||
previewData, | ||
...ctx | ||
}) { | ||
const { slug } = ctx.params | ||
let file = {} | ||
const filePath = `content/blog/${slug}.md` | ||
const sourceProviderConnection = { | ||
forkFullName: previewData.fork_full_name, | ||
headBranch: previewData.head_branch || 'master', | ||
} | ||
let error = null | ||
if(preview) { | ||
try { | ||
file = await getGithubMarkdownFile(filePath, | ||
sourceProviderConnection, | ||
previewData.accessToken) | ||
} | ||
catch (e) { | ||
// If there is an error initially loading the content from Github, we want to display an actionable error | ||
// to the user. They may need to re-authenticate or create a new fork. | ||
if (e instanceof GithubError) { | ||
error = { ...e } //workaround since we cant return error as JSON | ||
} else { | ||
throw e | ||
} | ||
} | ||
} | ||
else { | ||
// Get your production content here | ||
// when you are not in edit-mode | ||
file = await readLocalMarkdownFile(filePath) | ||
} | ||
return { | ||
props: { | ||
sourceProviderConnection, | ||
editMode: !!preview, | ||
file, | ||
error | ||
}, | ||
} | ||
} | ||
``` | ||
### Github Oauth App: | ||
In GitHub, within your account Settings, click [Oauth Apps](https://github.com/settings/developers) under Developer Settings. | ||
click "New Oauth App". | ||
For the **Authorization callback URL**, enter the url for the "authorizing" page that you created above (e.g https://your-url/github/authorizing). Fill out the other fields with your custom values. | ||
_Note: If you are testing your app locally, you may need a separate development Github app (with a localhost redirect), and a production Github app._ | ||
The generated **Client ID** & **Client Secret** will be consumed by the `createCreateAccessTokenFn` [defined above](#createcreateaccesstokenfn). | ||
## Next steps | ||
Now that we have configured our backend API functions to manage our Github authentication token, we will need to configure the front-end to use these endpoints. | ||
You may want to use the [next-tinacms-github](https://github.com/tinacms/tinacms/tree/master/packages/react-tinacms-github) package. |
@@ -18,6 +18,7 @@ /** | ||
*/ | ||
import { ACCESS_TOKEN_KEY } from '../constants' | ||
const axios = require('axios') | ||
export const createProxy = (authTokenKey: string) => (req: any, res: any) => { | ||
export const apiProxy = (req: any, res: any) => { | ||
const { headers, ...data } = JSON.parse(req.body) | ||
@@ -29,3 +30,3 @@ | ||
...headers, | ||
Authorization: 'token ' + req.cookies[authTokenKey], | ||
Authorization: 'token ' + req.cookies[ACCESS_TOKEN_KEY], | ||
}, | ||
@@ -32,0 +33,0 @@ }) |
@@ -20,4 +20,4 @@ /** | ||
export * from './next/preview' | ||
export * from './github/create-access-token' | ||
export * from './github/create-auth-handler' | ||
export * from './github/proxy' | ||
export * from './github/content' |
@@ -19,11 +19,9 @@ /** | ||
export const createPreviewFn = ( | ||
forkCookieKey: string, | ||
headBranchCookieKey: string, | ||
githubAccessTokenCookieKey: string | ||
) => (req: any, res: any) => { | ||
import { ACCESS_TOKEN_KEY, FORK_KEY, HEAD_BRANCH_KEY } from '../constants' | ||
export const previewHandler = (req: any, res: any) => { | ||
const previewData = { | ||
fork_full_name: req.cookies[forkCookieKey], | ||
github_access_token: req.cookies[githubAccessTokenCookieKey], | ||
head_branch: req.cookies[headBranchCookieKey] || 'master', | ||
fork_full_name: req.cookies[FORK_KEY], | ||
github_access_token: req.cookies[ACCESS_TOKEN_KEY], | ||
head_branch: req.cookies[HEAD_BRANCH_KEY] || 'master', | ||
} | ||
@@ -30,0 +28,0 @@ res.setPreviewData(previewData) |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
195308
40
1443
145
0