- 浏览: 2075848 次
- 性别:
- 来自: NYC
文章分类
- 全部博客 (628)
- Linux (53)
- RubyOnRails (294)
- HTML (8)
- 手册指南 (5)
- Mysql (14)
- PHP (3)
- Rails 汇总 (13)
- 读书 (22)
- plugin 插件介绍与应用 (12)
- Flex (2)
- Ruby技巧 (7)
- Gem包介绍 (1)
- javascript Jquery ext prototype (21)
- IT生活 (6)
- 小工具 (4)
- PHP 部署 drupal (1)
- javascript Jquery sort plugin 插件 (2)
- iphone siri ios (1)
- Ruby On Rails (106)
- 编程概念 (1)
- Unit Test (4)
- Ruby 1.9 (24)
- rake (1)
- Postgresql (6)
- ruby (5)
- respond_to? (1)
- method_missing (1)
- git (8)
- Rspec (1)
- ios (1)
- jquery (1)
- Sinatra (1)
最新评论
-
dadadada2x:
user模型里加上 protected def email ...
流行的权限管理 gem devise的定制 -
Sev7en_jun:
shrekting 写道var pattern = /^(0| ...
强悍的ip格式 正则表达式验证 -
jiasanshou:
好文章!!!
RPM包rpmbuild SPEC文件深度说明 -
寻得乐中乐:
link_to其实就是个a标签,使用css控制,添加一个参数: ...
Rails在link_to中加参数 -
aiafei0001:
完全看不懂,不知所然.能表达清楚一点?
"$ is not defined" 的问题怎么办
How to Add Simple Permissions into Your Simple App. Also, Thoughtbot Rules!
Posted about 21 hours back at RailsTips.org - Home
In which I discuss how I added simple permissions into flightcontrolled.com an app I created and how cool clearance, shoulda, factory girl and paperclip are.
Last week, in a few hours, I whipped together flightcontrolled.com for Flight Control, a super fun iPhone game. The site allows users to upload screenshots of their high scores. I thought I would provide a few details here as some may find it interesting.
It is a pretty straightforward and simple site, but it did need a few permissions. I wanted users to be able to update their own profile, scores and photos, but not anyone else’s. On top of that, I, as an admin, should be able to update anything on the site. I’m sure there is a better way, but this is what I did and it is working just fine.
Add admin to users
I added an admin boolean to the users table. You may or may not know this, but Active Record adds handy boolean methods for all your columns. For example, if the user model has an email column and an admin column, you can do the following.
user = User.new
user.email? # => false
user.email = 'foobar@foobar.com'
user.email? # => true
user.admin? # => false
user.admin = true
user.admin? # => true
Simple permissions module
Next up, I created a module called permissions, that looks something like this:
module Permissions
def changeable_by?(other_user)
return false if other_user.nil?
user == other_user || other_user.admin?
end
end
I put this in app/concerns/ and added that directory to the load path, but it will work just fine in lib/.
Mixin the permission module
Then in the user, score and photo models, I just include that permission module.
class Score < ActiveRecord::Base
include Permissions
end
class Photo < ActiveRecord::Base
include Permissions
end
class User < ActiveRecord::Base
include Permissions
end
Add checks in controllers/views
Now, in the view I can check if a user has permission before showing the edit and delete links.
<%- if score.changeable_by?(current_user) -%>
<li class="actions">
<%= link_to 'Edit', edit_score_url(score) %>
<%= link_to 'Delete', score, :method => :delete %>
</li>
<%- end -%>
And in the controller, I can do the same.
class ScoresController < ApplicationController
before_filter :authorize,nly => [:edit, :update, :destroy]
private
def authorize
unless @score.changeable_by?(current_user)
render :text => 'Unauthorized', :status => :unauthorized
end
end
end
Macro for model tests
I didn’t forget about testing either. I created a quick macro for shoulda like this (also uses factory girl and matchy):
class ActiveSupport::TestCase
def self.should_have_permissions(factory)
should "know who has permission to change it" do
object = Factory(factory)
admin = Factory(:admin)
other_user = Factory(:user)
object.changeable_by?(other_user).should be(false)
object.changeable_by?(object.user).should be(true)
object.changeable_by?(admin).should be(true)
object.changeable_by?(nil).should be(false)
end
end
end
Which I can then call from my various model tests:
class ScoreTest < ActiveSupport::TestCase
should_have_permissions :score
end
Looking at it now, I probably could just infer the score factory as I’m in the ScoreTest, but for whatever reason, I didn’t go that far.
A sprinkle of controller tests
I also did something like the following to test the controllers:
class ScoresControllerTest < ActionController::TestCase
context "A regular user" do
setup do
@user = Factory(:email_confirmed_user)
sign_in_as @user
end
context "on GET to :edit" do
context "for own score" do
setup do
@score = Factory(:score, :user => @user)
get :edit, :id => @score.id
end
should_respond_with :success
end
context "for another user's score" do
setup do
@score = Factory(:score)
get :edit, :id => @score.id
end
should_respond_with :unauthorized
end
end
end
context "An admin user" do
setup do
@admin = Factory(:admin)
sign_in_as @admin
end
context "on GET to :edit" do
context "for own score" do
setup do
@score = Factory(:score, :user => @admin)
get :edit, :id => @score.id
end
should_respond_with :success
end
context "for another user's score" do
setup do
@score = Factory(:score)
get :edit, :id => @score.id
end
should_respond_with :success
end
end
end
end
Summary of Tools
I should call flightcontrolled, the thoughtbot project as I used several of their awesome tools. I used clearance for authentication, shoulda and factory girl for testing, and paperclip for file uploads. This was the first project that I used factory girl on and I really like it. Again, I didn’t get the fuss until I used it, and then I was like “Oooooh! Sweet!”.
One of the cool things about paperclip is you can pass straight up convert options to imagemagick. Flight Control is a game that is played horizontally, so I knew all screenshots would need to be rotated 270 degress. I just added the following convert options (along with strip) to the paperclip call:
has_attached_file :image,
:styles => {:thumb => '100>', :full => '480>'},
:default_style => :full,
:convert_options => {:all => '-rotate 270 -strip'}
Conclusion
You don’t need some fancy plugin or a lot of code to add some basic permissions into your application. A simple module can go a long way. Also, start using Thoughtbot’s projects. I’m really impressed with the developer tools they have created thus far.
Posted about 21 hours back at RailsTips.org - Home
In which I discuss how I added simple permissions into flightcontrolled.com an app I created and how cool clearance, shoulda, factory girl and paperclip are.
Last week, in a few hours, I whipped together flightcontrolled.com for Flight Control, a super fun iPhone game. The site allows users to upload screenshots of their high scores. I thought I would provide a few details here as some may find it interesting.
It is a pretty straightforward and simple site, but it did need a few permissions. I wanted users to be able to update their own profile, scores and photos, but not anyone else’s. On top of that, I, as an admin, should be able to update anything on the site. I’m sure there is a better way, but this is what I did and it is working just fine.
Add admin to users
I added an admin boolean to the users table. You may or may not know this, but Active Record adds handy boolean methods for all your columns. For example, if the user model has an email column and an admin column, you can do the following.
user = User.new
user.email? # => false
user.email = 'foobar@foobar.com'
user.email? # => true
user.admin? # => false
user.admin = true
user.admin? # => true
Simple permissions module
Next up, I created a module called permissions, that looks something like this:
module Permissions
def changeable_by?(other_user)
return false if other_user.nil?
user == other_user || other_user.admin?
end
end
I put this in app/concerns/ and added that directory to the load path, but it will work just fine in lib/.
Mixin the permission module
Then in the user, score and photo models, I just include that permission module.
class Score < ActiveRecord::Base
include Permissions
end
class Photo < ActiveRecord::Base
include Permissions
end
class User < ActiveRecord::Base
include Permissions
end
Add checks in controllers/views
Now, in the view I can check if a user has permission before showing the edit and delete links.
<%- if score.changeable_by?(current_user) -%>
<li class="actions">
<%= link_to 'Edit', edit_score_url(score) %>
<%= link_to 'Delete', score, :method => :delete %>
</li>
<%- end -%>
And in the controller, I can do the same.
class ScoresController < ApplicationController
before_filter :authorize,nly => [:edit, :update, :destroy]
private
def authorize
unless @score.changeable_by?(current_user)
render :text => 'Unauthorized', :status => :unauthorized
end
end
end
Macro for model tests
I didn’t forget about testing either. I created a quick macro for shoulda like this (also uses factory girl and matchy):
class ActiveSupport::TestCase
def self.should_have_permissions(factory)
should "know who has permission to change it" do
object = Factory(factory)
admin = Factory(:admin)
other_user = Factory(:user)
object.changeable_by?(other_user).should be(false)
object.changeable_by?(object.user).should be(true)
object.changeable_by?(admin).should be(true)
object.changeable_by?(nil).should be(false)
end
end
end
Which I can then call from my various model tests:
class ScoreTest < ActiveSupport::TestCase
should_have_permissions :score
end
Looking at it now, I probably could just infer the score factory as I’m in the ScoreTest, but for whatever reason, I didn’t go that far.
A sprinkle of controller tests
I also did something like the following to test the controllers:
class ScoresControllerTest < ActionController::TestCase
context "A regular user" do
setup do
@user = Factory(:email_confirmed_user)
sign_in_as @user
end
context "on GET to :edit" do
context "for own score" do
setup do
@score = Factory(:score, :user => @user)
get :edit, :id => @score.id
end
should_respond_with :success
end
context "for another user's score" do
setup do
@score = Factory(:score)
get :edit, :id => @score.id
end
should_respond_with :unauthorized
end
end
end
context "An admin user" do
setup do
@admin = Factory(:admin)
sign_in_as @admin
end
context "on GET to :edit" do
context "for own score" do
setup do
@score = Factory(:score, :user => @admin)
get :edit, :id => @score.id
end
should_respond_with :success
end
context "for another user's score" do
setup do
@score = Factory(:score)
get :edit, :id => @score.id
end
should_respond_with :success
end
end
end
end
Summary of Tools
I should call flightcontrolled, the thoughtbot project as I used several of their awesome tools. I used clearance for authentication, shoulda and factory girl for testing, and paperclip for file uploads. This was the first project that I used factory girl on and I really like it. Again, I didn’t get the fuss until I used it, and then I was like “Oooooh! Sweet!”.
One of the cool things about paperclip is you can pass straight up convert options to imagemagick. Flight Control is a game that is played horizontally, so I knew all screenshots would need to be rotated 270 degress. I just added the following convert options (along with strip) to the paperclip call:
has_attached_file :image,
:styles => {:thumb => '100>', :full => '480>'},
:default_style => :full,
:convert_options => {:all => '-rotate 270 -strip'}
Conclusion
You don’t need some fancy plugin or a lot of code to add some basic permissions into your application. A simple module can go a long way. Also, start using Thoughtbot’s projects. I’m really impressed with the developer tools they have created thus far.
发表评论
-
Destroying a Postgres DB on Heroku
2013-04-24 10:58 935heroku pg:reset DATABASE -
VIM ctags setup ack
2012-04-17 22:13 3259reference ctags --extra=+f --e ... -
alias_method_chain方法在3.1以后的替代使用方式
2012-02-04 02:14 3295alias_method_chain() 是rails里的一个 ... -
一些快速解决的问题
2012-01-19 12:35 1472问题如下: 引用Could not open library ... -
API service 安全问题
2011-12-04 08:47 1386这是一个长期关注的课题 rest api Service的 ... -
Module方法调用好不好
2011-11-20 01:58 1349以前说,用module给class加singleton方法,和 ... -
一个ajax和rails交互的例子
2011-11-19 01:53 1908首先,这里用了一个,query信息解析的包,如下 https: ... -
Rails 返回hash给javascript
2011-11-19 01:43 2277这是一个特别的,不太正统的需求, 因为,大部分时候,ajax的 ... -
关于Rubymine
2011-11-18 23:21 2267开个帖子收集有关使用上的问题 前一段时间,看到半价就买了。想 ... -
ruby中和javascript中,动态方法的创建
2011-11-18 21:01 1241class Klass def hello(*args) ... -
textmate快捷键 汇总
2011-11-16 07:20 8147TextMate 列编辑模式 按住 Alt 键,用鼠标选择要 ... -
Ruby面试系列六,面试继续面试
2011-11-15 05:55 2025刚才受到打击了,充分报漏了自己基础不扎实,不肯向虎炮等兄弟学习 ... -
说说sharding
2011-11-13 00:53 1492这个东西一面试就有人 ... -
rails面试碎碎念
2011-11-12 23:51 1946面试继续面试 又有问ru ... -
最通常的git push reject 和non-fast forward是因为
2011-11-12 23:29 17216git push To git@github.com:use ... -
Rails 自身的many to many关系 self has_many
2011-11-12 01:43 2738简单点的 #注意外键在person上people: id ... -
Rails 3下的 in place editor edit in place
2011-11-12 01:20 946第一个版本 http://code.google.com/p ... -
Heroku 的诡异问题集合
2011-11-11 07:22 1697开个Post记录,在用heroku过程中的一些诡异问题和要注意 ... -
SCSS 和 SASS 和 HAML 和CoffeeScript
2011-11-07 07:52 12960Asset Pipeline 提供了内建 ... -
Invalid gemspec because of the date format in specification
2011-11-07 02:14 2122又是这个date format的错误。 上次出错忘了,记录下 ...
相关推荐
1 - Add these permissions into your AndroidManifest.xml and request for them in Android 6.0 2 - Open the recorder activity String filePath = Environment.getExternalStorageDirectory() "/recorded_...
Failed to set permissions of path: \tmp\hadoop-Administrator,的解决方法,更换hadoop-core-1.0.2-modified.jar包
eclipse远程调试hadoop时 报出eclipse Hadoop Failed to set permissions of path错误 修改hadoop core包中FileUtil java文件 里面有checkReturnValue方法 将代码throw new IOException "Failed to set ...
ERROR org.apache.hadoop.mapred.TaskTracker: Can not start task tracker because java.io.IOException: Failed to set permissions of path: \tmp\hadoop-admin \mapred\local\ttprivate to 0700 at org.apache...
It shows how to check and request permissions at runtime, handle backwards compatibility using the support library and how to declare optional permissions for M-devices only. Introduction Android M ...
Chapter 3, Groups, Users, and Permissions, explains how to create hosts in Zabbix and split them in groups. This chapter also covers how to create users and user groups. Then it explains the different...
Exactly how permissions work and how to decipher the most cryptic Linux permissions with ease. How to use the nano, vi, and emacs editors. Two methods to search for files and directories. How to ...
资源分类:Python库 所属语言:Python 资源全名:django-simple-permissions-0.6.0.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or...
This Project is to be simple, Checking permissions. Install repositories { jcenter() } compile 'com.nobrain.android.permissions:library:1.1.0' How to use To check permissions AndroidPermissions....
Moving on, you'll learn how to centralize the creation of search templates and give users the tools to pivot the data and expose it to the user in useful ways, such as on the dashboard. The book ends...
1 , manc-skinex.zip This is an example of how to add skins to your program.<END><br>2 , irregularForms.zip This is a great example. It takes two images to shape the form, then blits the "face" ...
To add this library to your project, add these lines to your build.gradle repositories { maven { url "https://jitpack.io" } } dependencies { implementation '...
To manage your storage on Ubuntu Server systems, you will learn how to add and format storage and view disk usage. Later, you will also learn how to configure network interfaces, manage IP addresses,...
Add the JitPack repository to your build file allprojects { repositories { ... maven { url 'https://jitpack.io' } } } Add dependency dependencies { implementation '...
We will show you how you can integrate NAV with the Microsoft platform, and secure your deployment by managing roles and permissions. Moving on, we will explain how to monitor and manage server ...
- **版权使用申请**:所有请求均需在线提交至[www.cengage.com/permissions](http://www.cengage.com/permissions)。 - **图书馆索书号**:2009937405 ### 四、国际分布与合作 Cengage Learning在全球范围内设有多...
the book covers practical scenarios to show how you or your organization can effectively manage your proprietary code., You will learn how to manage multiple users, groups, and the permissions GitLab...
This is a development tool to show all permissions on your phone Try it Installing android SDK See the official android doc Create emulator The command line for creating an AVD has the following ...
"Permissions"一词直译为“权限”,在操作系统、数据库、网络服务以及各种应用程序中都有广泛应用。它涉及到用户或进程对资源(如文件、目录、数据库记录)的访问控制,以防止未经授权的访问和操作。下面将详细阐述...