我有一个文件,我想提供在线下载,但仅限于选定的用户.
这是我想到的典型场景
A person who wants the file would typically go to the website and fill
out a form to request access to the file.If I would like to share the file with him/her,I would authorize the
user which should generate a unique link that would be sent to the
user via email. The link would be valid only for certain time period.
我会使用rails来做这件事.我正在寻找的答案:
解决方法
首先,您需要设置一个用于存储令牌的模型:
rails g model DownloadToken token:string expires_at:timestamp
download_token.rb
class DownloadToken < ActiveRecord::Base attr_accessible :token,:expires_at before_create :generate_token def generate_token self.token = SecureRandom.base64(15).tr('+/=lIO0','abc123') end end
接下来,设置控制器来处理提交的表单(或更改现有操作)并生成令牌,发送电子邮件等.
class FooController < ApplicationController def create #process submitted form ... #create a token that expires in 24 hours @token = DownloadToken.create(:expires_at => Time.now + 24.hours) #send email and redirect.. end end
<%= link_to "Click Me","/files/downloads?token=#{@token.token}" %>
您还需要设置一个负责提供下载的控制器,它应该如下所示:
class FileController < ApplicationController before_filter :check_token def check_token redirect_to :back,:flash => {:error => "Bad link"} if DownloadToken.where("token = ? and expires_at > ?",params[:token],Time.now).nil? end def download send_file '/home/your_app/downloads/yourfile.zip',:type=>"application/zip",:x_sendfile=>true end end
routes.rb(假设Foo已经设置为RESTful资源)
match 'files/download' => 'files#download'
此代码未经测试,但它应涵盖您需要的大部分内容,并让您了解您想要采取的方向.
补充阅读: