diff --git a/app/assets/javascripts/login.js b/app/assets/javascripts/login.js new file mode 100644 index 0000000..70a2f44 --- /dev/null +++ b/app/assets/javascripts/login.js @@ -0,0 +1,43 @@ +$("#checkin_menu").show(); +$("#checkin").click( function(e){ + var username = $("#user_email").val(); + var password = $("#user_password").val(); + $.ajax({ + type: 'POST', + url: '/api/v1/checkin', + dataType: 'json', + contentType: 'application/json', + processData: false, + data: JSON.stringify({"username": username, "password": password }), + complete: function() { }, + success: function(data) { + alert("Checked IN!"); + $("#user_email").val(''); + $("#user_password").val(''); + }, + error: function(data,textStatus) { + alert( "Error: " + JSON.parse(data.responseText)["error"]); + } + }) +}); +$("#checkout").click( function(e){ + var username = $("#user_email").val(); + var password = $("#user_password").val(); + $.ajax({ + type: 'POST', + url: '/api/v1/checkout', + dataType: 'json', + contentType: 'application/json', + processData: false, + data: JSON.stringify({"username": username, "password": password }), + complete: function() { }, + success: function(data) { + alert("Checked OUT!"); + $("#user_email").val(''); + $("#user_password").val(''); + }, + error: function(data,textStatus) { + alert( "Error: " + JSON.parse(data.responseText)["error"]); + } + }) +}); diff --git a/app/components/app_tab_panel.rb b/app/components/app_tab_panel.rb index 1398d2a..3c19eb4 100644 --- a/app/components/app_tab_panel.rb +++ b/app/components/app_tab_panel.rb @@ -6,6 +6,11 @@ class AppTabPanel < Netzke::Basepack::TabPanel c.text = "Exit" end + action :check_out do |c| + c.icon = :door_out + c.text = "CHECK OUT" if controller.current_user + end + def configure(c) #all users @@ -37,7 +42,10 @@ class AppTabPanel < Netzke::Basepack::TabPanel wrappedComponent: :transactions_border, title: "Transactions"}, :logs, - :user_roles] + { layout: :fit, + wrappedComponent: :user_role_joins, + title: "User Roles"} + ] end @@app_tab_panel_items.each do |item| @@ -47,9 +55,8 @@ class AppTabPanel < Netzke::Basepack::TabPanel self.class.component item[:wrappedComponent] end end - c.prevent_header = true - c.tbar = [:sign_out] + c.tbar = [:sign_out, :check_out] c.items = @@app_tab_panel_items super end @@ -58,6 +65,5 @@ class AppTabPanel < Netzke::Basepack::TabPanel #gets js from app_tab_panel/javascripts/sign_out.js c.mixin :sign_out end - end diff --git a/app/components/app_tab_panel/javascripts/sign_out.js b/app/components/app_tab_panel/javascripts/sign_out.js index d7c9bc3..8672024 100644 --- a/app/components/app_tab_panel/javascripts/sign_out.js +++ b/app/components/app_tab_panel/javascripts/sign_out.js @@ -5,5 +5,17 @@ url: '/users/sign_out', method: 'DELETE' }); + }, + onCheckOut: function(){ + Ext.Ajax.request({ + url: '/api/v1/checkout', + method: 'POST', + success: function(response, opts) { + Ext.Ajax.request({ + url: '/users/sign_out', + method: 'DELETE' + }); + } + }); } } diff --git a/app/components/bikes.rb b/app/components/bikes.rb index 29ec030..9897742 100644 --- a/app/components/bikes.rb +++ b/app/components/bikes.rb @@ -18,9 +18,9 @@ class Bikes < Netzke::Basepack::Grid }, :color, { :name => :bike_style__style, :text => 'Style' }, - :seat_tube_height, - :top_tube_length, - :wheel_size, + { :name => :seat_tube_height, :text => 'Seat Tube (in)'}, + { :name => :top_tube_length, :text => 'Top Tube (in)'}, + { :name => :wheel_size, :text => 'Wheel Size (in)'}, :value, { :name => :bike_condition__condition, :text => 'Condition'}, { :name => :bike_status__status, :text => 'Status'}, diff --git a/app/components/user_logs.rb b/app/components/user_logs.rb index 1300845..63dbf8e 100644 --- a/app/components/user_logs.rb +++ b/app/components/user_logs.rb @@ -37,7 +37,7 @@ class UserLogs < Netzke::Basepack::Grid { :name => :end_date, :hidden => true, :default_value => Time.now.to_formatted_s(:db) }, { :name => :hours, :getter => lambda { |rec| (rec.end_date - rec.start_date)/3600 }, :sorting_scope => :sort_by_duration}, :description, - { :name => :user_action__action, :text => 'Action' }, + { :name => :user_action__action, :text => 'Action', :default_value => ::ActsAsLoggable::UserAction.all.first.id }, :created_at, :updated_at, { :name => :logged_by, :getter => lambda{ |rec| @@ -53,13 +53,12 @@ class UserLogs < Netzke::Basepack::Grid bike_store = Bike.all.map { |b| [b.id, b.shop_id] } current_user ||= User.find_by_id(session[:selected_user_id]) || controller.current_user bike_id = current_user.bike.nil? ? nil : current_user.bike.id - action_id = current_user.user_role.id [ { :name => :start_date}, { :name => :end_date}, { :name => :description}, #had to hack acts_as_loggable/log.rb to get this to work - { :name => :user_action__action, :field_label => 'Action', :value => action_id}, + { :name => :user_action__action, :field_label => 'Action'}, { :name => :for_bike, :checkboxName => :copy_log, :inputValue => true, :title => "Copy description to a Bike's History?", :xtype => 'fieldset', :checkboxToggle => true, :collapsed => true, :items => [ {:xtype => 'combo', :no_binding => true, :name => :copy_id, :title => 'Bike', :fieldLabel => 'Bike', :store => bike_store, :value => bike_id} ] diff --git a/app/components/user_role_joins.rb b/app/components/user_role_joins.rb new file mode 100644 index 0000000..ba61e66 --- /dev/null +++ b/app/components/user_role_joins.rb @@ -0,0 +1,21 @@ +class UserRoleJoins < Netzke::Basepack::Grid + def configure(c) + super + c.model = "UserRoleJoin" + c.header = false + c.title = "User Roles" + c.columns = [ + { :name => :user__first_name, :text => "First"}, + { :name => :user__last_name, :text => "Last"}, + { :name => :role__role, :text => "Role"}, + :created_at, + :updated_at, + :ends ] + end + + #override with nil to remove actions + def default_bbar + [ :apply, :add_in_form, :search ] + end + +end diff --git a/app/components/user_roles.rb b/app/components/user_roles.rb deleted file mode 100644 index 4de2383..0000000 --- a/app/components/user_roles.rb +++ /dev/null @@ -1,15 +0,0 @@ -class UserRoles < Netzke::Basepack::Grid - - def configure(c) - super - c.model = "UserRole" - c.title = "User Roles" - c.columns = [ :role, :created_at, :updated_at, :ends ] - end - - #override with nil to remove actions - def default_bbar - [ :apply, :add_in_form, :search ] - end - -end diff --git a/app/components/users.rb b/app/components/users.rb index 45ef596..e45962d 100644 --- a/app/components/users.rb +++ b/app/components/users.rb @@ -10,7 +10,6 @@ class Users < Netzke::Basepack::Grid :last_name, :nickname, :email, - :user_role__role, :bike__shop_id ] end diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rb new file mode 100644 index 0000000..a3ed9c1 --- /dev/null +++ b/app/controllers/api/v1/base_controller.rb @@ -0,0 +1,22 @@ +class Api::V1::BaseController < ActionController::Base + respond_to :json + + before_filter :authenticate_user + + private + def authenticate_user + if params[:username] + user = User.find_for_database_authentication( :email => params[:username] ) + @current_user = user if user && user.valid_password?( params[:password] ) + + if @current_user.nil? + msg = "Username/Password/Token invalid" + render :json => {:error => msg }, :status => 403 and return + end + else + authenticate_user! + @current_user = current_user + end + end +end + diff --git a/app/controllers/api/v1/logs_controller.rb b/app/controllers/api/v1/logs_controller.rb new file mode 100644 index 0000000..b226b24 --- /dev/null +++ b/app/controllers/api/v1/logs_controller.rb @@ -0,0 +1,22 @@ +class Api::V1::LogsController < Api::V1::BaseController + + def checkin + #must use @current_user since user may not have signed in + if @current_user.checked_in? + render :json => { "error" => "You are already checked in."}, :status => 404 and return + else + @current_user.checkin + render :nothing => true, :status => 204 and return + end + end + + def checkout + #must use @current_user since user may not have signed in + if !@current_user.checked_in? + render :json => { "error" => "You were not even checked in."}, :status => 404 and return + else + @current_user.checkout + render :nothing => true, :status => 204 and return + end + end +end diff --git a/app/models/ability.rb b/app/models/ability.rb index 4fde40d..7bf89a3 100644 --- a/app/models/ability.rb +++ b/app/models/ability.rb @@ -1,14 +1,16 @@ class Ability include CanCan::Ability - + def initialize(current_user) @current_user = current_user - self.send(current_user.role.to_sym) + current_user.roles.each do |role| + self.send(role.role.to_sym) + end end def admin can :manage, :all - end + end def staff can :manage, :all @@ -21,7 +23,7 @@ class Ability def user can :read, :all - can :update, Bike, :id => @current_user.bike_id unless @current_user.bike.nil? + can :manage, Bike, :id => @current_user.bike_id unless @current_user.bike.nil? can :manage, ::ActsAsLoggable::Log, { :loggable_type => "Bike", :loggable_id => @current_user.bike_id } can :manage, ::ActsAsLoggable::Log, { :loggable_type => "User", :loggable_id => @current_user.id } end diff --git a/app/models/role.rb b/app/models/role.rb new file mode 100644 index 0000000..e7a5b90 --- /dev/null +++ b/app/models/role.rb @@ -0,0 +1,16 @@ +class Role < ActiveRecord::Base + attr_accessible :role + + has_many :user_role_joins + has_many :users, through: :user_role_joins + validates_uniqueness_of :role + + + def to_s + self.role + end + + def ==(other) + self.role == other.role + end +end diff --git a/app/models/user.rb b/app/models/user.rb index 9b67e65..338afd5 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -7,14 +7,16 @@ class User < ActiveRecord::Base # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, - :first_name, :last_name, :nickname, :user_role_id, :bike_id, - :user_profiles_attributes + :first_name, :last_name, :nickname, :bike_id, + :user_profiles_attributes, :username has_many :transactions has_many :user_profiles accepts_nested_attributes_for :user_profiles, allow_destroy: false - has_one :user_role + has_many :user_role_joins, :conditions => ["ends IS NULL OR ends > ?", Time.now] + has_many :roles, through: :user_role_joins + belongs_to :bike validates :first_name, :presence => true @@ -24,29 +26,65 @@ class User < ActiveRecord::Base "#{first_name} #{last_name}" end - def full_name - to_s + def email_required? + false end - def role - user_role.role + def full_name + to_s end def role?(role) - user_role.to_s == role.to_s + if role.kind_of?(String) or role.kind_of?(Symbol) + role = Role.find_by_role(role.to_s) + end + roles.include?(role) end +### TODO methods below probably belong somewhere else + def total_hours - ActsAsLoggable::Log.where( :loggable_type => self.class.to_s, :loggable_id => self.id).sum { |l| (l.end_date - l.start_date)/3600 }.round(2) + log_action = ::ActsAsLoggable::UserAction.find_by_action("CHECKIN") + logs.where("log_action_id != ? AND log_action_type = ?", log_action.id, log_action.class.to_s).sum { |l| (l.end_date - l.start_date)/3600 }.round(2) end def current_month_hours + log_action = ::ActsAsLoggable::UserAction.find_by_action("CHECKIN") #TODO need to prevent users from saving logs across months, force to create a new log if crossing month current_month_range = (Time.now.beginning_of_month..Time.now.end_of_month) - ActsAsLoggable::Log.where( :loggable_type => self.class.to_s, :loggable_id => self.id) + logs.where("log_action_id != ? AND log_action_type = ?", log_action.id, log_action.class.to_s) .where( :start_date => current_month_range) .where( :end_date => current_month_range) .sum { |l| (l.end_date - l.start_date)/3600 } .round(2) end + + def checked_in? + log_action = ::ActsAsLoggable::UserAction.find_by_action("CHECKIN") + checked = logs.where( log_action_id: log_action.id). + where("start_date >= ?", Time.zone.now.beginning_of_day). + where("start_date = end_date") + !checked.empty? + end + + def checkin + log_action = ::ActsAsLoggable::UserAction.find_by_action("CHECKIN") + time = Time.now + logs.create( logger_id: self.id, + logger_type: self.class.to_s, + start_date: time, + end_date: time, + log_action_id: log_action.id, + log_action_type: log_action.class.to_s) + save + end + + def checkout + log_action = ::ActsAsLoggable::UserAction.find_by_action("CHECKIN") + checked = logs.where( log_action_id: log_action.id). + where("start_date >= ?", Time.zone.now.beginning_of_day). + where("start_date = end_date").first + checked.end_date = Time.now + checked.save + end end diff --git a/app/models/user_role.rb b/app/models/user_role.rb deleted file mode 100644 index 5a9452f..0000000 --- a/app/models/user_role.rb +++ /dev/null @@ -1,11 +0,0 @@ -class UserRole < ActiveRecord::Base - attr_accessible :role - - belongs_to :user - - self.per_page = 15 - - def to_s - self.role - end -end diff --git a/app/models/user_role_join.rb b/app/models/user_role_join.rb new file mode 100644 index 0000000..b1d285d --- /dev/null +++ b/app/models/user_role_join.rb @@ -0,0 +1,13 @@ +class UserRoleJoin < ActiveRecord::Base + self.table_name = :user_role_joins + attr_accessible :role_id, :user_id, :ends + + belongs_to :user + belongs_to :role + + validate :role_id, presence: true, numericality: true + validate :user_id, presence: true, numericality: true + validates_uniqueness_of :user_id, :scope => :role_id + + self.per_page = 15 +end diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb index 34db7fc..3f64071 100644 --- a/app/views/devise/sessions/new.html.erb +++ b/app/views/devise/sessions/new.html.erb @@ -1,6 +1,6 @@ <%= stylesheet_link_tag "bootstrap_and_overrides", :media => "all" %> -

