Wednesday 17 May 2017

MEAN Stack Tutorial Help, Adding User Profile Functionality

I'm completing this tutorial https://thinkster.io/mean-stack-tutorial/ and have made a few changes in order to create more of a blog site. The only thing I need now is to be able to do now is add functionality so that when a user's name is clicked (the name next to a post comment), their profile page is shown along with each of their blog titles on the /profiles:username page. Can someone guide me as to how to complete this? Here is what I have so far:

index.ejs:

    <html>
<head>
  <title>BlogIt!</title>


  <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.2/angular-ui-router.js"></script>

  <script src="/javascripts/angularApp.js"></script>


</head>
<body ng-app="flapperNews">
  <nav class="navbar navbar-default pull-right" ng-controller="NavCtrl">
    <ul class="nav navbar-nav">
      <li ng-show="isLoggedIn()"><a href="/">Home</a></li>
      <li ng-show="isLoggedIn()"><a href="#/account"></a></li>
      <li ng-show="isLoggedIn()"><a ng-click="logOut()">Log Out</a></li>
      <li ng-hide="isLoggedIn()"><a href="/#/login">Log In</a></li>
      <li ng-hide="isLoggedIn()"><a href="/#/register">Register</a></li>
      <li></li>
    </ul>
  </nav>
  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      <ui-view></ui-view>
    </div>
  </div>

  <script type="text/ng-template" id="/home.html">
    <div class="page-header">
      <h1>BlogIt!</h1>
    </div>

    <div ng-repeat="post in posts | orderBy:'-upvotes'">
      <span class="glyphicon glyphicon-thumbs-up"
        ng-click="incrementUpvotes(post)"></span>
      
      <span style="font-size:20px; margin-left:10px;">
        <a ng-show="post.link" href="#/posts/">
          
        </a>
        <span ng-hide="post.link">
          
        </span>
      </span>
      <span ng-show="post.author">
        posted by  |
      </span>
      <span>
         Comments
      </span>
    </div>

    <form ng-submit="addPost()"
      style="margin-top:30px;" ng-show="isLoggedIn()">
      <h3>Add a new post</h3>

      <div class="form-group">
        <input type="text"
        class="form-control"
        placeholder="Title"
        ng-model="title"></input>
      </div>
      <div class="form-group">
        <input type="textarea" class="form-control" placeholder="Write your blog here..." ng-model="text" style="height: 500px;"/>
      </div>
      <button type="submit" class="btn btn-primary">Post</button>
    </form>

    <div ng-hide="isLoggedIn()">
      <h3>You need to <a href="/#/login">Log In</a> or <a href="/#/register">Register</a> before you can add a post.</h3>
    </div>
  </script>

  <script type="text/ng-template" id="/profiles.html">
    <div class="page-header">
      <h3>
        's Profile:
      </h3>
      Total Blogs:
    </div>
  </script>

  <script type="text/ng-template" id="/account.html">
    <div class="page-header">
      <h3>
        My Account: 
      </h3>
      My Blogs:
    </div>
  </script>

  <script type="text/ng-template" id="/posts.html">
    <div class="page-header">
      <h3>
        <a ng-show="post.link" href="#/posts/">
          
        </a>
        <span ng-hide="post.link">
          
        </span>
      </h3>
      
    </div>

    <div ng-repeat="comment in post.comments | orderBy:'-upvotes'">
      <span class="glyphicon glyphicon-thumbs-up"
        ng-click="incrementUpvotes(comment)"></span>
       - by <a href="#/profiles/"></a>
      <span style="font-size:20px; margin-left:10px;">
        
      </span>
    </div>
    <form ng-submit="addComment()"
      style="margin-top:30px;" ng-show="isLoggedIn()">
      <h3>Add a new comment</h3>

      <div class="form-group">
        <input type="text"
        class="form-control"
        placeholder="Comment"
        ng-model="body"></input>
      </div>
      <button type="submit" class="btn btn-primary">Post</button>
    </form>

    <div ng-hide="isLoggedIn()">
      <h3>You need to <a href="/#/login">Log In</a> or <a href="/#/register">Register</a> before you can comment.</h3>
    </div>
  </script>

  <script type="text/ng-template" id="/login.html">
    <div class="page-header">
      <h1>BlogIt!</h1>
    </div>

    <div ng-show="error" class="alert alert-danger row">
      <span></span>
    </div>

    <form ng-submit="logIn()"
      style="margin-top:30px;">
      <h3>Log In</h3>

      <div class="form-group">
        <input type="text"
        class="form-control"
        placeholder="Username"
        ng-model="user.username"></input>
      </div>
      <div class="form-group">
        <input type="password"
        class="form-control"
        placeholder="Password"
        ng-model="user.password"></input>
      </div>
      <button type="submit" class="btn btn-primary">Log In</button>
    </form>
  </script>

  <script type="text/ng-template" id="/register.html">
    <div class="page-header">
      <h1>BlogIt!</h1>
    </div>

    <div ng-show="error" class="alert alert-danger row">
      <span></span>
    </div>

    <form ng-submit="register()"
      style="margin-top:30px;">
      <h3>Register</h3>

      <div class="form-group">
        <input type="text"
        class="form-control"
        placeholder="Username"
        ng-model="user.username"></input>
      </div>
      <div class="form-group">
        <input type="password"
        class="form-control"
        placeholder="Password"
        ng-model="user.password"></input>
      </div>
      <button type="submit" class="btn btn-primary">Register</button>
    </form>
  </script>
</body>
    </html>

angularApp.js:

angular.module('flapperNews', ['ui.router'])
.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('profiles', {
      url: '/profiles/{username}',
      templateUrl: '/profiles.html',
      controller: 'ProfilesCtrl'
    })
    .state('account', {
      url: '/account',
      templateUrl: '/account.html',
      controller: 'AcctCtrl'
    })
    .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');
}])
.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').success(function(data){
      angular.copy(data, o.posts);
    });
  };

  o.create = function(post) {
    return $http.post('/posts', post, {
      headers: {Authorization: 'Bearer '+auth.getToken()}
    }).success(function(data){
      o.posts.push(data);
    });
  };

  o.upvote = function(post) {
    return $http.put('/posts/' + post._id + '/upvote', null, {
      headers: {Authorization: 'Bearer '+auth.getToken()}
    }).success(function(data){
      post.upvotes += 1;
    });
  };

  o.addComment = function(id, comment) {
    return $http.post('/posts/' + id + '/comments', comment, {
      headers: {Authorization: 'Bearer '+auth.getToken()}
    });
  };

  o.upvoteComment = function(post, comment) {
    return $http.put('/posts/' + post._id + '/comments/'+ comment._id + '/upvote', {
      headers: {Authorization: 'Bearer '+auth.getToken()}
    }).success(function(data){
      comment.upvotes += 1;
    });
  };

  return o;
}])
.factory('auth', ['$http', '$window', '$rootScope', function($http, $window, $rootScope){
   var auth = {
    saveToken: function (token){
      $window.localStorage['flapper-news-token'] = token;
    },
    getToken: function (){
      return $window.localStorage['flapper-news-token'];
    },
    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;
      }
    },
    currentUser: function(){
      if(auth.isLoggedIn()){
        var token = auth.getToken();
        var payload = JSON.parse($window.atob(token.split('.')[1]));

        return payload.username;
      }
    },
    register: function(user){
      return $http.post('/register', user).success(function(data){
        auth.saveToken(data.token);
      });
    },
    logIn: function(user){
      return $http.post('/login', user).success(function(data){
        auth.saveToken(data.token);
      });
    },
    logOut: function(){
      $window.localStorage.removeItem('flapper-news-token');
      $window.location = '/';
    }
  };

  return auth;
}])
.controller('MainCtrl', [
'$scope',
'posts',
'auth',
function($scope, posts, auth){
  $scope.test = 'Hello world!';

  $scope.posts = posts.posts;
  $scope.isLoggedIn = auth.isLoggedIn;

  $scope.addPost = function(){
    if($scope.title === '') { return; }
    posts.create({
      title: $scope.title,
      link: $scope.title,
      text: $scope.text
    });
    $scope.title = '';
    $scope.link = '';
    $scope.text = '';
  };

  $scope.incrementUpvotes = function(post) {
    posts.upvote(post);
  };

}])
.controller('ProfilesCtrl', [
  '$scope',
  'posts',
  'auth',
  'username',
  function($scope, posts, auth, username){
    $scope.posts = posts.posts;
    $scope.isLoggedIn = auth.isLoggedIn;
    $scope.auth = auth;
    $scope.username = username;
}])
.controller('AcctCtrl', [
  '$scope',
  'posts',
  'auth',
  function($scope, posts, auth){
    $scope.posts = posts.posts;
    $scope.isLoggedIn = auth.isLoggedIn;
    $scope.auth = auth;
  }
])
.controller('PostsCtrl', [
'$scope',
'posts',
'post',
'auth',
function($scope, posts, post, auth){
  $scope.post = post;
  $scope.isLoggedIn = auth.isLoggedIn;

  $scope.addComment = function(){
    if($scope.body === '') { return; }
    posts.addComment(post._id, {
      body: $scope.body,
      author: 'user',
    }).success(function(comment) {
      $scope.post.comments.push(comment);
    });
    $scope.body = '';
  };

  $scope.incrementUpvotes = function(comment){
    posts.upvoteComment(post, comment);
  };
}])
.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');
    });
  };
}])
.controller('NavCtrl', [
'$scope',
'auth',
function($scope, auth){
  $scope.isLoggedIn = auth.isLoggedIn;
  $scope.currentUser = auth.currentUser;
  $scope.logOut = auth.logOut;
}]);

routes/index.js:

    var express = require('express');
var router = express.Router();
var jwt = require('express-jwt');
var passport = require('passport');

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});


var mongoose = require('mongoose');
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
var User = mongoose.model('User');

var auth = jwt({secret: 'SECRET', userProperty: 'payload'});

router.get('/posts', function(req, res, next) {
  Post.find(function(err, posts){
    if(err){ return next(err); }

    res.json(posts);
  });
});

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);
  });
});


// Preload post objects on routes with ':post'
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;
    return next();
  });
});

// Preload comment objects on routes with ':comment'
router.param('comment', function(req, res, next, id) {
  var query = Comment.findById(req.params.id);
  console.log(query);

  query.exec(function (err, comment){
    if (err) { return next(err); }
    if (!comment) { return next(new Error("can't find comment")); }

    req.comment = comment;
    return next();
  });
});


// return a post
router.get('/posts/:post', function(req, res, next) {
  req.post.populate('comments', function(err, post) {
    res.json(post);
  });
});

// return a user's profile
router.get('/profiles/:username', function(req, res, next, username)  {
  req.username = username;
});

//return user's account
router.get('/account', function(req, res, next) {

});


// upvote 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);
  });
});


// create a new comment
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);
    });
  });
});


// upvote a comment
router.put('/posts/:post/comments/:comment/upvote', auth, function(req, res, next) {
  req.comment.upvote(function(err, comment){
    if (err) {
      console.log(err);
      return next(err); }

    res.json(comment);
  });
});


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);
});

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()})
  });
});

module.exports = router;



via Eric Johnson

No comments:

Post a Comment