react / wstein / node_modules / jest-cli / node_modules / jsdom / node_modules / request / node_modules / hawk / example / usage.js
81146 views// Load modules12var Http = require('http');3var Request = require('request');4var Hawk = require('../lib');567// Declare internals89var internals = {10credentials: {11dh37fgj492je: {12id: 'dh37fgj492je', // Required by Hawk.client.header13key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',14algorithm: 'sha256',15user: 'Steve'16}17}18};192021// Credentials lookup function2223var credentialsFunc = function (id, callback) {2425return callback(null, internals.credentials[id]);26};272829// Create HTTP server3031var handler = function (req, res) {3233Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {3435var payload = (!err ? 'Hello ' + credentials.user + ' ' + artifacts.ext : 'Shoosh!');36var headers = {37'Content-Type': 'text/plain',38'Server-Authorization': Hawk.server.header(credentials, artifacts, { payload: payload, contentType: 'text/plain' })39};4041res.writeHead(!err ? 200 : 401, headers);42res.end(payload);43});44};4546Http.createServer(handler).listen(8000, '127.0.0.1');474849// Send unauthenticated request5051Request('http://127.0.0.1:8000/resource/1?b=1&a=2', function (error, response, body) {5253console.log(response.statusCode + ': ' + body);54});555657// Send authenticated request5859credentialsFunc('dh37fgj492je', function (err, credentials) {6061var header = Hawk.client.header('http://127.0.0.1:8000/resource/1?b=1&a=2', 'GET', { credentials: credentials, ext: 'and welcome!' });62var options = {63uri: 'http://127.0.0.1:8000/resource/1?b=1&a=2',64method: 'GET',65headers: {66authorization: header.field67}68};6970Request(options, function (error, response, body) {7172var isValid = Hawk.client.authenticate(response, credentials, header.artifacts, { payload: body });73console.log(response.statusCode + ': ' + body + (isValid ? ' (valid)' : ' (invalid)'));74process.exit(0);75});76});77787980