Exchanging user/password for token in a Rails API -


i'm having little trouble figuring out how create token based authentication system rails api.

i'm planning build ember app users should able sign in providing password , username.

on rails side have setup authenticationtoken model checks authorization token , non-persisted secret. store encrypted secret based on secret , authenticationtoken id (a bson::objectid).

basically idea client should able authenticate long hangs onto secret. , needs request new access token. want keep stateless avoiding sessions.

i'm confused route , controller should user trades user/pass access token. numerous blog post/tutorials have found omits part. create simple post route client sends credentials , gets token json? or should use http basic auth?

class user   include mongoid::document   include activemodel::securepassword   embeds_many :tokens, class_name: 'users::authenticationtoken'   field :email, type: string   field :username, type: string   field :password_digest, type: string   validates :email, presence: true, uniqueness: true   has_secure_password end 

require "securerandom" require "bcrypt"  class users::authenticationtoken   include mongoid::document   embedded_in :user    attr_accessor :secret   field :hashed_secret    validates :hashed_secret, uniqueness: true, presence: true   before_validation :generate_secret    def self.find_by_id(id)     begin       id = bson::objectid.from_string(id) unless id.is_a?(bson::objectid)       tokens = user.find_by('tokens._id' => id).try(:tokens)       tokens ? tokens.find_by(id: id) : nil     rescue mongoid::errors::documentnotfound, bson::objectid::invalid       nil     end   end    # @return [boolean]   def has_secret? secret     bcrypt::password.new(hashed_secret) == secret   end    def authenticate!(secret)     user if has_secret? secret   end    private    def generate_secret     self.secret = securerandom.urlsafe_base64(32)     self.hashed_secret = bcrypt::password.create secret, cost: cost   end    def cost     rails.env.test? ? 1 : 10   end end 

i have authenticate method looks this:

def authenticate!   token = users::authenticationtoken.find_by_id(token_id)   user = token.try(:authenticate!, secret)   user.nil? ? fail!("could not log in") : success!(user) end 


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -