Generating Unique Tokens for Assets within Rails Application

I've been developing an application in Rails 3.0.3 using Ruby 1.9.2. It is one of my first applications using Rails 3 and I am quite pleased with the progress thus far. However, I am wanting to add a feature that I have thought through, but I am not sure where to really begin.

Essentially, I am building a dumping ground for files, much like Dropbox, however this is mostly for personal storage. Currently, I have files (assets) being uploaded and placed into a folder. I'm using numerous gems to assist:

Devise, for authentication Paperclip, Bcrypt, AWS-s3, mocha, and nifty-generators.

Currently a user is only able to see his/her assets and folders. You can Share your folders with other users of the application, which works great. However, now I am wanting to integrate a feature that you could generate a token which would be used to link an individual not using the application to a file. I'm wanting to allow each asset to have numerous tokens in use, currently.

Essentially, you upload a file (asset) and when you upload it, it gets an id ( I have another scaffold I've created Token, which belongs_to :assets and has:

public_key:string used_at:datetime asset:references

I'm not sure how to move forward from here. I want you to click a link, and it will generate a key. Then you could email this key off to someone and they would click the link and download the file. That would be my starting point, from there I could work out the UI to control multiple keys, expirations,etc. For now, just a single use- once off key that once they use it, it sets used_at to that datetime and makes it unavailable. So unless @token.used_at.nil? , say sorry this token is invalid. Otherwise, allow them to download the file, or present them with a page/view.. etc

Make sense?

I'm just looking for direction, not the code :slight_smile:



you want to generate a nonce (number used once), i have seen this behavior, i think devise uses a similar approach for token authentication, what you do is

you create a route that catches the token

match “blah/:token”

to create

Token.create(:nonce=>Digest::MD5.hexdigest(rand(99999))) <=== you ca be more creative


def authorize


@token = Token.find_by_nonce(params[:token])



return true

rescue ActiveRecord::recordnotfound

sesion[:token]= nil

return false



dont put the files in the public folder, apache serve the file from there not rails, anyone can get them by putting the right path on the url no matter if they are authenticated on the rails app or not, instead put the file where apache cant server them (anywhere inside the app folder but outside the public folder) and use send_file to send them to the user if the authorize action returns true. If you are deploying with capistrano done forget to send the file to the shared directory and create a symbolic link to the location where the file are suppose to be in the app.