Advertisement
Guest User

Untitled

a guest
Aug 10th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. var server=http.createServer(function(request, responsehttp) {
  2. if (request.method == 'POST') {
  3. var body = '';
  4. request.on('data', function (data) {
  5. body += data;
  6. });
  7. request.on('end', function () {
  8. var POST = qs.parse(body);
  9. processquery(POST, request, responsehttp);
  10. });
  11. } else {
  12. var url_parts = url.parse(request.url, true);
  13. var query = url_parts.query;
  14. console.log(query);
  15. processquery(query, request, responsehttp);
  16. }
  17. });
  18.  
  19. function processquery(query, request, responsehttp){
  20. var returnResult = function (data){
  21. responsehttp.end(JSON.stringify(data));
  22. };
  23.  
  24. if (!query.command) {
  25. fileprocess(request, responsehttp);
  26. }
  27. responsehttp.writeHead(200, {"Content-Type": "application/json"});
  28. switch(query.command) {
  29. case 'logout':
  30. logout(query, returnResult);
  31. break;
  32. case 'login':
  33. login(query, returnResult);
  34. break;
  35. }
  36. }
  37.  
  38. function login(request, callback) {
  39. if(request.username==users[request.username] && request.password==users[request.username].password) {
  40. users[request.username].auth=true;
  41. var data = {result:'success','message':'login successful'};
  42. callback(data);
  43. } else {
  44. var data = {result:'error','message':'login incorrect'};
  45. callback(data);
  46. }
  47. }
  48.  
  49. function checkAuth(req, res, next) {
  50. if (!req.session.user_id) {
  51. res.send('You are not authorized to view this page');
  52. } else {
  53. next();
  54. }
  55. }
  56.  
  57. app.get('/my_secret_page', checkAuth, function (req, res) {
  58. res.send('if you are viewing this page it means you are logged in');
  59. });
  60.  
  61. app.post('/login', function (req, res) {
  62. var post = req.body;
  63. if (post.user === 'john' && post.password === 'johnspassword') {
  64. req.session.user_id = johns_user_id_here;
  65. res.redirect('/my_secret_page');
  66. } else {
  67. res.send('Bad user/pass');
  68. }
  69. });
  70.  
  71. app.get('/logout', function (req, res) {
  72. delete req.session.user_id;
  73. res.redirect('/login');
  74. });
  75.  
  76. function checkAuth(req, res, next) {
  77. // if logined or it's login request, then go next route
  78. if (isLogin || (req.path === '/login' && req.method === 'POST')) {
  79. next()
  80. } else {
  81. res.send('Not logged in yet.')
  82. }
  83. }
  84.  
  85. app.use('/', checkAuth)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement