How to track if user make any actions Rails app - ruby-on-rails

I'm creating app with lessons/tests after it and right now I need to create a report card with some information. I want to add column to Users which will track time spent online(without idle time). For example student is pressing any buttons on site(just for example), it means that student is online and the (current_user.online_time should not stop), but if student did nothing more than 5 minutes - (current_user.online_time should stop). I found a gem devise lastseenable, but can't imagine right know how to make it work according to my wishes. Gem tracks when U did any actions only with User(create/update/delete/ or with models which belongs to user), without tracking any other moves. Can someone give me any ideas?

It is certainly possible to put together a simple user tracking feature without using an external gem specifically built for this purpose. Here is a list of the required implementation steps:
1. Add a total_time_online and a last_seen_at field to User
total_time_online will contain the number of seconds the user was seen online
last_seen_at will hold the date and time the user last interacted with the site
2. Add an active_now! method to User
This method will be called whenever the user is interacting with the site. It is responsible for incrementing the total_time_online value and updating the last_seen_at field:
class User
ActivityThreshold = 5.minutes
# ...
def active_now!
time_since_last_activity = [Time.now - last_seen_at, 0].max
if time_since_last_activity <= ActivityThreshold
self.total_time_online ||= 0
self.total_time_online += time_since_last_activity
end
self.last_seen_at = Time.now
save!
end
# ...
end
This will only increment the total_time_online if the last interaction was less than 5 minutes ago.
3. Call active_now! on the current user on every request
A global before_action should do the trick:
class ApplicationController < ActionController::Base
# ...
before_action :record_user_activity
# ...
private
# ...
def record_user_activity
current_user.active_now! if current_user
end
end

Related

Ruby on Rails devise, how to put a limit on how often a user can change their username

`I have recently started working on a rails app and using devise as authentication. but I have ran into a wall. I would like to know if there's a way to set a period limit on how often a user may update their username. For example, if a User update their username today, they shouldn't be able to update it again until a 30day period has passed.
I have looked through devise docs, but nothing address that functionality, I have also search SO and the web but to no avail.
Any help would be very much be appreciated on how to go about it, or at least be pointed in the right direction. Thanks in advance!
I have added to the user model
after_save :name_last_updated
def name_last_updated
if self.username_changed?
self.name_last_updated_at = Time.now
end
but this does not update the colunm name_last_updated_at. any clues of what i am doing wrong will be helpful ^^ thanks!
so, after messing around with a few codes i figured an alternative way to go about this. I created a new column to track new time the user should be able to see the form to update his username.
def username_next_update
self.username_next_update_at = self.username_last_update_at + 2.minutes
end
for learning and testing purposes i added +2.minutes
and i did a before_save on it.
In my view i wrapped it around an if and else statement although i am quite confuse with the logic.
<% if current_user.username_next_update_at < time.zone.now %>
********
<% end %>
but i expected to it to work only if it was > sign instead of <. any tips will be helpful or any better alternatives :)
You need to create it from scratch.
Create a new column in the users table, call it name_last_updated, when the user updates their name for the first time, set that column to today's date. then every time a user wants to update their name, check that column and compare with today's date and see if 30 days have passed:
if Date.today - user.name_last_update < 30
#display error
end
We can use user updated_at column created by the devise gem and add a callback method in the user model to make sure that we call this method every time the user model is updated.
before_update { |user| user.write_attribute if user.is_permitted? }
def write_attribute
self.user_name = params[:user][:user_name]
end
def is_permitted?
if self.username_changed?
Date.today - updated_at < 30
end
end
You should use the before_update and specify which record has to activate the callback instead of using after_save.
I would do something like this:
before_update :name_last_updated, if: :username_changed?
def name_last_updated
if (self.name_last_updated_at.to_date + 30.days) < Date.today
self.update(name_last_updated_at: Time.now)
end
end

Ruby on Rails: What is the convention (is there one?) for creating a model instance programmatically

I have a model: 'event' and it has a controller: 'event_controller'
The event_controller handles the following route: events/:id/complete_event
In the controller, I need to trigger the creation a couple other model objects in the system, which are calculated and not inputted via a web form.
In this case the models to create are:
score (which belongs_to: user and event)
stats (which belongs_to: event)
standing (which belongs_to: user | and is based on the new score/stats object)
What is the convention for this type of model creation for Ruby on Rails?
Is it okay for the event_controller to create these (somewhat unrelated) model objects?
or,
Should the event_controller call into the score_controller, stats_controller and standing_controller?
With the second option, I am concerned that it will not work to dispatch 2-3 routes in a chain to create all the objects in their corresponding controllers but is that is the convention.
In the end, it's ideal to redirect the user back to show_event view, which will display the event and its associated scores and stats objects.
Code for the event_controller method: complete_event
def complete_event
event = Event.find(params[:id])
if event.in_progress?
event.complete!
end
# 1. create score for each user in event.users
# 2. create stats for the event
# 3. update the overall standings for each score (per user)
redirect_to event
end
As you can see, the event is not being creating on this action, rather the event state is updated to 'complete' this is the trigger to create the associated records.
The commented lines above represent what I need to do after event is complete; I am just not sure that this is where I go ahead and directly create the objects.
E.g. To create score will I have to calculate a lot of data that starts in event, but uses many models to get all the relevant data to create it.
You can move the whole logic out of controller so what i can understand when you call even.completed! you need to create score for users and update the over all ratings. So add call back in your model after_update is_event_completed! assuming evet.completed! will mark the event complete at db level. Then just place the corresponding logic in your model. It's the best practice to place your business logic into your model. Here is a nice gem to manage states of a model github.com/pluginaweek/state_machine and do specific stuff on specific events.
It feels to me that all the steps are part of completing an event, therefore I think it belongs into the Event#complete! method.
# in the controller
def complete_event
event = Event.find(params[:id])
event.complete! if event.in_progress?
redirect_to event
end
# in the model
def complete!
# complete event
# 1. create score for each user in event.users
# 2. create stats for the event
# 3. update the overall standings for each score (per user)
end
Or you could use a small Ruby class that performs the completion:
# in the controller
def complete_event
event = Event.find(params[:id])
EventCompleter.new(event).perform
redirect_to event
end
# in models/event_completer.rb
class EventCompleter < Struct.new(:event)
def perform
event.complete!
# 1. create score for each user in event.users
# 2. create stats for the event
# 3. update the overall standings for each score (per user)
end
end
The second seems a bit too complex for this simple example, but is an interesting pattern for more complex tasks. Main benefit is that this simple Ruby class encapsulates all business and domain logic that need to be done, when completing an event (this logic doesn't not really belong to events). And it it easier to test.

How to use the new ActiveSupport::Testing::TimeHelpers inside controller

Edit to make it more clear
Like the title tells how to use the awesome ActiveSupport::Testing::TimeHelpers#travel_to method inside my controller. Like in tests, I want to achieve something like this:
SomethingConroller < ApplicationController
def index
travel_to some_date do
# some stuff that it depends on the current_date
end
end
end
Tried include the module:
include ActiveSupport::Testing::TimeHelpers
but I got:
uninitialized constant ActiveSupport::Testing
Hoping that the date traveled to will be applied to the view, view_helpers, controller_action
If you must, then add require 'active_support/testing/time_helpers' at the top of the file.
Although I've no idea what you're doing with that code. Try this instead:
SomethingConroller < ApplicationController
def index
#instance = SomeModel.find_by_date(12.days.ago)
end
end
I think you're messing up your concepts here. You should use time travel to put tests in a certain time so that you can test a scenario at that new time. For example, lets say users have to renew their subscription after one year.
create the user(now).
travel to the time a year from now
Make sure that when the user logs in at travelled to time they are duly notified.
To manipulate date for queries, use 12.days.ago, 12.days.from_now, this can be used with seconds,days, minutes, years

Create a logic captcha from scratch

I haven't touched a scrap of code yet, but here's my thoughts on how to do this:
Create a :interactions entry in my session hash. This will contain an array of time stamps. Every time a user goes through any action, the time they did this will be appended to the :interactions entry. The array will be initialized in my sessions controller, and timestamps appended to it via a filter in my application controller:
class SessionsController < ApplicationController
def create
create_session
session[:interactions] = []
end
end
class ApplicationController < ActionController::Base
after_action :log_time
private
def log_time
session[:interactions] << Time.now.to_i
end
end
Then, create another action in my application controller, the one tasked with launching the recaptcha if the user's behaviour is suspicious. All it does is see when we have 20 entries in our session[:interactions] array, find out the time elapsed between each pair of consecutive entries, and then find the average time elapsed between these interactions. If the average time is under two minutes, the recaptcha is launched. The session[interactions] array is then reset.
class ApplicationController < ActionController::Base
after_action :log_time
before_action :launch_captcha
private
def launch_captcha
if session[:interactions].length == 20
elapsed = []
session[:interactions].each_slice(2) do |a, b|
elapsed << b - a
end
total = elapsed.inject(:+)
average = total / 20
if total < 120
# this a part I'm really not sure how to do:
# various instance variables should be populated here
redirect_to 'application/launch_captcha.html.erb'
end
session[:interactions] = []
end
end
def log_time
session[:interactions] << Time.now
end
end
Now, the fact the session[:interactions] is reset may be a bit of a weakness; all bets are off for those twenty interactions. But I want to build on the above logic, maybe add session[:captchas_sent], to the session hash (or even have captchas_sent as a column and save it to the user's record), and if the session[:captchas_sent] is x amount or y amount, warnings or temporary bans could come into effect.
What are your thoughts on the above way of monitoring user behaviour?
Here's where my knowledge of rails is starting to break down though. Once I've redirected the user to the recaptcha page, how should I proceed? I have two tables, questions and answers with a has_many belongs_to relationship between them respectively.
So a random question will come from my questions table, and then I'll have a form that pertains to an answer. It will be an ajax form, and have just one field, a text field for the answer. The action the form links to, human test, will see if the answer given is equal to one of the question's answers. But how should the question's id be passed into this action? It couldn't be a simple hidden field, because once the spammer knows the answer to one question, his script could always set the id to that one question. So the params hash or the sessions hash maybe? I need some advice here guys.
I also don't really know how the human test method should proceed once the it finds the user's answer is equal to one of the question's answers:
Let's say the user is submitting a comment. They fill in the comment, hit the submit button, the launch_captcha action kicks in, and redirects them to 'application/launch_captcha.html.erb'. What has happened to the data in the comment create form? Once they've answered the captcha correctly, how should the human_test method proceed? How could it go on to submit their comment as usual? I just don't know how to do that...I need to create an action that is called before the create action of a form...and..argh I just don't know. Help guys!

Rails: how to show user's "last seen at" time?

I'm using devise which stores current_sign_in_at and last_sign_in_at datetimes.
But lets say a user logged in a month ago but last viewed a page 5 minutes ago?
Is there a way I can display that ("User last seen 5 minutes ago").
How about this:
Create a migration to add a new field to users to store the date and time the user was last seen:
rails g migration add_last_seen_at_to_users last_seen_at:datetime
Add a before action callback to your application controller:
before_action :set_last_seen_at, if: proc { user_signed_in? }
private
def set_last_seen_at
current_user.update_attribute(:last_seen_at, Time.current)
end
This way, on every request (i.e. activity) that the current user performs, his/her last seen at attribute is updated to the current time.
Please note, however, that this may take up some of your app's resources if you have many users who are logged in, because this will execute before every controller action requested by someone who is logged in.
If performance is a concern, consider adding the following throttle mechanism to step 2 (in this example, throttling at 15 minutes):
before_action :set_last_seen_at, if: proc { user_signed_in? && (session[:last_seen_at] == nil || session[:last_seen_at] < 15.minutes.ago) }
private
def set_last_seen_at
current_user.update_attribute(:last_seen_at, Time.current)
session[:last_seen_at] = Time.current
end
To improve performance of the previous answer:
don't use session, as user already loaded with warden and all the attributes are accessible
update_attribute runs callbacks and updates updated_at attribute, and update_column not
to improve performance, better to use background workers, like ActiveJob/Resque/Sidekiq
to prevent from the high DB locking, better to create a seperate table, associated with users table, and write accesses there
Updated code:
before_action :set_last_seen_at, if: proc { user_signed_in? && (user.last_seen_at.nil? || user.last_seen_at < 15.minutes.ago) }
private
def set_last_seen_at
current_user.update_column(:last_seen_at, Time.now)
end
Devise plugin makes similar behaviour happen (just last seen, without optimizations): https://github.com/ctide/devise_lastseenable

Resources