Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var mongoose = require('mongoose');
- var crypto = require('crypto');
- var jwt = require('jsonwebtoken');
- var UserSchema = new mongoose.Schema({
- username:{type:String, lowercase:true, unique:true},
- hash: String,
- salt: String
- });
- UserSchema.methods.setPassword = function(password){
- this.salt = crypto.randomBytes(16).toString('hex');
- this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
- };
- UserSchema.methods.validPassword = function(password){
- var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
- return this.hash === hash;
- };
- UserSchema.methods.generateJWT = function(){
- //set expiration to 60 days
- var today = new Date();
- var exp = new Date(today);
- exp.setDate(today.getDate() + 60);
- return jwt.sign({
- _id: this._id,
- username: this.username,
- exp: parseInt(exp.getTime() / 1000),
- }, 'SECRET');
- };
- mongoose.model('User', UserSchema);
- var express = require('express');
- var router = express.Router();
- var mongoose = require('mongoose');
- mongoose.Promise = global.Promise;
- var passport = require('passport');
- var jwt = require('express-jwt');
- var Post = mongoose.model('Post');
- var Comment = mongoose.model('Comment')
- var User = mongoose.model('User');
- //I KNOW TO CHANGE TO ENV VARIABLE BEFORE PRODUCTION
- var auth = jwt({secret: 'SECRET', userProperty: 'payload'});
- router.param('post', function(req, res, next, id){
- var query = Post.findById(id);
- query.exec(function(err, post){
- if(err){return next(err);}
- if(!post){return next(new Error('can't find post'));}
- req.post = post;
- next();
- });
- });
- router.param('comment', function(req, res, next, id){
- var query = Comment.findById(id);
- query.exec(function(err, comment){
- if(err){return next(err);}
- if(!comment){return next(new Error('can't find comment'));}
- req.comment = comment;
- next();
- })
- })
- //EDITED OUT ALL ROUTES THAT DID NOT USE AUTH TO SAVE SPACE
- //save a post to the posts collections
- router.post('/posts', auth, function(req, res, next){
- var post = new Post(req.body);
- post.author = req.payload.username;
- post.save(function(err,post){
- if(err){return next(err);}
- res.json(post);
- });
- });
- //Add an upvote to a post
- router.put('/posts/:post/upvote', auth, function(req, res, next){
- req.post.upvote(function(err, post){
- if(err){return next(err)};
- res.json(post);
- });
- });
- //post comments to a post
- router.post('/posts/:post/comments', auth, function(req, res, next){
- var comment = new Comment(req.body);
- comment.post = req.post;
- comment.author = req.payload.username;
- comment.save(function(err, comment){
- if(err){return next(err);}
- req.post.comments.push(comment);
- req.post.save(function(err, post){
- if(err){return next(err);}
- res.json(comment);
- });
- });
- });
- //Add an upvote to comment
- router.put('/posts/:post/comments/:comment/upvote', auth, function(req, res, next){
- req.comment.upvote(function(err, comment){
- if(err){return next(err);}
- res.json(comment);
- });
- });
- router.post('/register', function(req, res, next){
- if(!req.body.username || !req.body.password){
- return res.status(400).json({message: 'Please fill out all fields'});
- }
- var user = new User();
- user.username = req.body.username;
- user.setPassword(req.body.password);
- user.save(function(err){
- if(err){return next(err);}
- return res.json({token: user.generateJWT()})
- });
- });
- router.post('/login', function(req, res, next){
- if(!req.body.username || !req.body.password){
- return res.status(400).json({message: 'Please fill out all fields'});
- }
- passport.authenticate('local', function(err, user, info){
- if(err){return next(err);}
- if(user){
- return res.json({token:user.generateJWT()});
- }else{
- return res.status(401).json(info);
- }
- })(req, res, next);
- });
- module.exports = router;
- var app = angular.module('rawle_news_app', ['ui.router'])
- app.controller('MainCtrl', ['$scope', 'posts', 'auth', function($scope, posts, auth){
- $scope.test = 'Hello world!';
- $scope.posts = posts.posts;
- $scope.addPost = function(){
- if(!$scope.title || $scope.title === '') { return; }
- posts.create({
- title: $scope.title,
- link: $scope.link
- });
- $scope.title='';
- $scope.link='';
- }
- $scope.incrementUpvotes = function(post) {
- posts.upvote(post)
- };
- $scope.isLoggedIn = auth.isLoggedIn;
- }]);
- app.controller('PostsCtrl', ['$scope','posts', 'post', 'auth', function($scope, posts, post, auth){
- $scope.post = post;
- $scope.addComment = function(){
- if($scope.body === ''){return ;}
- posts.addComment(post._id,{
- body:$scope.body,
- author:'user',
- }).then(function(comment){
- $scope.post.comments.push(comment);
- });
- $scope.body='';
- };
- $scope.incrementUpvotes = function(comment) {
- posts.upvoteComment(post, comment);
- };
- $scope.isLoggedIn = auth.isLoggedIn;
- }])
- app.controller('AuthCtrl', ['$scope', '$state', 'auth', function($scope, $state, auth){
- $scope.user = {};
- $scope.register = function(){
- auth.register($scope.user).error(function(error){
- $scope.error = error;
- }).then(function(){
- $state.go('home');
- });
- };
- $scope.logIn = function(){
- auth.logIn($scope.user).error(function(error){
- $scope.error = error;
- }).then(function(){
- $state.go('home');
- });
- };
- }])
- app.controller('NavCtrl', ['$scope','auth', function($scope, auth){
- $scope.isLoggedIn = auth.isLoggedIn;
- $scope.currentUser = auth.currentUser;
- $scope.logOut = auth.logOut;
- }]);
- app.factory('posts', ['$http', 'auth', function($http, auth){
- var o = {
- posts:[]
- }
- o.get = function(id){
- return $http.get('/posts/' + id).then(function(res){
- return res.data;
- });
- };
- o.getAll = function() {
- return $http.get('/posts').then(function(data){
- angular.copy(data.data, o.posts);
- });
- };
- o.create = function(post) {
- return $http.post('/posts', post, {
- headers: {Authorization: 'Bearer '+auth.getToken()}
- }).then(function(response){
- o.posts.push(response.data);
- return response.data;
- });
- };
- o.upvote = function(post){
- return $http.put('/posts/'+ post._id + '/upvote', null, {
- headers: {Authorization: 'Bearer '+auth.getToken()}
- }).then(function(data){
- post.upvotes +=1;
- });
- }
- o.addComment = function(id, comment){
- return $http.post('/posts/' + id + '/comments', comment, {
- headers: {Authorization: 'Bearer '+auth.getToken()}
- }).then(function(response){
- return response.data;
- });
- };
- o.upvoteComment = function(post, comment){
- return $http.put('/posts/' + post._id + '/comments/' + comment._id + '/upvote', null, {
- headers: {Authorization: 'Bearer '+auth.getToken()}
- })
- .then(function(data){
- comment.upvotes += 1;
- });
- };
- return o;
- }])
- app.factory('auth', ['$http', '$window', function($http, $window){
- var auth = {};
- auth.saveToken = function(token){
- $window.localStorage['rawle_news_app'] = token;
- };
- auth.getToken = function(){
- return $window.localStorage['rawle_news_app'];
- }
- auth.isLoggedIn = function(){
- var token = auth.getToken();
- if(token){
- var payload = JSON.parse($window.atob(token.split('.')[1]));
- return payload.exp > Date.now() / 1000;
- }else{
- return false;
- }
- };
- auth.currentUser = function(){
- if(auth.isLoggedIn()){
- var token = auth.getToken();
- var payload = JSON.parse($window.atob(token.split('.')[1]));
- return payload.username;
- }
- };
- auth.register = function(user){
- return $http.post('/register', user).then(function(data){
- auth.saveToken(data.token);
- });
- };
- auth.logIn = function(user){
- return $http.post('/login', user).then(function(data){
- auth.saveToken(data.token);
- });
- };
- auth.logOut = function(){
- $window.localStorage.removeItem('rawle_news_app');
- };
- return auth;
- }])
- app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
- $stateProvider
- .state('home', {
- url:'/home',
- templateUrl:'/home.html',
- controller:'MainCtrl',
- resolve:{
- postPromise:['posts', function(posts){
- return posts.getAll();
- }]
- }
- })
- .state('posts', {
- url:'/posts/{id}',
- templateUrl:'/posts.html',
- controller:'PostsCtrl',
- resolve:{
- post:['$stateParams', 'posts', function($stateParams, posts){
- return posts.get($stateParams.id);
- }]
- }
- })
- .state('login', {
- url: '/login',
- templateUrl: '/login.html',
- controller: 'AuthCtrl',
- onEnter: ['$state', 'auth', function($state, auth){
- if(auth.isLoggedIn()){
- $state.go('home');
- }
- }]
- })
- .state('register', {
- url: '/register',
- templateUrl: '/register.html',
- controller: 'AuthCtrl',
- onEnter: ['$state', 'auth', function($state, auth){
- if(auth.isLoggedIn()){
- $state.go('home');
- }
- }]
- });
- $urlRouterProvider.otherwise('home');
- }])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement