Permalink
Browse files

Can Admin User Policy

  • Loading branch information...
jorgecasar committed Jan 19, 2014
1 parent e58ea71 commit 01a7287d07509d9f90cb440cb6af828847ece9fe
Showing with 38 additions and 7 deletions.
  1. +7 −0 api/controllers/UserController.js
  2. +17 −0 api/policies/canAdminUser.js
  3. +4 −1 config/policies.js
  4. +10 −6 views/user/find.ejs
@@ -25,6 +25,8 @@ module.exports = {
// If id is a shortcut we don't have to find.
if ( isShortcut(id) ) return next();
+ req.session.canAdminUser = canAdminUser(id, req.session.user);
+
// If we get an id we will retun one unique user.
if (id) {
User.findOne(id).done(function foundUser(err, user){
@@ -70,6 +72,11 @@ module.exports = {
function isShortcut(id){
return (id === 'find' || id === 'create' || id === 'update' || id === 'destroy' );
}
+ function canAdminUser(id, sessionUser){
+ // Check if there are an logged user
+ // and the id is the requested one
+ return sessionUser && sessionUser.id === id;
+ }
},
create: function(req, res, next) {
// Create an user using all params.
@@ -0,0 +1,17 @@
+/**
+ * canAdminUser
+ *
+ * @module :: Policy
+ * @description :: Simple policy to allow administrate the requested user.
+ * @docs :: http://sailsjs.org/#!documentation/policies
+ *
+ */
+module.exports = function(req, res, next) {
+
+ // Allow only if the user requested is the same as logged.
+ if (req.param('id') === req.session.user.id) return next();
+
+ // User is not allowed
+ // (default res.forbidden() behavior can be overridden in `config/403.js`)
+ return res.forbidden('You are not permitted to perform this action.');
+};
View
@@ -18,7 +18,10 @@ module.exports.policies = {
// (`true` allows public access)
'*': true,
UserController: {
- '*': 'isAuthenticated',
+ '*': ['isAuthenticated', 'canAdminUser'],
+ find: 'isAuthenticated',
+ update: 'isAuthenticated',
+ logout: 'isAuthenticated',
create: true,
new: true,
auth: true,
View
@@ -9,12 +9,16 @@ if ( typeof users === 'undefined' ) {
</ol>
<h2><%= user.email %></h2>
-<form action="/user/destroy/<%= user.id %>" method="POST">
- <a class="btn btn-primary" href="/user/edit/<%= user.id %>">Edit</a>
- <input type="hidden" name="_method" value="delete"/>
- <input type="submit" class="btn btn-danger" value="<%= __('Delete') %>"/>
-</form>
-
+ <%
+ if ( session.canAdminUser ) {
+ // There logged user and showed user is the same.
+ %>
+ <form action="/user/destroy/<%= user.id %>" method="POST">
+ <a class="btn btn-primary" href="/user/edit/<%= user.id %>">Edit</a>
+ <input type="hidden" name="_method" value="delete"/>
+ <input type="submit" class="btn btn-danger" value="<%= __('Delete') %>"/>
+ </form>
+ <% } %>
<%
} else {
// There are multiple one user.

0 comments on commit 01a7287

Please sign in to comment.