Advertisement
Guest User

Untitled

a guest
Sep 19th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.15 KB | None | 0 0
  1. // ------------------------------------------------------
  2. // server.js
  3.  
  4. // .......................................................
  5. // requires
  6. var fs = require('fs');
  7. var express = require('express');
  8. var myBusinessLogic = require('../businessLogic/businessLogic.js');
  9.  
  10. // .......................................................
  11. // security options
  12.  
  13. /*
  14. 1. Generate a self-signed certificate-key pair
  15. openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out certificate.pem
  16.  
  17. 2. Import them to a keystore (some programs use a keystore)
  18. keytool -importcert -file certificate.pem -keystore my.keystore
  19. */
  20.  
  21. var securityOptions = {
  22. key: fs.readFileSync('key.pem'),
  23. cert: fs.readFileSync('certificate.pem'),
  24. requestCert: true
  25. };
  26.  
  27. // .......................................................
  28. // create the secure server (HTTPS)
  29.  
  30. var app = express();
  31. var secureServer = require('https').createServer(securityOptions, app);
  32.  
  33. // ------------------------------------------------------
  34. // helper functions for auth
  35.  
  36. // .............................................
  37. // true if req == GET /login
  38.  
  39. function isGETLogin (req) {
  40. if (req.path != "/login") { return false; }
  41. if ( req.method != "GET" ) { return false; }
  42. return true;
  43. } // ()
  44.  
  45. // .............................................
  46. // your auth policy here:
  47. // true if req does have permissions
  48. // (you may check here permissions and roles
  49. // allowed to access the REST action depending
  50. // on the URI being accessed)
  51.  
  52. function reqHasPermission (req) {
  53. // decode req.accessToken, extract
  54. // supposed fields there: userId:roleId:expiryTime
  55. // and check them
  56.  
  57. // for the moment we do a very rigorous check
  58. if (req.headers.accessToken != "you-are-welcome") {
  59. return false;
  60. }
  61. return true;
  62. } // ()
  63.  
  64. // ------------------------------------------------------
  65. // install a function to transparently perform the auth check
  66. // of incoming request, BEFORE they are actually invoked
  67.  
  68. app.use (function(req, res, next) {
  69. if (! isGETLogin (req) ) {
  70. if (! reqHasPermission (req) ){
  71. res.writeHead(401); // unauthorized
  72. res.end();
  73. return; // don't call next()
  74. }
  75. } else {
  76. console.log (" * is a login request ");
  77. }
  78. next(); // continue processing the request
  79. });
  80.  
  81. // ------------------------------------------------------
  82. // copy everything in the req body to req.body
  83.  
  84. app.use (function(req, res, next) {
  85. var data='';
  86. req.setEncoding('utf8');
  87. req.on('data', function(chunk) {
  88. data += chunk;
  89. });
  90. req.on('end', function() {
  91. req.body = data;
  92. next();
  93. });
  94. });
  95.  
  96. // ------------------------------------------------------
  97. // REST requests
  98. // ------------------------------------------------------
  99.  
  100. // .......................................................
  101. // authenticating method
  102. // GET /login?user=xxx&password=yyy
  103.  
  104. app.get('/login', function(req, res){
  105. var user = req.query.user;
  106. var password = req.query.password;
  107.  
  108. // rigorous auth check of user-passwrod
  109. if (user != "foobar" || password != "1234") {
  110. res.writeHead(403); // forbidden
  111. } else {
  112. // OK: create an access token with fields user, role and expiry time, hash it
  113. // and put it on a response header field
  114. res.setHeader ('accessToken', "you-are-welcome");
  115. res.writeHead(200);
  116. }
  117. res.end();
  118. });
  119.  
  120. // .......................................................
  121. // "regular" methods (just an example)
  122. // newBook()
  123. // PUT /book
  124.  
  125. app.put('/book', function (req,res){
  126. var bookData = JSON.parse (req.body);
  127.  
  128. myBusinessLogic.newBook(bookData, function (err) {
  129. if (err) {
  130. res.writeHead(409);
  131. res.end();
  132. return;
  133. }
  134. // no error:
  135. res.writeHead(200);
  136. res.end();
  137. });
  138. });
  139.  
  140. // .......................................................
  141. // "main()"
  142.  
  143. secureServer.listen (8081);
  144.  
  145. echo "---- first: do login "
  146. curl -v "https://localhost:8081/login?user=foobar&password=1234" --cacert certificate.pem
  147.  
  148. # now, in a real case, you should copy the accessToken received before, in the following request
  149.  
  150. echo "---- new book"
  151. curl -X POST -d '{"id": "12341324", "author": "Herman Melville", "title": "Moby-Dick"}' "https://localhost:8081/book" --cacert certificate.pem --header "accessToken: you-are-welcome"
  152.  
  153. -require/import modules & files into the system (comment out db & router until those files are filled in)
  154. const db = require('../db/conf');
  155. const router = require('./router/whateverRouter');
  156. const express = require('express');
  157. const bodyParser = require('body-parser');
  158. -define port & ip
  159. const port = 3000;
  160. const ip = 'localhost';
  161. -create an instance of express server
  162. -const app = express();
  163. -list out what the app will use
  164. .use(express.static('whatever frontend client folder'))
  165. .use(bodyParser.json())
  166. .use(bodyParser.urlencoded({extended: true}))
  167. .use('/api', router)
  168. -listen for server
  169. app.listen(port, ip, () => {
  170. console.log("server started");
  171. });
  172. -test to see if server can start up ($ npm start)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement