Advertisement
Guest User

Untitled

a guest
Jun 30th, 2016
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 12.75 KB | None | 0 0
  1. module Api
  2.   class AdminController < Api::BaseController
  3.  
  4.     #before_filter :authenticate_user!
  5.  
  6.     include ApplicationHelper
  7.  
  8.     def get_users
  9.  
  10.       render json: { data: Users.all }
  11.     end
  12.  
  13.     def list_users
  14.       authorize! :admin, :message => 'Not authorized as an administrator.'
  15.  
  16.       users = Array.new
  17.  
  18.       User.all.each do |user|
  19.         roles = Array.new
  20.  
  21.       if user.visibility_class == "Group"
  22.         user["location"] = LocationGroup.where(:location_group_id => user.visibility_id).only(:name).first()
  23.       end
  24.  
  25.       if user.visibility_class == "Location"
  26.         user["location"] = Location.where(:location_id => user.visibility_id).only(:name).first()
  27.       end
  28.  
  29.         if(!user['role_ids'].nil?)
  30.           user['role_ids'].each do |r|
  31.             role = Role.find(r) rescue nil
  32.             if(!role.nil?)
  33.               roles.push ({ id: role.id, name: role.name })
  34.             end
  35.           end
  36.           user['role_ids'] = roles
  37.         else
  38.           user['role_ids'] = []
  39.         end
  40.         users.push user
  41.       end
  42.  
  43.       render json: { data: users }
  44.     end
  45.  
  46.     def add_user
  47.       @user = User.new
  48.     end
  49.    
  50.  
  51.     def create_user
  52.       authorize! :admin, :message => 'Not authorized as an administrator.'
  53.       email = params["user"]["email"]
  54.       generated_password = Devise.friendly_token.first(12)
  55.  
  56.       begin
  57.         default_widgets_setting = Setting.where(:name => 'default_widgets').first
  58.         if !default_widgets_setting.nil?
  59.           default_widgets = default_widgets_setting.value
  60.         end
  61.         user = User.create!(:email => email, :password => generated_password, :widget_control => default_widgets)
  62.         #RegistrationMailer.welcome(user, generated_password).deliver
  63.        
  64.         render json: { status: :success, message: 'User was successfully created. Generated Password: ' + generated_password  }
  65.       rescue Exception => e1
  66.         render json: { status: :error, message: 'User create Exception.' }
  67.       end
  68.     end
  69.  
  70.     def update_user
  71.       user = params[:user]
  72.  
  73.       if user[:email] != @current_user[:email]
  74.         render json: { error: 'Unauthorized'} , status: :unauthorized
  75.         return
  76.       else
  77.  
  78.         @userUpdated = User.where(email: user[:email]).first  rescue nil
  79.        
  80.         if(@userUpdated.nil?)
  81.           render json: {
  82.               errors: {
  83.                    global: ['User is not available']
  84.               }
  85.           }, status: :unprocessable_entity
  86.           return
  87.         end
  88.  
  89.         if(!user[:current_password].blank?)
  90.           if(@userUpdated.password != user[:current_password])
  91.             render json: {
  92.                 errors: {
  93.                      global: ['Incorrect current password']
  94.                 }
  95.             }, status: :unprocessable_entity
  96.             return
  97.           end
  98.  
  99.           if(user[:password] == user[:current_password])
  100.             render json: {
  101.                 errors: {
  102.                     global: ['The new password cannot be the same of the current.']
  103.                 }
  104.             }, status: :unprocessable_entity
  105.             return
  106.           end
  107.  
  108.           if(user[:password].blank?)
  109.             render json: {
  110.                 errors: {
  111.                      global: ['Please fill the required field to change passwords']
  112.                 }
  113.             }, status: :unprocessable_entity
  114.             return
  115.           end
  116.  
  117.           if(user[:password] != user[:password_confirmation])
  118.             render json: {
  119.                 errors: {
  120.                      global: ['Password confirmation failed']
  121.                 }
  122.             }, status: :unprocessable_entity
  123.             return
  124.           end
  125.  
  126.           @userUpdated.password = user[:password]
  127.         end
  128.  
  129.         @userUpdated[:widget_control] = user[:widget_control]
  130.  
  131.         if @userUpdated.save
  132.           render json: { status: 'success', user: @userUpdated }
  133.           return
  134.         else
  135.           render json: {
  136.                 errors: {
  137.                      global: ['User failed to update']
  138.                 }
  139.             }, status: :unprocessable_entity
  140.           return
  141.         end
  142.       end
  143.     end
  144.  
  145.     def assign_location_user
  146.       #@users = User.all
  147.       user = User.find(params["user_id"])
  148.       user.visibility_class = params["visibility_class"]
  149.       user.visibility_id = params["visibility_id"]
  150.  
  151.       if user.save
  152.         render json: { status: 'success' }
  153.       else
  154.         render json: { status: 'error' }
  155.       end
  156.     end
  157.  
  158.     def get_user
  159.       @user = User.find(params["userId"])
  160.  
  161.       if !@user.nil?
  162.         render json: { status: 'success', user: @user }
  163.       else
  164.         render json: { status: 'error', message: 'User not found' }
  165.       end
  166.     end
  167.  
  168.     def add_user_role
  169.       target_role = params[:role]
  170.       user = User.find(params[:id])
  171.  
  172.       if !target_role.nil? && target_role == 'executive'
  173.         user.add_role :executive
  174.       end
  175.       if !target_role.nil? && target_role == 'admin'
  176.         user.add_role :admin
  177.       end
  178.       if !target_role.nil? && target_role == 'manager'
  179.         user.add_role :manager
  180.       end
  181.       if !target_role.nil? && target_role == 'publisher'
  182.         user.add_role :publisher
  183.       end
  184.       if !target_role.nil? && target_role == 'content creator'
  185.         user.add_role :content_creator
  186.       end
  187.       if !target_role.nil? && target_role == 'content approver'
  188.         user.add_role :content_approver
  189.       end
  190.  
  191.       user.save
  192.       render json: { status: 'success' }
  193.     end
  194.  
  195.     def remove_user_role
  196.       target_role = params[:role]
  197.       user = User.find(params[:id])
  198.  
  199.       if !target_role.nil? && target_role == 'executive'
  200.         user.remove_role :executive
  201.       end
  202.       if !target_role.nil? && target_role == 'admin'
  203.         user.remove_role :admin
  204.       end
  205.       if !target_role.nil? && target_role == 'manager'
  206.         user.remove_role :manager
  207.       end
  208.       if !target_role.nil? && target_role == 'publisher'
  209.         user.remove_role :publisher
  210.       end
  211.       if !target_role.nil? && target_role == 'content creator'
  212.         user.remove_role :content_creator
  213.       end
  214.       if !target_role.nil? && target_role == 'content approver'
  215.         user.remove_role :content_approver
  216.       end
  217.  
  218.       user.save
  219.       render json: { status: 'success' }
  220.     end
  221.  
  222.     def remove_user
  223.       user = User.find(params[:id])
  224.       if user == @current_user
  225.         render json: { status: 'error', message: 'Unable to delete currently logged in user.' }
  226.       else
  227.         user.remove
  228.         render json: { status: 'success' }
  229.       end
  230.     end
  231.  
  232.     def remote_status
  233.       eyeq = Mongoid::Sessions.with_name(:core_data)
  234.       coll = eyeq["remote_checks"]
  235.       ds = coll.aggregate(
  236.           {"$group" => {
  237.               _id: {
  238.                   "loc_id" => "$loc_id",
  239.                   "place_id" => "$place_id",
  240.                   "mac" => "$mac",
  241.                   "e_ip" => "$e_ip",
  242.                   "i_ip" => "$i_ip",
  243.                   "hostname" => "$hostname"},
  244.               capture_time: {"$max" => "$capture_time" }}},
  245.           {"$sort" => {"capture_time" => -1}},
  246.           {"$group" => {
  247.               _id: {
  248.                   "loc_id" => "$_id.loc_id",
  249.                   "place_id" => "$_id.place_id"},
  250.               "mac" => {"$first" => "$_id.mac"},
  251.               "e_ip" => {"$first" => "$_id.e_ip"},
  252.               "i_ip" => {"$first" => "$_id.i_ip"},
  253.               "hostname" => {"$first" => "$_id.hostname"},
  254.               "capture_time" => {"$first" => "$capture_time"}}},
  255.           {"$sort" => {"_id.loc_id" => 1, "_id.place_id" => 1}}
  256.       )
  257.  
  258.       @remote_devices = Array.new
  259.       ds.each do |r|
  260.         placement = Placement.where(:placement_id => r["_id"]["place_id"]).first
  261.         if !placement.nil?
  262.           location = Location.where(:location_id => placement.location_id).first
  263.           if !r["capture_time"].nil?
  264.             last_ts = r["capture_time"].in_time_zone('America/Chicago')
  265.           else
  266.             last_ts = nil
  267.           end
  268.           device = {
  269.               :capture_time => last_ts,
  270.               :trafficmap => get_last_timestamp(placement.placement_id, "trafficmap_all"),
  271.               :demographics => get_last_timestamp(placement.placement_id, "demographics"),
  272.               :engage => get_last_timestamp(placement.placement_id, "engagements"),
  273.               :feedbacks => get_last_timestamp(placement.placement_id, "feedbacks"),
  274.               :location => location.label + ' [' + location.location_id.to_s + ']',
  275.               :location_active => location.active,
  276.               :placement => placement.label + ' [' + placement.placement_id.to_s + ']',
  277.               :placement_active => placement.active,
  278.               :hostname => r["hostname"],
  279.               :external_ip => r["e_ip"],
  280.               :internal_ip => r["i_ip"],
  281.               :wlan_mac => r["mac"],
  282.               :location_id => location,
  283.               :placement_id => placement,
  284.           }
  285.           @remote_devices.push(device)
  286.  
  287.          
  288.         end
  289.       end
  290.  
  291.       render json:  { remote_devices: @remote_devices }
  292.     end
  293.  
  294.     def get_last_timestamp(place_id, collection_name)
  295.       eyeq = Mongoid::Sessions.with_name(:core_data)
  296.       coll = eyeq[collection_name]
  297.       ds = coll.find({"place_id"=>place_id}).sort({"local_time"=>-1}).limit(1)
  298.       timestamp = ds.first
  299.       if !timestamp.nil? && !timestamp["capture_time"].nil?
  300.         return timestamp["capture_time"].in_time_zone('America/Chicago')
  301.       else
  302.         return nil
  303.       end
  304.     end
  305.  
  306.     def mac_history
  307.  
  308.       #access other database
  309.       @start_date = GetStartDate(session['start_date'], params[:start_date])
  310.       session['start_date'] = @start_date
  311.       @end_date = GetAnyDate(session['end_date'], params[:end_date])
  312.       session['end_date'] = @end_date
  313.       @l_id_list = GetLocationList()
  314.  
  315.  
  316.       default_login_location = 0;
  317.  
  318.       @l_id_list.each do |item|
  319.         default_login_location = item[1]
  320.         break
  321.       end
  322.  
  323.       #(@l_id_list.count > 0) ? @l_id_list[0][1] : 1
  324.       @l_id = GetParamSessionValues(session['l_id'], params[:l_id], default_login_location)
  325.       session['l_id'] = @l_id
  326.  
  327.       macaddr = params[:mac]
  328.       eyeq = Mongoid::Sessions.with_name(:core_data)
  329.       coll = eyeq["remote_checks"]
  330.  
  331.       #db.remote_checks.find({"mac": /^c8:f7:33:ed:4d:ec$/i}).sort({"capture_time":1}).limit(100)
  332.       @mac_history = coll.find({
  333.                                    mac: macaddr,
  334.                                    local_time: {
  335.                                        "$gte" => DateToTime(@start_date),
  336.                                        "$lt" => AddaDay(DateToTime(@end_date))}}
  337.       ).sort({"capture_time" => -1}).limit(10)
  338.  
  339.       ds_mac_by_hour = coll.aggregate(
  340.           {"$match" => {
  341.               mac: macaddr,
  342.               local_time: {
  343.                   "$gte" => DateToTime(@start_date),
  344.                   "$lt" => AddaDay(DateToTime(@end_date))}
  345.           }},
  346.           {"$group" => {
  347.               _id:{
  348.                   "p_year" => {"$year" => "$local_time"},
  349.                   "p_month" => {"$month" => "$local_time"},
  350.                   "p_day" => {"$dayOfMonth" => "$local_time"},
  351.                   "p_hour" => {"$hour" => "$local_time"},
  352.               },
  353.               row_count:{"$sum" => 1}
  354.           }},
  355.           {"$sort" => {"_id.p_year" => 1, "_id.p_month" => 1, "_id.p_day" => 1, "_id.p_hour" => 1}}
  356.       )
  357.  
  358.       #mac_by_hour_table = GoogleVisualr::DataTable.new
  359.       mac_by_hour_table = Array.new
  360.       #mac_by_hour_table.new_column('datetime', 'Hour' )
  361.       #mac_by_hour_table.new_column('number', 'MAC Count')
  362.  
  363.       ds_mac_by_hour.each do |d|
  364.         row_count = d["row_count"]
  365.         time = Time.new(d["_id"]["p_year"], d["_id"]["p_month"], d["_id"]["p_day"], d["_id"]["p_hour"], 0, 0, '+00:00')
  366.         mac_by_hour_table.push([time, row_count])
  367.       end
  368.    
  369.       render json: { devices: mac_by_hour_table, mac_history: @mac_history }, root: false
  370.     end
  371.  
  372.     def get_visibility_by_id
  373.       visibilityClass = params["visibility_class"]
  374.  
  375.       if visibilityClass == "Group"
  376.         location = Location.where(:location_id => params["visibility_id"])
  377.       end
  378.  
  379.       if visibilityClass == "Location"
  380.         location = LocationGroup.where(:location_id => params["visibility_id"])
  381.       end
  382.  
  383.       render json: { data: location }, root: false
  384.     end
  385.  
  386.     def manage_widgets
  387.       default_widgets_setting = Setting.where(:name => 'default_widgets').first
  388.       if (!default_widgets_setting.nil?)
  389.         @widget_control = JSON.parse(default_widgets_setting.value)
  390.       else
  391.         @widget_control = JSON.parse('{}')
  392.       end
  393.  
  394.       render json: { data: @widget_control }, root: false
  395.     end
  396.   end
  397. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement