Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add access control for posts #23

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion api/config/mongo_database.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ var mongodbURL = 'mongodb://localhost/blog';
var mongodbOptions = { };

mongoose.connect(mongodbURL, mongodbOptions, function (err, res) {
if (err) {
if (err) {
console.log('Connection refused to ' + mongodbURL);
console.log(err);
} else {
Expand All @@ -24,6 +24,7 @@ var User = new Schema({
});

var Post = new Schema({
uid: { type: String, required: true },
title: { type: String, required: true },
tags: [ {type: String} ],
is_published: { type: Boolean, default: false },
Expand Down
164 changes: 107 additions & 57 deletions api/route/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,26 @@ exports.list = function(req, res) {

exports.listAll = function(req, res) {
if (!req.user) {
return res.send(401);
res.header('Location', '/#/admin/login');
return res.send(301);
}

var query = db.postModel.find();
query.sort('-created');
query.exec(function(err, results) {
if (err) {
console.log(err);
return res.send(400);
}

for (var postKey in results) {
results[postKey].content = results[postKey].content.substr(0, 400);
}

return res.json(200, results);
db.userModel.findById(req.user.id, function (err, user) {
if (err || !user) {
console.log(err ? err : 'Bad user id: ' + post._id);
return res.send(400, err ? err.message : 'User not found.');
}
var q = user.is_admin ? {} : {uid: req.user.id},
query = db.postModel.find(q, {tags: 0, content: 0});
query.sort('-created');
query.exec(function(err, results) {
if (err) {
console.log(err);
return res.send(400, err.message);
}

return res.json(200, results);
});
});
};

Expand Down Expand Up @@ -97,52 +101,60 @@ exports.unlike = function(req, res) {
}

return res.send(200);
});
});
}

exports.create = function(req, res) {
if (!req.user) {
return res.send(401);
res.header('Location', '/#/admin/login');
return res.send(301);
}

var post = req.body.post;
if (post == null || post.title == null || post.content == null
if (post == null || post.title == null || post.content == null
|| post.tags == null) {
return res.send(400);
return res.send(400, 'Post is not complete.');
}

var postEntry = new db.postModel();
postEntry.title = post.title;
postEntry.tags = post.tags.split(',');
postEntry.is_published = post.is_published;
postEntry.content = post.content;

postEntry.save(function(err) {
if (err) {
console.log(err);
return res.send(400);
db.userModel.findById(req.user.id, function (err, user) {
if (err || !user) {
console.log(err ? err : 'Bad user id: ' + post._id);
return res.send(400, err ? err.message : 'User not found.');
}

return res.send(200);
});
}
var postEntry = new db.postModel();
postEntry.uid = req.user.id;
postEntry.title = post.title;
postEntry.tags = post.tags.split(',');
postEntry.is_published = post.is_published;
postEntry.content = post.content;

exports.update = function(req, res) {
if (!req.user) {
return res.send(401);
}
postEntry.save(function(err) {
if (err) {
console.log(err);
return res.send(400);
}

var post = req.body.post;
return res.send(200);
});
});
}

/**
Update post actually
@param {Object} post - req.body.post
@param {Function} callback - callback(statusCode, message)
*/
var _update = function(post, callback) {
if (post == null || post._id == null) {
res.send(400);
return callback(400, 'Post not found.');
}

var updatePost = {};

if (post.title != null && post.title != "") {
if (post.title != null && post.title !== "") {
updatePost.title = post.title;
}
}

if (post.tags != null) {
if (Object.prototype.toString.call(post.tags) === '[object Array]') {
Expand All @@ -157,43 +169,81 @@ exports.update = function(req, res) {
updatePost.is_published = post.is_published;
}

if (post.content != null && post.content != "") {
if (post.content != null && post.content !== "") {
updatePost.content = post.content;
}

updatePost.updated = new Date();

db.postModel.update({_id: post._id}, updatePost, function(err, nbRows, raw) {
return res.send(200);
if (err) {
console.log(err);
return callback(400, err.message);
}
return callback(200, '');
});
};

exports.update = function(req, res) {
if (!req.user) {
res.header('Location', '/#/admin/login');
return res.send(301);
}

db.userModel.findById(req.user.id, function (err, user) {
if (err || !user) {
console.log(err ? err : 'Bad user id: ' + post._id);
return res.send(400, err ? err.message : 'User not found.');
}

var post = req.body.post;
db.postModel.findById(post._id, function (err, result) {
if (err || !result) {
console.log(err ? err : 'Bad post id: ' + post._id);
return res.send(400, err ? err.message : 'Post not found.');
}
if (result.uid !== req.user.id) {
return res.send(400, 'Only the author can update.');
}
_update(post, function (code, message) {
return res.send(code, message);
});
});
});
};

exports.delete = function(req, res) {
if (!req.user) {
return res.send(401);
res.header('Location', '/#/admin/login');
return res.send(301);
}

var id = req.params.id;
if (id == null || id == '') {
res.send(400);
}

var query = db.postModel.findOne({_id:id});
if (id == null || id === '') {
res.send(400, 'Post not specified.');
}

query.exec(function(err, result) {
if (err{
console.log(err);
return res.send(400);
db.userModel.findById(req.user.id, function (err, user) {
if (err || !user) {
console.log(err ? err : 'Bad user id: ' + post._id);
return res.send(400, err ? err.message : 'User not found.');
}

if (result != null) {
var query = db.postModel.findOne({_id:id});

query.exec(function(err, result) {
if (err || !result) {
console.log(err ? err : 'Bad post id: ' + post._id);
return res.send(400, err ? err.message : 'Post not found.');
}

if (!user.is_admin && user.id !== result.str) {
return res.send(400, 'Requires authorization.');
}

result.remove();
return res.send(200);
}
else {
return res.send(400);
}

});
});
};

Expand Down
8 changes: 6 additions & 2 deletions app/js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ options.api = {};
options.api.base_url = "http://localhost:3001";


app.config(['$locationProvider', '$routeProvider',
app.config(['$locationProvider', '$routeProvider',
function($location, $routeProvider) {
$routeProvider.
when('/', {
Expand Down Expand Up @@ -41,6 +41,10 @@ app.config(['$locationProvider', '$routeProvider',
controller: 'AdminPostEditCtrl',
access: { requiredAuthentication: true }
}).
when('/admin/post/view/:id', {
templateUrl: 'partials/admin.post.view.html',
controller: 'PostViewCtrl'
}).
when('/admin/register', {
templateUrl: 'partials/admin.register.html',
controller: 'AdminUserCtrl'
Expand All @@ -67,7 +71,7 @@ app.config(function ($httpProvider) {
app.run(function($rootScope, $location, $window, AuthenticationService) {
$rootScope.$on("$routeChangeStart", function(event, nextRoute, currentRoute) {
//redirect only if both isAuthenticated is false and no token is set
if (nextRoute != null && nextRoute.access != null && nextRoute.access.requiredAuthentication
if (nextRoute != null && nextRoute.access != null && nextRoute.access.requiredAuthentication
&& !AuthenticationService.isAuthenticated && !$window.sessionStorage.token) {

$location.path("/admin/login");
Expand Down
6 changes: 4 additions & 2 deletions app/partials/admin.post.list.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,18 @@
<th>Action</th>
</tr>
</thead>
<tbody>
<tbody>
<tr ng-repeat="post in posts">
<td>{{post.title}}</td>
<td>{{post.read}}</td>
<td>{{post.created | date:'medium'}}</td>
<td>{{post.updated | date:'medium'}}</td>
<td>
<a href="#/admin/post/view/{{post._id}}" class="btn btn-primary btn-xs"><span class="glyphicon glyphicon-play"></span></a>

<button ng-show="post.is_published" class="btn btn-warning btn-xs" ng-click="updatePublishState(post, false)"><span class="glyphicon glyphicon-eye-close"></span></button>
<button ng-show="!post.is_published" class="btn btn-success btn-xs" ng-click="updatePublishState(post, true)"><span class="glyphicon glyphicon-eye-open"></span></button>

<a href="#/admin/post/edit/{{post._id}}" class="btn btn-warning btn-xs"><span class="glyphicon glyphicon-edit"></span></a>
<button class="btn btn-danger btn-xs" ng-click="deletePost(post._id)"><span class="glyphicon glyphicon-trash"></span></button>
</td>
Expand Down
29 changes: 29 additions & 0 deletions app/partials/admin.post.view.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<section class="post">
<ol class="breadcrumb">
<li><a href="#/">Blog</a></li>
<li><a href="#/admin">Administration</a></li>
<li class="active">{{post.title}}</li>
</ol>

<header class="post-header">
<img class="post-avatar" alt="Kevin Delemme" height="52" width="52" src="img/avatar.jpg">
<div class="post-meta"><i class="fa fa-bullseye"></i> Posted on {{post.created | date:'medium'}}</div>
<div class="post-meta"><i class="fa fa-thumbs-up"></i> {{post.likes}}</div>
<div class="post-meta">
<ul class="list-inline">
<i class="fa fa-tags"></i>
<li ng-repeat="tag in post.tags">
<a class="label label-success" href="#/tag/{{tag}}">{{tag}}</a>
</li>
</ul>
</div>
</header>
<div class="post-content">
<p ng-bind-html="post.content"></p>
</div>
<footer class="post-footer">
<button ng-click="likePost()" class="btn btn-xs btn-success" ng-hide="isAlreadyLiked">Like</button>
<button ng-click="unlikePost()" class="btn btn-xs btn-success" ng-show="isAlreadyLiked">Unlike</button>
{{post.likes}} <i class="fa fa-thumbs-up"></i>
</footer>
</section>