implement devise-like "current_user" method in RubyMotion App - ios

I am an Objective C noob and learning to build apps with RubyMotion.
I want to be able to call current_user and get the currently logged in user to my app.
Right now I am sending the current_user record from the server and calling User.new(:user) when a user logs in, but I can't call this user globally the way I'd like to, and send it into a Formotion edit form, etc
Right now I am initializing models using the KVO as described in the ruby tutorial Should I implement MotionModel? How would I use that tool to get that ready-at-hand current_user method?
Thanks!

I usually use a class method in the user model.
User.current_user
Your user class:
class User
def self.current_user
#current_user ||= begin
# get your user here, using BubbleWrap's App::Persistence or another persistence mechanism.
end
end
end

One way would be to send the current_user's id back with the login response, then store it in
App::Persistence['currentUserId']
Then when you call the user detail controller create a custom "initWithId" method that takes the id as an argument.
UserDetailController.alloc.initWithId(App::Persistence['currentUserId'])

Related

How the replacement of auth_token field is working in below scenario

class User < ActiveRecord::Base
def facebook
#facebook ||= Koala::Facebook::API.new(oauth_token)
end
end
In the rails console
user = User.first
user.facebook.get_object("me")
First question is, User model has a column called oauth_token, which is magically getting replaced in Koala::Facebook::API.new(oauth_token) here, even though I am not passing oauth_token explicitly
Second question, what is the need of caching #facebook variable here? I am following this rails casts tutorial
https://www.youtube.com/watch?v=JqeZy2G2C1g
#First question
What do you mean by getting replaced?
From what I see when initializing API (API.new(oauth_token)) you are passing ouath_token that is assigned to specific user. When calling User.first you're loading first user from database, and ActiveRecord automatically assigns oauth_token to newly created instance. If ouath_token was never saved (thus present in db record) it would be nil.
#Second question
This is in general done for performance reasons in order to avoid multiple API calls within same request. However, usually response from API call is cached not the API instance itself. Maybe that Koala API instance calls webservice directly in constructor (in its initialize method).
My note - keeping such methods like facebook calling external webservice within User model ends with very difficult to change code.
It's better to move it somewhere out from this model.

How can I find a devise user by it's session id?

Given session["session_id"] is it possible to find the logged in User to which that session belongs to?
At least on my system (rails 3.2, devise 2.0.4), you can do it like this:
session is:
{"session_id"=>"be02f27d504672bab3408a0ccf5c1db5", "_csrf_token"=>"DKaCNX3/DMloaCHbVSNq33NJjYIg51X0z/p2T1VRzfY=", "warden.user.user.key"=>["User", [3], "$2a$10$5HFWNuz5p6fT3Z4ZvJfQq."]}
session["warden.user.user.key"][1][0], then is 3.
So, I'd find it as:
User.find(session["warden.user.user.key"][1][0])
I'm not sure what you are trying to accomplish but will try to answer
If you want only the User from the current session, a simple way would be to store his id on session, for example:
def login(username, pass)
# do the usual authentication stuff and get user
if logedin
session[:user_id] = user.id
end
end
Then get the current user would be something like
current_user =User.find(session[:user_id])
If what you want is finding all the users that are currently logged in, I think you need to config your app to save session at DB, because predefined is that session data is store in cookies in the browser. For more information on this check this answer
How to track online users in Rails?
EDIT: Just noticed you are using devise so the first way is actually there for you. You just need to call current_user method at any controller.
For the second way check this answer "Who's Online" using Devise in Rails
And i might add this, as i was trying to do it the other way, if you are using ActiveRecord session_store you can find all stored sessions of a user like so:
ActiveRecord::SessionStore::Session.select{ |s| s.data["warden.user.user.key"] && s.data["warden.user.user.key"][0][0] == user_id }

Ruby on Rails - Submitting Form Data Directly to a Session Variable

I have spent hours trying to find a resource that explains the process of submitting form data directly to a session variable, but I have had no luck finding anything!
Essentially I am not wanting to store the data in the database when the user submits in this particular form, I just want it to be assigned to the session[:member_pin] variable when the user submits the form, so I can then check if the pin they entered matches the pin on the members database record.
Please let me know if you need anymore clarification for what I am trying to do, and thank you so much for your help!
You don't have to save the data to database every time a form is submitted. In your controller 's action, get the params you want and store them in the session. Eg.,
def some_action
session[:user_id] = User.find_by_pin(params[:pin]) if params[:pin]
end
Then in your application controller, make a helper method like this. Then you should be able to access "current_user" method in your views. (It will be nil if you haven't got any user verified with pins.
def current_user
User.find(session[:user_id]) if session[:user_id].present?
end
maybe something like this in your controller method:
session[:member_pin] = params[:member_pin_input_name]

Authlogic and Single Access Token

I am having a hard time finding a simple tutorial on how to enable single access token authentication using authlogic. There is some documentation but it isn't very helpful.
I added single_access_token to my db, I added this:
single_access_allowed_request_types :any
to my Session class. but I still don't understand how a user is authenticated using the credentials param that is passed over every call. My require_authentication before filter does a standard check for current_user like this:
def current_session
return #current_session if #current_session
#current_session = Session.find
end
def current_user
#current_user = current_session && current_session.record
end
But is that enough to work? Does the Session.find method do the magic to log the user is based on my params or do I have to create separate method that actually check if the user_credentials param is there and then find the user based on it and then log that user in. I am confused if I really am "creating" a new session everytime I use a SAT or if I'm just setting current user in a before filter every time an API call is made.
Any help would be amazing! Thanks!
I implemented a single_access_token solution with authlogic and what I had to do was add single_access_allowed_request_types :all to the UserSession model.
Then I added the following to the controller where I wanted to allow single_access_token authentication.
def single_access_allowed?
["some_action_1","some_action_2","some_action_3"].include?(action_name)
end
It looks like you're missing the controller code. So if you had two actions "get_user_info" and "update_user_info" you would add.
def single_access_allowed?
["get_user_info","update_user_info"].include?(action_name)
end
The only thing I had to do make this work was
add a field called single_access_token to my users-table
add a method called single_access_allowed? to each controller where single access should be allowed.
This method would look like this:
# method for authlogic: defines for which action the single-access-token can be used
def single_access_allowed?
(action_name == "deliver") || (action_name == "delivery_status")
end
I did not have to add anything in UserSessionsController or the UserSession object. Authlogic handles that for you. With a single-access-token only one request is authenticated, so there is not a persistent session. Each request has to send the single-access-token. Hence the name: a token to get a single access :)
Hope this helps.
The source code of authlogic is the best documentation on the single access token. This is the specific section that discusses it.
You will need to add a private method called single_access_allowed? in the controller where you are trying to let users access. The Single Access Token is passed by default as a URL encoded parameter using the name user_credentials. So to hit your controller without logging in it will be /your_route/?user_credentials=xxxxxx

Rails 3 - logging in a user automatically after creating the account

In my users_controller I have two methods signup_process and login. I would like to call login automatically for a user after a successful signup_process call.
Is this possible? In other language frameworks I would usually just call the login controller action direct from the signup_process action passing the username and password - but I think that is frowned upon in Rails.
Is there some way instead to post the user data to the users.login action from my controller?
This must be a common pattern - what am I missing? :)
Thanks in advance!
Not sure what you mean by frowned upon, but here's one way
class UsersController < ...
def signup
// Do some stuff
do_login(username, password)
// render or redirect as you wish
end
def login
do_login(username,password)
// render or redirect as you wish
end
private
def do_login(username,password)
// do the actual login processing
// can even render or redirect here if it's common to both setup and login
end
end
Would that do what you want?
Well, what does the login action do?
Most likely, it sets something in the session indicating the user is logged in. You could do just that, after creating the user.
It does not make sense to call a controller action, since it's most likely hooked up with a view/form.
Please provide more information on what the login action does, if you still feel like you need to go through it.

Resources