Initial commit
[yaffs-website] / node_modules / hawk / example / usage.js
1 // Load modules\r
2 \r
3 var Http = require('http');\r
4 var Request = require('request');\r
5 var Hawk = require('../lib');\r
6 \r
7 \r
8 // Declare internals\r
9 \r
10 var internals = {\r
11     credentials: {\r
12         dh37fgj492je: {\r
13             id: 'dh37fgj492je',                                             // Required by Hawk.client.header\r
14             key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',\r
15             algorithm: 'sha256',\r
16             user: 'Steve'\r
17         }\r
18     }\r
19 };\r
20 \r
21 \r
22 // Credentials lookup function\r
23 \r
24 var credentialsFunc = function (id, callback) {\r
25 \r
26     return callback(null, internals.credentials[id]);\r
27 };\r
28 \r
29 \r
30 // Create HTTP server\r
31 \r
32 var handler = function (req, res) {\r
33 \r
34     Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {\r
35 \r
36         var payload = (!err ? 'Hello ' + credentials.user + ' ' + artifacts.ext : 'Shoosh!');\r
37         var headers = {\r
38             'Content-Type': 'text/plain',\r
39             'Server-Authorization': Hawk.server.header(credentials, artifacts, { payload: payload, contentType: 'text/plain' })\r
40         };\r
41 \r
42         res.writeHead(!err ? 200 : 401, headers);\r
43         res.end(payload);\r
44     });\r
45 };\r
46 \r
47 Http.createServer(handler).listen(8000, '127.0.0.1');\r
48 \r
49 \r
50 // Send unauthenticated request\r
51 \r
52 Request('http://127.0.0.1:8000/resource/1?b=1&a=2', function (error, response, body) {\r
53 \r
54     console.log(response.statusCode + ': ' + body);\r
55 });\r
56 \r
57 \r
58 // Send authenticated request\r
59 \r
60 credentialsFunc('dh37fgj492je', function (err, credentials) {\r
61 \r
62     var header = Hawk.client.header('http://127.0.0.1:8000/resource/1?b=1&a=2', 'GET', { credentials: credentials, ext: 'and welcome!' });\r
63     var options = {\r
64         uri: 'http://127.0.0.1:8000/resource/1?b=1&a=2',\r
65         method: 'GET',\r
66         headers: {\r
67             authorization: header.field\r
68         }\r
69     };\r
70 \r
71     Request(options, function (error, response, body) {\r
72 \r
73         var isValid = Hawk.client.authenticate(response, credentials, header.artifacts, { payload: body });\r
74         console.log(response.statusCode + ': ' + body + (isValid ? ' (valid)' : ' (invalid)'));\r
75         process.exit(0);\r
76     });\r
77 });\r
78 \r