r-oauth2
Version:
A RethinkDB and Express implementation of OAuth2
55 lines (50 loc) • 1.59 kB
JavaScript
//Create database
require('rethink-config')({
"database": "oauth2",
"tables": ["users", "token"]
})
//Dependencies
var express = require('express');
var bodyParser = require('body-parser');
var oauth2 = require('../index');
//Initialize oauth2 module
oauth2.init();
app = express();
//Enable JSON to be parsed and passed in request.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
//Enable CORS - Note you need to add `authorization in the headers.`
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authorization");
res.header('Access-Control-Allow-Methods', 'POST, PATCH, GET, PUT, DELETE, OPTIONS');
next();
});
/*
Generate a Client ID and Client Secret
All that's required in the body is `grantType`.
*/
app.post('/client', oauth2.generateClient());
/*
Generate an access token and refresh token
All that's required in is the client object supplied by `/client`
*/
app.post('/oauth', oauth2.generateToken());
/*
Generate a new token exchanging the old one
All that's required is the `refreshToken parameter`
*/
app.post('/refresh', oauth2.refreshToken());
/*
To access a restricted area you must put in your header `Authorization: Bearer [Access Token]`
*/
app.get('/restricted', oauth2.authenticate(), function(req,res,next) {
res.send('Restricted area accessed.');
})
app.get('/', function(req,res,next) {
res.send('Open area.');
})
app.listen(9001);
console.log("Demo server running on port 9001")