Permalink
Browse files

work on the api, you can manage a users login session with a token an…

…d register a new user with the /api/registrations route
  • Loading branch information...
1 parent 47a4866 commit 14b8b2ac96ac655f845efd79261d2fcfe2c46b03 @cjstewart88 committed Jan 19, 2013
View
3 app/controllers/api_controller.rb → app/controllers/api/data_controller.rb
@@ -1,4 +1,5 @@
-class ApiController < ApplicationController
+class Api::DataController < ApplicationController
+ before_filter :authenticate_user!, :only => [:user_info]
before_filter :validate_user_id, :except => :library
def library
View
19 app/controllers/api/registrations_controller.rb
@@ -0,0 +1,19 @@
+# to register a new user:
+# method: POST
+# route: /api/registrations?username=USERNAME_HERE&email=EMAIL_HERE&password=PASSWORD_HERE
+
+class Api::RegistrationsController < ApplicationController
+ respond_to :json
+
+ def create
+ user = User.new(params)
+
+ if user.save
+ render :json => user.as_json(:auth_token=>user.authentication_token, :email=>user.email), :status => 201
+ return
+ else
+ warden.custom_failure!
+ render :json => user.errors, :status => 422
+ end
+ end
+end
View
56 app/controllers/api/sessions_controller.rb
@@ -0,0 +1,56 @@
+# to sign in:
+# method: POST
+# route: /api/sessions.json?email_or_username=USERNAME_OR_EMAIL&password=PASSWORD_HERE
+#
+# to sign out: /api/sessions/
+# method: DELETE
+# route: /api/sessions/:token_here
+
+class Api::SessionsController < ApplicationController
+ skip_before_filter :verify_authenticity_token
+ respond_to :json
+
+ def create
+ email_or_username = params[:email_or_username]
+ password = params[:password]
+
+ if request.format != :json
+ render :status => 406, :json => { :message => "The request must be json" }
+ return
+ end
+
+ if email_or_username.nil? or password.nil?
+ render :status => 400, :json => { :message => "The request must contain the user email/username and password." }
+ return
+ end
+
+ @user = User.where('email = :email_or_username OR username = :email_or_username', {email_or_username: email_or_username}).first
+
+ if @user.nil?
+ logger.info("User #{email_or_username} failed signin, user cannot be found.")
+ render :status => 401, :json => { :message => "Invalid email/username or passoword." }
+ return
+ end
+
+ @user.ensure_authentication_token!
+
+ if not @user.valid_password?(password)
+ logger.info("User #{email_or_username} failed signin, password \"#{password}\" is invalid")
+ render :status => 401, :json => { :message => "Invalid email/username or password." }
+ else
+ render :status => 200, :json => { :id => @user.id, :token => @user.authentication_token }
+ end
+ end
+
+ def destroy
+ @user = User.find_by_authentication_token(params[:id])
+
+ if @user.nil?
+ logger.info("Token not found.")
+ render :status => 404, :json => { :message => "Invalid token." }
+ else
+ @user.reset_authentication_token!
+ render :status => 200, :json => { :token => params[:id] }
+ end
+ end
+end
View
7 app/controllers/application_controller.rb
@@ -1,7 +1,7 @@
class ApplicationController < ActionController::Base
protect_from_forgery
- before_filter :ensure_domain, :check_current_user
+ before_filter :ensure_domain
def index
flash[:notice] = "Thanks a ton for your support, it means a lot!" if params[:thanks]
@@ -42,9 +42,4 @@ def ensure_domain
redirect_to "http://www.tubalr.com#{request.fullpath}", :status => 301
end
end
-
- def check_current_user
- # set
- # current_user = User.find() if params[:auth_token]
- end
end
View
4 app/controllers/banned_videos_controller.rb
@@ -1,4 +1,6 @@
-class BannedVideosController < ApplicationController
+class BannedVideosController < ApplicationController
+ before_filter :authenticate_user!
+
def ban_video
current_user.banned_videos.create(:video_id => params[:video_id])
render :json => { :success => true }
View
10 app/controllers/events_controller.rb
@@ -38,18 +38,14 @@
# query: '/r/metal'
# }
+
+
class EventsController < ApplicationController
- before_filter :validate_current_user
+ before_filter :authenticate_user!
def create
event = JSON.parse(params[:event])
current_user.events.create(event)
head 201
end
-
- private
-
- def validate_current_user
- head 403 and return unless user_signed_in?
- end
end
View
5 app/controllers/follows_controller.rb
@@ -1,4 +1,5 @@
class FollowsController < ApplicationController
+ before_filter :authenticate_user!
before_filter :validate_follow_params
def follow
@@ -14,11 +15,9 @@ def unfollow
private
def validate_follow_params
- head 403 and return unless user_signed_in?
-
@who = User.find(params[:who])
rescue ActiveRecord::RecordNotFound
- render :status => 400, :json => {error: "User not found"}
+ render :status => 400, :json => { error: "User not found" }
end
end
View
2 app/controllers/playlists_controller.rb
@@ -1,4 +1,6 @@
class PlaylistsController < ApplicationController
+ before_filter :authenticate_user!, :only => [:import_youtube_playlists, :create, :sort, :update]
+
def listen
@user = User.where(:username => params[:username]).first
@username = params[:username]
View
8 app/controllers/registrations_controller.rb
@@ -1,9 +1,11 @@
class RegistrationsController < Devise::RegistrationsController
+ before_filter :authenticate_user!, :only => [:update]
+
def create
resource_params["md5_email"] = Digest::MD5.hexdigest(resource_params["email"])
-
+
build_resource
-
+
if resource.save
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_navigational_format?
@@ -32,7 +34,7 @@ def update
end
@user = User.find(current_user.id)
-
+
if params[:user][:favorite_genres]
@user.favorite_genre_list = params[:user][:favorite_genres].join(',')
else
View
10 app/models/user.rb
@@ -2,27 +2,25 @@ class User < ActiveRecord::Base
has_many :events
has_many :playlists, :order => "lower(playlist_name) ASC"
has_many :banned_videos
-
+
validates_presence_of :username
validates_uniqueness_of :username, :case_sensitive => false
acts_as_taggable
acts_as_taggable_on :favorite_genres
-
+
acts_as_followable
acts_as_follower
self.per_page = 10
- # Include default devise modules. Others available are:
- # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
- devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
+ devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :token_authenticatable
attr_accessor :login
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :username, :background, :password, :password_confirmation, :remember_me, :login, :md5_email
-
+
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
login = conditions.delete(:login)
View
12 config/initializers/devise.rb
@@ -92,10 +92,6 @@
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
- # If true, uses the password salt as remember token. This should be turned
- # to false if you are not using database authenticatable.
- config.use_salt_as_remember_token = true
-
# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.cookie_options = {}
@@ -207,9 +203,9 @@
# manager.intercept_401 = false
# manager.default_strategies(:scope => :user).unshift :some_external_strategy
# end
-
+
config.warden do |manager|
- manager.strategies.add(:login_with_username_or_email) do
+ manager.strategies.add(:login_with_username_or_email) do
def valid?
params[:user] && params[:user][:email] && params[:user][:password]
end
@@ -226,6 +222,6 @@ def authenticate!
end
manager.default_strategies(scope: :user).unshift :login_with_username_or_email
end
-
+
config.authentication_keys = [ :login ]
-end
+end
View
10 config/routes.rb
@@ -39,7 +39,11 @@
post "/event" => "events#create"
- get "/api/library.json" => "api#library"
- get "/api/user/:user_id/info.json" => "api#user_info"
- get "/api/user/:user_id/playlists.json" => "api#user_playlists"
+ namespace :api do
+ get "/library.json" => "data#library"
+ get "/user/:user_id/info.json" => "data#user_info"
+ get "/user/:user_id/playlists.json" => "data#user_playlists"
+ resources :sessions, :only => [:create, :destroy]
+ resources :registrations, :only => [:create]
+ end
end
View
8 db/migrate/20130119142649_add_token_to_user.rb
@@ -0,0 +1,8 @@
+class AddTokenToUser < ActiveRecord::Migration
+ def change
+ change_table :users do |t|
+ t.string :authentication_token
+ end
+ add_index :users, :authentication_token, :unique => true
+ end
+end
View
4 db/schema.rb
@@ -11,7 +11,7 @@
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20130108043259) do
+ActiveRecord::Schema.define(:version => 20130119142649) do
create_table "banned_videos", :force => true do |t|
t.integer "user_id"
@@ -86,8 +86,10 @@
t.string "background"
t.string "md5_email"
t.integer "playlists_count", :default => 0
+ t.string "authentication_token"
end
+ add_index "users", ["authentication_token"], :name => "index_users_on_authentication_token", :unique => true
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true

0 comments on commit 14b8b2a

Please sign in to comment.