Ruby on Rails 中受保护的共享链接 [英] Protected sharing link in Ruby on Rails

查看:40
本文介绍了Ruby on Rails 中受保护的共享链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来创建和共享到 Rails 视图的受保护链接.

I am looking for a way to create and share protected links to a Rails view.

在我的应用程序中,用户可以创建项目页面.我想让用户创建共享链接,以便只有拥有链接的收件人才能访问项目页面并在该页面上发表评论.我什至可能想为链接添加密码保护.

In my application, Users can create project pages. I want to enable Users to create a sharing link, so that only recipients with the link can access the project page and leave comments on that page. I might even want to add password protection to the link.

有什么好办法吗?

推荐答案

我不知道任何用于受保护链接的宝石,我可以想象很难为这样的单个功能找到一个共同点.

I don't know of any gems for protected links and I can imagine that it is hard to find a common denominator for such an individual feature.

但是,这是我实现这样一个系统的方法.基本思想是用实际上不可猜测"的 token 替换 id.

However, here's how I would implement such a system. The basic idea is to substitute the id with a practically "unguessable" token.

1 - 为要保护的资源创建一个 token 列(index: true, unique: true)

1 - create an token column (index: true, unique: true) for the resource you want to protect

2 - 在模型中,添加验证、生成器、回调和覆盖 to_param

2 - In the model, add validations, generator, callback and override to_param

validates :token, presence: true
validates :token, uniqueness: true

before_validation :generate_token, on: :create

def generate_token
  begin
    self.token = SecureRandom.urlsafe_base64(64, false)
  end while self.class.find_by(token: token)
end

def to_param
  token
end

3 - 更改路由以使用 :token 作为 url 参数

3 - Change the routes to use :token as url parameter

resources :things, param: :token

4 - 更改控制器以通过令牌而不是 id 查找

4 - Change the controller to find by token instead of id

@thing = Thing.find(params[:id])              # change this
@thing = Thing.find_by(token: params[:token]) # to this

现在,thing_url(@thing) 将返回一个您可以安全共享的网址:

Now, thing_url(@thing) will return a url you can safely share:

http://example.com/things/KSwdmTuDSVOGLTHtjK-RU78x7Bme_g-noTrNcovrtXioxPletLvNK35ia_F8CpIBtNDv-_xQ5bZ8uuv18msD4w

当然,您需要将 thingThing 分别替换为您的模型名称.

Of course, you need to replace thing and Thing with your model name, respectively.

这篇关于Ruby on Rails 中受保护的共享链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