Advertisement
Guest User

Untitled

a guest
Jan 25th, 2017
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.99 KB | None | 0 0
  1. var mongoose = require('mongoose');
  2. var crypto = require('crypto');
  3. var jwt = require('jsonwebtoken');
  4.  
  5. var UserSchema = new mongoose.Schema({
  6. username:{type:String, lowercase:true, unique:true},
  7. hash: String,
  8. salt: String
  9. });
  10.  
  11. UserSchema.methods.setPassword = function(password){
  12. this.salt = crypto.randomBytes(16).toString('hex');
  13.  
  14. this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
  15. };
  16.  
  17. UserSchema.methods.validPassword = function(password){
  18. var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
  19.  
  20. return this.hash === hash;
  21. };
  22.  
  23. UserSchema.methods.generateJWT = function(){
  24. //set expiration to 60 days
  25. var today = new Date();
  26. var exp = new Date(today);
  27. exp.setDate(today.getDate() + 60);
  28.  
  29. return jwt.sign({
  30. _id: this._id,
  31. username: this.username,
  32. exp: parseInt(exp.getTime() / 1000),
  33. }, 'SECRET');
  34. };
  35.  
  36. mongoose.model('User', UserSchema);
  37.  
  38. var express = require('express');
  39. var router = express.Router();
  40. var mongoose = require('mongoose');
  41. mongoose.Promise = global.Promise;
  42. var passport = require('passport');
  43. var jwt = require('express-jwt');
  44. var Post = mongoose.model('Post');
  45. var Comment = mongoose.model('Comment')
  46. var User = mongoose.model('User');
  47.  
  48. //I KNOW TO CHANGE TO ENV VARIABLE BEFORE PRODUCTION
  49. var auth = jwt({secret: 'SECRET', userProperty: 'payload'});
  50.  
  51. router.param('post', function(req, res, next, id){
  52. var query = Post.findById(id);
  53.  
  54. query.exec(function(err, post){
  55. if(err){return next(err);}
  56. if(!post){return next(new Error('can't find post'));}
  57.  
  58. req.post = post;
  59. next();
  60. });
  61. });
  62.  
  63. router.param('comment', function(req, res, next, id){
  64. var query = Comment.findById(id);
  65.  
  66. query.exec(function(err, comment){
  67. if(err){return next(err);}
  68. if(!comment){return next(new Error('can't find comment'));}
  69.  
  70. req.comment = comment;
  71. next();
  72. })
  73. })
  74.  
  75. //EDITED OUT ALL ROUTES THAT DID NOT USE AUTH TO SAVE SPACE
  76.  
  77. //save a post to the posts collections
  78. router.post('/posts', auth, function(req, res, next){
  79. var post = new Post(req.body);
  80. post.author = req.payload.username;
  81.  
  82. post.save(function(err,post){
  83. if(err){return next(err);}
  84.  
  85. res.json(post);
  86. });
  87. });
  88.  
  89. //Add an upvote to a post
  90. router.put('/posts/:post/upvote', auth, function(req, res, next){
  91. req.post.upvote(function(err, post){
  92. if(err){return next(err)};
  93.  
  94. res.json(post);
  95. });
  96. });
  97.  
  98. //post comments to a post
  99. router.post('/posts/:post/comments', auth, function(req, res, next){
  100. var comment = new Comment(req.body);
  101. comment.post = req.post;
  102. comment.author = req.payload.username;
  103.  
  104. comment.save(function(err, comment){
  105. if(err){return next(err);}
  106.  
  107. req.post.comments.push(comment);
  108. req.post.save(function(err, post){
  109. if(err){return next(err);}
  110.  
  111. res.json(comment);
  112. });
  113. });
  114. });
  115.  
  116. //Add an upvote to comment
  117. router.put('/posts/:post/comments/:comment/upvote', auth, function(req, res, next){
  118. req.comment.upvote(function(err, comment){
  119. if(err){return next(err);}
  120.  
  121. res.json(comment);
  122. });
  123. });
  124.  
  125. router.post('/register', function(req, res, next){
  126. if(!req.body.username || !req.body.password){
  127. return res.status(400).json({message: 'Please fill out all fields'});
  128. }
  129.  
  130. var user = new User();
  131.  
  132. user.username = req.body.username;
  133. user.setPassword(req.body.password);
  134.  
  135. user.save(function(err){
  136. if(err){return next(err);}
  137.  
  138. return res.json({token: user.generateJWT()})
  139. });
  140. });
  141.  
  142. router.post('/login', function(req, res, next){
  143. if(!req.body.username || !req.body.password){
  144. return res.status(400).json({message: 'Please fill out all fields'});
  145. }
  146.  
  147. passport.authenticate('local', function(err, user, info){
  148. if(err){return next(err);}
  149.  
  150. if(user){
  151. return res.json({token:user.generateJWT()});
  152. }else{
  153. return res.status(401).json(info);
  154. }
  155. })(req, res, next);
  156. });
  157.  
  158. module.exports = router;
  159.  
  160. var app = angular.module('rawle_news_app', ['ui.router'])
  161.  
  162. app.controller('MainCtrl', ['$scope', 'posts', 'auth', function($scope, posts, auth){
  163. $scope.test = 'Hello world!';
  164.  
  165. $scope.posts = posts.posts;
  166.  
  167. $scope.addPost = function(){
  168. if(!$scope.title || $scope.title === '') { return; }
  169. posts.create({
  170. title: $scope.title,
  171. link: $scope.link
  172. });
  173. $scope.title='';
  174. $scope.link='';
  175. }
  176.  
  177. $scope.incrementUpvotes = function(post) {
  178. posts.upvote(post)
  179. };
  180.  
  181. $scope.isLoggedIn = auth.isLoggedIn;
  182. }]);
  183. app.controller('PostsCtrl', ['$scope','posts', 'post', 'auth', function($scope, posts, post, auth){
  184. $scope.post = post;
  185.  
  186. $scope.addComment = function(){
  187. if($scope.body === ''){return ;}
  188. posts.addComment(post._id,{
  189. body:$scope.body,
  190. author:'user',
  191. }).then(function(comment){
  192. $scope.post.comments.push(comment);
  193. });
  194. $scope.body='';
  195. };
  196.  
  197. $scope.incrementUpvotes = function(comment) {
  198. posts.upvoteComment(post, comment);
  199. };
  200.  
  201. $scope.isLoggedIn = auth.isLoggedIn;
  202. }])
  203.  
  204. app.controller('AuthCtrl', ['$scope', '$state', 'auth', function($scope, $state, auth){
  205. $scope.user = {};
  206.  
  207. $scope.register = function(){
  208. auth.register($scope.user).error(function(error){
  209. $scope.error = error;
  210. }).then(function(){
  211. $state.go('home');
  212. });
  213. };
  214.  
  215. $scope.logIn = function(){
  216. auth.logIn($scope.user).error(function(error){
  217. $scope.error = error;
  218. }).then(function(){
  219. $state.go('home');
  220. });
  221. };
  222. }])
  223.  
  224. app.controller('NavCtrl', ['$scope','auth', function($scope, auth){
  225. $scope.isLoggedIn = auth.isLoggedIn;
  226. $scope.currentUser = auth.currentUser;
  227. $scope.logOut = auth.logOut;
  228. }]);
  229.  
  230. app.factory('posts', ['$http', 'auth', function($http, auth){
  231. var o = {
  232. posts:[]
  233. }
  234.  
  235. o.get = function(id){
  236. return $http.get('/posts/' + id).then(function(res){
  237. return res.data;
  238. });
  239. };
  240.  
  241. o.getAll = function() {
  242. return $http.get('/posts').then(function(data){
  243. angular.copy(data.data, o.posts);
  244. });
  245. };
  246.  
  247. o.create = function(post) {
  248. return $http.post('/posts', post, {
  249. headers: {Authorization: 'Bearer '+auth.getToken()}
  250. }).then(function(response){
  251. o.posts.push(response.data);
  252. return response.data;
  253. });
  254. };
  255.  
  256. o.upvote = function(post){
  257. return $http.put('/posts/'+ post._id + '/upvote', null, {
  258. headers: {Authorization: 'Bearer '+auth.getToken()}
  259. }).then(function(data){
  260. post.upvotes +=1;
  261. });
  262. }
  263.  
  264. o.addComment = function(id, comment){
  265. return $http.post('/posts/' + id + '/comments', comment, {
  266. headers: {Authorization: 'Bearer '+auth.getToken()}
  267. }).then(function(response){
  268. return response.data;
  269. });
  270. };
  271.  
  272. o.upvoteComment = function(post, comment){
  273. return $http.put('/posts/' + post._id + '/comments/' + comment._id + '/upvote', null, {
  274. headers: {Authorization: 'Bearer '+auth.getToken()}
  275. })
  276. .then(function(data){
  277. comment.upvotes += 1;
  278. });
  279. };
  280.  
  281. return o;
  282.  
  283. }])
  284.  
  285. app.factory('auth', ['$http', '$window', function($http, $window){
  286. var auth = {};
  287.  
  288. auth.saveToken = function(token){
  289. $window.localStorage['rawle_news_app'] = token;
  290. };
  291.  
  292. auth.getToken = function(){
  293. return $window.localStorage['rawle_news_app'];
  294. }
  295.  
  296. auth.isLoggedIn = function(){
  297. var token = auth.getToken();
  298.  
  299. if(token){
  300. var payload = JSON.parse($window.atob(token.split('.')[1]));
  301.  
  302. return payload.exp > Date.now() / 1000;
  303. }else{
  304. return false;
  305. }
  306. };
  307.  
  308. auth.currentUser = function(){
  309. if(auth.isLoggedIn()){
  310. var token = auth.getToken();
  311. var payload = JSON.parse($window.atob(token.split('.')[1]));
  312.  
  313. return payload.username;
  314. }
  315. };
  316.  
  317. auth.register = function(user){
  318. return $http.post('/register', user).then(function(data){
  319. auth.saveToken(data.token);
  320. });
  321. };
  322.  
  323. auth.logIn = function(user){
  324. return $http.post('/login', user).then(function(data){
  325. auth.saveToken(data.token);
  326. });
  327. };
  328.  
  329. auth.logOut = function(){
  330. $window.localStorage.removeItem('rawle_news_app');
  331. };
  332.  
  333. return auth;
  334. }])
  335.  
  336. app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
  337. $stateProvider
  338. .state('home', {
  339. url:'/home',
  340. templateUrl:'/home.html',
  341. controller:'MainCtrl',
  342. resolve:{
  343. postPromise:['posts', function(posts){
  344. return posts.getAll();
  345. }]
  346. }
  347. })
  348. .state('posts', {
  349. url:'/posts/{id}',
  350. templateUrl:'/posts.html',
  351. controller:'PostsCtrl',
  352. resolve:{
  353. post:['$stateParams', 'posts', function($stateParams, posts){
  354. return posts.get($stateParams.id);
  355. }]
  356. }
  357. })
  358. .state('login', {
  359. url: '/login',
  360. templateUrl: '/login.html',
  361. controller: 'AuthCtrl',
  362. onEnter: ['$state', 'auth', function($state, auth){
  363. if(auth.isLoggedIn()){
  364. $state.go('home');
  365. }
  366. }]
  367. })
  368. .state('register', {
  369. url: '/register',
  370. templateUrl: '/register.html',
  371. controller: 'AuthCtrl',
  372. onEnter: ['$state', 'auth', function($state, auth){
  373. if(auth.isLoggedIn()){
  374. $state.go('home');
  375. }
  376. }]
  377. });
  378.  
  379. $urlRouterProvider.otherwise('home');
  380. }])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement