Non-expiring sessions in Padrino - session-state

I've made a Padrino app that has one single password for accessing the admin page. I'm using the following helpers for the authorization.
# Check if the user is authenticated.
def authenticated?(opts = {})
if session["cooly"] != options.session_secret
redirect url(opts[:send_to] || :login)
end
end
# Create a new session.
def authenticate!
session["cooly"] ||= 0
session["cooly"] = options.session_secret
end
Write now, when I exit my browser, the session goes away and I have to login again. How do I keep the session?

Make sure you have the in your app session_secret
set :session_secret, 'fc29ce0f33f0c8cde13f3'

The answer was to make non-expiring cookies.
# Check if the user is authenticated.
def authenticated?(opts = {})
if session["cooly"] == options.session_secret || request.cookies["cooly"] == options.session_secret
return true
else
redirect url(opts[:send_to] || :login)
end
end
# Create a new session.
def authenticate!
session["cooly"] ||= 0
session["cooly"] = options.session_secret
expiration_date = 10.year.from_now
response.set_cookie('cooly', :value => options.session_secret, :expires => expiration_date)
end

Check out: https://gist.github.com/977690 and that should resolve the issue.

Related

Perl catalyst controller redirect not working

I have looked over this code and I can not understand the weirdness it exhibits. For a lack of understanding all I know
$c->res->redirect('qbo/home');
is being ignored, in favor of the redirect in the following if else condition. In other words, I always end up at the OAuthentication website.
If I block comment out the else condition I end up where I want to go qbo/home
sub index :Path :Args(0) {
my ($self, $c) = #_;
# Check to see if we have QBO::OAuth object in our user's session
# Create new object in session if we don't already have one
if(!($c->session->{qbo})) {
$c->log->info('Creating QBO::OAuth, save in user session');
$c->session->{qbo} = QBO::OAuth->new(
consumer_key => 'qyprddKpLkOclitN3cJCJno1fV5NzcT',
consumer_secret => 'ahwpSghVOzA142qOepNHoujyuHQFDbEzeGbZjEs3sPIc',
);
}
# Now we set our object variable to the session old or new
my $qbo = $c->session->{qbo};
######### GOTO 'qbo/home' ##########
$c->res->redirect('qbo/home');
####################################
if($c->req->params->{oauth_token}) {
$c->log->info('Now Redirect to access_endpoint');
# Get realmId and save it to our QBO::OAuth object in user session
$qbo->realmId($c->req->params->{realmId});
# Call QBO::OAuth->request_access_token
my $r = $qbo->request_access_token($c->req->params->{oauth_verifier});
$c->res->redirect('qbo/home');
} else {
my $callback = 'http://www.example.com/qbo';
# Request a token
my $r = $qbo->request_token($callback);
if($qbo->has_token) {
#Continue on down, Redirect to auth_user_endpoint
$c->res->redirect($qbo->auth_user_endpoint . '?oauth_token=' . $qbo->token);
}
}
}
Seems I am missing some basic fundamental about how this works. Any clues appreciated
From the fine manual...
This is a convenience method that sets the Location header to the redirect destination, and then sets the response status. You will want to return or $c->detach() to interrupt the normal processing flow if you want the redirect to occur straight away.
Note also the warning on that manual page about redirecting to a relative URL - you shouldn't do it. For your use-case, I'd recommend getting into the habit of using:
return $c->res->redirect($c->uri_for('qbo/home'));
or
$c->res->redirect($c->uri_for('qbo/home')) && $c->detach();
depending on your preference.

RAILS 4 After editing and updating, the id of posts is passed as user why?

I have a user model that has_many posts, but I have few issues when a user updates a post. When a first user (user id:1) updates a post, (say post id:13), upon redirect, the page tries to redirect to user id:13. Does anyone know why this is? Here are my lines of code.. Thanks in advance.
posts_controller.rb
.
.
.
def update
#post = current_user.posts.find(params[:id])
if #post.update_attributes(post_params)
redirect_to user_path, notice: "Successfully updated!"
else
render action: "edit"
end
end
users_controller.rb
.
.
.
def show
#user = User.find(params[:id])
#posts = #user.posts.paginate(page: params[:page])
end
redirect_to **user_path**, notice: "Successfully updated!"
You are redirecting to the user_path. You want to redirect to the post_path. Unless what you want is directing to the user_path. Then, you need to pass it the user id: user_path(current_user.id)

Making Register Plus Redux work with Nextend Google Connect

I'm trying to make two popular WordPress plug-ins work well together. Hopefully this question isn't too specific to my setup -- I think enough people use these plug-ins to make it a common issue.
I'm using Register Plus Redex (RPR) to require user registration to be accepted (by admin) before a user can log-in. Alone, this works fine.
I'm also using Nextend Google Connect (NGC) to allow users to log-in with Google. Those also need to be approved before they can log-in.
When NGC creates a new user in the database, it correctly has the "not activated" flag set. However, the user is still logged in. This allows them to see some blog pages that are protected by "Members Only" (another plug-in). I could maybe update Members Only or other areas to avoid this, but I would rather these users see the same behavior a normal user would see, one that just logs in with user/password, not Google. They get a nice "Your account has not been activated yet" message.
RPR has this code to authenticate, I think I need to use it from NGC some way:
public /*.object.*/ function rpr_authenticate( /*.object.*/ $user, /*.string.*/ $username, /*.string.*/ $password) {
if ( !empty($user) && !is_wp_error( $user ) ) {
if ( NULL !== get_role( 'rpr_unverified' ) && in_array( 'rpr_unverified', $user->roles ) ) {
return null;
}
}
return $user;
}
I think this is the section of NGC code I need to modify:
$secure_cookie = is_ssl();
$secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, array());
global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
$auth_secure_cookie = $secure_cookie;
wp_set_auth_cookie($ID, true, $secure_cookie);
$user_info = get_userdata($ID);
do_action('wp_login', $user_info->user_login, $user_info);
do_action('nextend_google_user_logged_in', $ID, $u, $oauth2);
update_user_meta($ID, 'google_profile_picture', 'https://profiles.google.com/s2/photos/profile/' . $u['id']);
The NGC code uses what I think is a "hacked" method of log-in. It doesn't use any of the methods I have seen recommended online, like the new wp_signon or older wp_login functions.
Is what I'm trying to do a major project? If so, is there another combination of plug-ins (or a single one) that will handle the following:
Require users to be logged in to see any pages (what Members Only does)
Require admin to moderate/approve new users (what RPR does)
Support log-in via Facebook, Twitter, and Google (what the Nextend Connect plug-ins do)
Update:
I changed the NGC code to this, and now it doesn't log the user in, but it just leaves them on the log-in page with no error message. I'm not sure how I can add an error message to the default log-in page, everything I find online is related to custom log-in pages.
if ($ID) { // Login
$user_info = get_userdata($ID);
if ( !empty($user_info) && !is_wp_error( $user_info ) ) {
if ( NULL !== get_role( 'rpr_unverified' ) && in_array( 'rpr_unverified', $user_info->roles ) ) {
// TODO - How to add error message to log-in page?
return;
}
}
$secure_cookie = is_ssl();
$secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, array());
global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
$auth_secure_cookie = $secure_cookie;
wp_set_auth_cookie($ID, true, $secure_cookie);
//
do_action('wp_login', $user_info->user_login, $user_info);
do_action('nextend_google_user_logged_in', $ID, $u, $oauth2);
update_user_meta($ID, 'google_profile_picture', 'https://profiles.google.com/s2/photos/profile/' . $u['id']);
}
I'm sure there is a better way to do this, one that will not be undone anytime I update the plug-in, but for now this works for me.
I updated nextend-google-connect.php, part of the Nextend Google Connect plug-in, and changed the Login code (starting around line 230 depending on your version) to this:
if ($ID) { // Login
$user_info = get_userdata($ID);
if ( !empty($user_info) && !is_wp_error( $user_info ) ) {
if ( NULL !== get_role( 'rpr_unverified' ) && in_array( 'rpr_unverified', $user_info->roles ) ) {
wp_redirect('wp-login.php?checkemail=registered');
exit;
}
}
$secure_cookie = is_ssl();
$secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, array());
global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
$auth_secure_cookie = $secure_cookie;
wp_set_auth_cookie($ID, true, $secure_cookie);
do_action('wp_login', $user_info->user_login, $user_info);
do_action('nextend_google_user_logged_in', $ID, $u, $oauth2);
update_user_meta($ID, 'google_profile_picture', 'https://profiles.google.com/s2/photos/profile/' . $u['id']);
}
By redirecting to that special URL, the Redux plug-in already has code to display a nice message to the user letting them know the admin needs to verify the account.

Authentication fails in Zend for account confirmation

I am stuck with this problem. When the login credentials are authenticated in my zend application , I also want to check if the account has been confirmed or not. Confirmed is a boolean column in my account table and is set to False by default. I am trying to achieve this through following code..but it is not working
$db = Zend_Db_Table::getDefaultAdapter();
$authAdapter = new Zend_Auth_Adapter_DbTable($db);
$authAdapter->setTableName('Account');
$authAdapter->setIdentityColumn('Email');
$authAdapter->setCredentialColumn('Password');
$authAdapter->setCredentialTreatment('Confirmed = 1');
$authAdapter->setIdentity($data['email']);
$authAdapter->setCredential($data['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($authAdapter);
if ($result->isValid()) {
if ($data['public'] == "1") {
Zend_Session::rememberMe(Zend_Registry::getInstance()->constants->sessiontime);
} else {
Zend_Session::forgetMe();
}
return TRUE;
} else {
return FALSE;
}
Despite the account not confirmed the authentication passes. Please tell me where am I wrong
The credential treatment parameter specifies how the password should be checked. You can override this to add additional clauses, but you still need to include the password bit. Really I wouldn't have expected your method to authenticate any users, so this may not be the main issue, but try:
$authAdapter->setCredentialTreatment('MD5(?) AND Confirmed = 1');
Changing the MD5 bit for however your passwords are encrypted. That should generate a query along the lines of:
... WHERE Email = 'xxx' AND Password = MD5(?) AND Confirmed = 1

How to allow custom flash keys in a redirect_to call in Rails 3

In Rails 3, you can pass has attributes directly to redirect_to to set the flash. For example:
redirect_to root_path, :notice => "Something was successful!"
However, this only works with the :alert and :notice keys; if you want to use custom keys, you have to use a more verbose version:
redirect_to root_path, :flash => { :error => "Something was successful!" }
Is there any way to make it so that custom keys (such as :error, above) can be passed to redirect_to without specifying it in :flash => {}?
In Rails 4 you can do this
class ApplicationController < ActionController::Base
add_flash_types :error, ...
and then somewhere
redirect_to root_path, error: 'Some error'
http://blog.remarkablelabs.com/2012/12/register-your-own-flash-types-rails-4-countdown-to-2013
I used the following code, placed in lib/core_ext/rails/action_controller/flash.rb and loaded via an initializer (it's a rewrite of the built-in Rails code):
module ActionController
module Flash
extend ActiveSupport::Concern
included do
delegate :alert, :notice, :error, :to => "request.flash"
helper_method :alert, :notice, :error
end
protected
def redirect_to(options = {}, response_status_and_flash = {}) #:doc:
if alert = response_status_and_flash.delete(:alert)
flash[:alert] = alert
end
if notice = response_status_and_flash.delete(:notice)
flash[:notice] = notice
end
if error = response_status_and_flash.delete(:error)
flash[:error] = error
end
if other_flashes = response_status_and_flash.delete(:flash)
flash.update(other_flashes)
end
super(options, response_status_and_flash)
end
end
end
You can, of course, add more keys besides just :error; check the code at http://github.com/rails/rails/blob/ead93c/actionpack/lib/action_controller/metal/flash.rb to see how the function looked originally.