Sign in

+

Velocipede

<%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>
<%= f.label :username%>
@@ -14,8 +14,15 @@ <% end -%>
<%= f.submit "Sign in" %>
+ + <% end %> + + <%= render "links" %> <% if Rails.env.development? %> diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb index e923b33..f8129db 100644 --- a/config/initializers/devise.rb +++ b/config/initializers/devise.rb @@ -38,12 +38,12 @@ Devise.setup do |config| # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. - config.case_insensitive_keys = [ :email ] + config.case_insensitive_keys = [ :username ] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. - config.strip_whitespace_keys = [ :email ] + config.strip_whitespace_keys = [ :username ] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the @@ -221,3 +221,9 @@ Devise.setup do |config| # manager.default_strategies(:scope => :user).unshift :some_external_strategy # end end + +#Check in the user if they sign in. (Devise uses Warden) +Warden::Manager.after_authentication do |user,auth,opts| + user.checkin unless user.checked_in? +end + diff --git a/config/routes.rb b/config/routes.rb index 31c9f6e..59ff145 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -4,4 +4,13 @@ Velocipede::Application.routes.draw do netzke root :to => 'site#index' + ########################### + # API Routes + scope 'api', :module => :api do + scope 'v1', :module => :v1 do + post 'checkin' => "logs#checkin", :as => "api_checkin" + post 'checkout' => "logs#checkout", :as => "api_checkout" + end + end + end diff --git a/db/migrate/20130423231937_alter_user_roles.rb b/db/migrate/20130423231937_alter_user_roles.rb new file mode 100644 index 0000000..329d470 --- /dev/null +++ b/db/migrate/20130423231937_alter_user_roles.rb @@ -0,0 +1,9 @@ +class AlterUserRoles < ActiveRecord::Migration + def change + rename_table :user_roles, :user_role_joins + change_table :user_role_joins do |t| + t.rename :role, :role_id + t.change :role_id, :integer + end + end +end diff --git a/db/migrate/20130423233228_add_roles.rb b/db/migrate/20130423233228_add_roles.rb new file mode 100644 index 0000000..f82f955 --- /dev/null +++ b/db/migrate/20130423233228_add_roles.rb @@ -0,0 +1,8 @@ +class AddRoles < ActiveRecord::Migration + def change + create_table(:roles) do |t| + t.string :role + t.timestamps + end + end +end diff --git a/db/migrate/20130424005701_alter_user.rb b/db/migrate/20130424005701_alter_user.rb new file mode 100644 index 0000000..510d717 --- /dev/null +++ b/db/migrate/20130424005701_alter_user.rb @@ -0,0 +1,5 @@ +class AlterUser < ActiveRecord::Migration + def change + remove_column :users, :user_role_id + end +end diff --git a/db/schema.rb b/db/schema.rb index c68d03e..6508b93 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -97,6 +97,12 @@ ActiveRecord::Schema.define(:version => 20130525143240) do add_index "logs", ["loggable_id", "loggable_type", "context"], :name => "index_logs_on_loggable_id_and_loggable_type_and_context" + create_table "roles", :force => true do |t| + t.string "role" + t.datetime "created_at", :null => false + t.datetime "updated_at", :null => false + end + create_table "task_lists", :force => true do |t| t.integer "item_id", :null => false t.string "item_type", :null => false @@ -148,10 +154,10 @@ ActiveRecord::Schema.define(:version => 20130525143240) do t.datetime "updated_at", :null => false end - create_table "user_roles", :force => true do |t| - t.string "role" - t.datetime "created_at", :null => false - t.datetime "updated_at", :null => false + create_table "user_role_joins", :force => true do |t| + t.integer "role_id", :limit => 255 + t.datetime "created_at", :null => false + t.datetime "updated_at", :null => false t.datetime "ends" t.integer "user_id" end @@ -167,7 +173,6 @@ ActiveRecord::Schema.define(:version => 20130525143240) do t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" - t.integer "user_role_id", :default => 1, :null => false t.integer "bike_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false diff --git a/db/seed/fixtures/acts_as_loggable/user_actions.yml b/db/seed/fixtures/acts_as_loggable/user_actions.yml index f3c3a18..f5e86f3 100644 --- a/db/seed/fixtures/acts_as_loggable/user_actions.yml +++ b/db/seed/fixtures/acts_as_loggable/user_actions.yml @@ -13,3 +13,8 @@ staff: action: STAFF created_at: <%= Time.now %> updated_at: <%= Time.now %> +checkin: + id: 4 + action: CHECKIN + created_at: <%= Time.now %> + updated_at: <%= Time.now %> diff --git a/db/seed/fixtures/roles.yml b/db/seed/fixtures/roles.yml new file mode 100644 index 0000000..46f26fc --- /dev/null +++ b/db/seed/fixtures/roles.yml @@ -0,0 +1,9 @@ +user: + id: 1 + role: user +staff: + id: 2 + role: staff +admin: + id: 3 + role: admin diff --git a/db/seeds.rb b/db/seeds.rb index 6d1f3c2..89a9000 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -21,7 +21,7 @@ end if Rails.env.development? #create default admin user - if UserRole.all.empty? and User.all.empty? + if User.all.empty? FactoryGirl.create(:user) FactoryGirl.create(:staff) FactoryGirl.create(:admin) diff --git a/spec/factories/user_roles.rb b/spec/factories/roles.rb similarity index 91% rename from spec/factories/user_roles.rb rename to spec/factories/roles.rb index ac4d2f3..97ae258 100644 --- a/spec/factories/user_roles.rb +++ b/spec/factories/roles.rb @@ -1,5 +1,5 @@ FactoryGirl.define do - factory :user_role do + factory :role do factory :role_staff do role 'staff' end diff --git a/spec/factories/users.rb b/spec/factories/users.rb index 6d01799..1ad7f21 100644 --- a/spec/factories/users.rb +++ b/spec/factories/users.rb @@ -7,24 +7,32 @@ FactoryGirl.define do first_name 'Michael' last_name 'Scott' sequence(:bike_id) { |n| n } - association :user_role, factory: :role_user + after_build do |r| + r.roles << (Role.find_by_role("user") || FactoryGirl.create(:role_user)) + end factory :staff do username "staff" first_name 'Staff' - association :user_role, factory: :role_staff + after_build do |r| + r.roles << (Role.find_by_role("staff") || FactoryGirl.create(:role_staff)) + end end factory :admin do username "admin" first_name 'Admin' - association :user_role, factory: :role_admin + after_build do |r| + r.roles << (Role.find_by_role("admin") || FactoryGirl.create(:role_admin)) + end end factory :bike_admin do username "bike_admin" first_name 'BikeAdmin' - association :user_role, factory: :role_bike_admin + after_build do |r| + r.roles << (Role.find_by_role("bike_admin") || FactoryGirl.create(:role_bike_admin)) + end end end