Created
August 15, 2018 09:40
-
-
Save MadeBaruna/7dd6ee3f7c3e321a8e1d83912d68826b to your computer and use it in GitHub Desktop.
AccounKit API Backend Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"APP_ID": "{{YOUR_APP_ID}}", | |
"APP_SECRET": "{{YOUR_APP_SECRET}}", | |
"JWT_SECRET": "{{YOUR_JWT_SECRET}}" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require("express"); | |
const axios = require("axios"); | |
const querystring = require("querystring"); | |
const cors = require("cors"); | |
const jwt = require("jsonwebtoken"); | |
const jwt_middleware = require("express-jwt"); | |
const config = require("./config.json"); | |
const app = express(); | |
app.use(express.json()); | |
app.use(cors()); | |
const app_id = config.APP_ID; | |
const app_secret = config.APP_SECRET; | |
const api_version = "v1.1"; | |
const me_endpoint_base_url = `https://graph.accountkit.com/${api_version}/me`; | |
const token_exchange_base_url = `https://graph.accountkit.com/${api_version}/access_token`; | |
app.post("/token", async (req, res) => { | |
console.log(req.body); | |
try { | |
const app_access_token = ["AA", app_id, app_secret].join("|"); | |
const params = { | |
grant_type: "authorization_code", | |
code: req.body.code, | |
access_token: app_access_token | |
}; | |
const token_exchange_url = `${token_exchange_base_url}?${querystring.stringify( | |
params | |
)}`; | |
const { data } = await axios.get(token_exchange_url); | |
const me_endpoint_url = `${me_endpoint_base_url}?access_token=${ | |
data.access_token | |
}`; | |
const me_res = await axios.get(me_endpoint_url); | |
console.log(me_res.data); | |
// create jwt token for internal api auth | |
const jwt_token = jwt.sign(me_res.data, config.JWT_SECRET); | |
res.json({ ...me_res.data, jwt_token }); | |
} catch (err) { | |
res.status(400).end(); | |
} | |
}); | |
app.get('/protected', jwt_middleware({ secret: config.JWT_SECRET }), (req, res) => { | |
res.json({ | |
status: 'Hello World!', | |
your_id: req.user.id, | |
}); | |
}); | |
app.listen(3001, () => console.log("API Server on port 3001")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment