authentication in CodeIgniter - authentication

in the project I'm creating I need to check if the user is logged in or not, the tutorials I have seen do explain how to authenticate in the controllers and give access to a page or not. But I want all the pages to be visible to everyone but only show certain options if a user is logged in or not.
something like this in the views
if(is_logged_in()):
//some options here
else:
echo "you need to login to have more options";
endif;
so where should I add this code? in the helper folder?
EDIT: I'm now checking in the views like this, it works but I don't know if it's a best practice. The 'is_logged_in' is something I set to true when the credentials were validated
if($this->session->userdata('is_logged_in'))
EDIT:
so if I make a helper to call that function. Can I check using the userdata function?
this is the function that creates the session
$data = array(
'username' => $this->input->post('username'),
//usertype toevoegen hier
//email toevoegen
//deposit money
'is_logged_in' => true
);
$this->session->set_userdata($data);
How could I used the session data in the function in my helper file?

If you want to have it as a stand-alone function that you can call from anywhere then you are best making it an helper. It might be helpful to think of helpers as the blades of a swiss army knife in your CodeIgniter toolbox.
That way you can change your checks later, move things all around, and still be making calls to isloggedin(). However, both ways work. $this->user->isloggedin() is slightly more verbose, but presents the same useful separation of concerns.
EDIT:
If you want to make calls to your session data in a helper, the way to do that is via get_instance().
In the beginning of your helper file, do this: $CI =& get_instance();
function user_logged_in() {
$CI =& get_instance();
// Do what you want to do with session.
// Simply replace $this->session ... etc. with
// $CI->session ... etc.
...
}

It would be fine to add it into the view, and this is presentation logic.

Related

Using a third party plugin with Yii

i am using a third party plugin with yii, it provides chat functionality, it has its own DB and php files that provide the functionality,
now i am want to use it in the view, but the simple include statements are not working, do i need to convert it to yii or can i use it as is?
<?php
session_start();
// Load MySQL DB settings
include_once('config.inc.php');
$_SESSION['username'] = 'Currently logged in users's username from database';
$_SESSION['user_id'] = 'Currently logged in user's id';
?>
//That's it! To print online users, you need to do it like this:
<?php
$users = mysql_query("SELECT id,username FROM ".$sql_table_users." WHERE chat_status='online' AND id!='".$_SESSION['user_id']."'");
if(mysql_num_rows($users) > 0){
while($user = mysql_fetch_assoc($users)){
print ''.$user['username'].'<br />';
}
}
?>
this is the interface plugin has provided for me.
plugin location is /assets/plugin.
i cant use direct php query commands to another Database, which i want to keep seperate from mine, plus the js file that comes with the plugin calls the script with wrong URL parameters, so what is the best method to incorperate this into my yii app. thanks
You should create a Yii extension that'll wrap your plugin.
Then in your view you'll have to call a widget that'll display your chat.
I think this is the best way to do it because using this all your call to the plugin will be performed with the yii strucutre and philosophy. Only your extension will be structured using the chat philosophy.
Source about creating widgets

Is there a way of adding a quick link on the administration page to a module's configuration?

Is it possible to add a link on the top menubar of the Administration page (Catalog, Orders, Customers...) going straight to a module's configuration page? I've inherited a large module with a ton of messy code that I'd really like to leave be, if at all possible.
The only requirement is that its configuration has to be accessible from that menu bar in particular (or, if there's no other possible option, from the quick links section; this one in particular can easily be achieved, except for the token part).
EDIT: I managed to pull it off by creating an Admin controller, but I am having issues generating the correct access token. I do not really know what to do to fix it and, as such, I am hereby launching (yet another) bounty.
Here's the code I am using for the redirect:
<?php
class AdminMultiBlockController extends AdminController
{
public function __construct()
{
global $cookie;
// this doesn't really work
$tab = 'adminmodules';
$token = Tools::getAdminToken($tab.(int)(Tab::getIdFromClassName($tab)).(int)($cookie->id_employee));
Tools::redirectAdmin('index.php?controller=adminmodules&configure=egr_MultiBlockSlider&token=' . $token);
}
}
My workaround was to force a working token, but this won't do.
What am I doing wrong? What parameters should I put inside the getAdminToken() function in order to successfully access a module's configuration?
I am currently using Prestashop v1.5.1.
Cheers guys!
Not being able to reproduce the problem, I can only guess.
However, try with the following code:
$url = 'index.php?controller=AdminModules&configure=egr_MultiBlockSlider';
$url .= '&token='.Tools::getAdminTokenLite('AdminModules');
Tools::redirectAdmin($url);

Setting returnURL for CButtonColumn button

I'm looking at the controller for the default Delete button in the CButtonColumn class. It manages to return to the previous web-page after deleting a CGridView line and remain on the same page of the CGridView, as opposed to going to the first page. The lines responsible for this in the associated controller seem to be:
if (!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
I would like to create a new custom button that has this behavior (i.e. returning to the previous view without resetting the pagination to page 1), but simply including the above lines of code in the button's associated action does not do the trick. I think I need to send that 'returnUrl' parameter somehow, but I cannot figure out how :)
The 'returnUrl' code you are looking at uses a POST variable for the returnUrl. To use this, you will need to POST that somehow. On the View this code is called from I am assuming there is a <input name="returnUrl"> field in the form. You should make sure this field (populated with the correct URL value) is on all of the Views you are POSTing from in order to access that POST variable in your Controller action.
If you are POSTing to the deleteAction via AJAX, I think you can set the $_POST['returnUrl'] variable with the jQuery AJAX function.
Another way to go might be to use CWebUser's returnUrl SESSION variable instead of this POST variable. I have never done this, but it's built in to Yii so I assume it works OK.
I never really liked the hacky $_POST['returnUrl'] that Gii generates anyway.
ANOTHER thing you could do, possibly, is look at the $_SERVER['HTTP_REFERER'] variable, and use that for the return redirect in your deleteAction. I don't know if that will be set correctly though, with complications from the 302 redirect/rewrites that Yii does.
Good luck!
You can set the return url via the CHtml::link call. Here is an example using delete
CHtml::link(
'Delete',
'#',
array('submit'=>array('delete','id'=>$model->id),
'params'=>('returnUrl'=>'controller/action...'),
'confirm' => 'Are you sure?'
)
);
Pulled from this Stackoverflow answer.

A better way of passing variables from controller to view in symfony

Hey.
I've got a login form with post as method. The action goes to 'auth/login' and will check the database if the user exists. If the user exists, I call the $this->getUser->setAuthenticated(true);. After this I want to redirect to a welcome page if success.
If the login failed, I would want to tell the user so in the view of course. But settings variables in the controller only if login failed, and check in the view if each of those variables are set, is a lot of work?
This means I have to check almost all variables I want to use in the view set from the controller. If it should happen that it is not set, and I just go ahead and echo it, I get an error from symfony, and production stage-mode-ish don't show anything but an 500 internal server error .
Thanks
EDIT:
This is my current, new and better solution. Still looking for feeback.
in /templates/loginSuccess
if ($sf_params->has('bad_login')) {
echo "Wrong username or password";
}
And in my controller:
$this->redirect('auth/login?bad_login=');
Take a look at how sfDoctrineGuardPlugin (the de-facto standard for authentication) does it: they created sfGuardValidatorUser and use it as a post validator in the signin form.
Advantage of this method: the form takes care of the username/password validation, you do not need to put that code in your action. It simplifies that to a simple $form->isValid() { $this->redirect("#homepage"); }.
It seems like you could use symfony's form to take care of the validation. Since the forms show errors built in, you could put this into the form validation and then your controller looks something like:
$form = new LoginForm;
if ($request->isMethod('post'))
{
if ($form->isValid())
{
$this->redirect('account');
}
else
{
// this would show the form, and since you put the login in the form validation it will show errors. You could have the username show the error
}
}
To do what you are doing though, I'd recommend this. That way you aren't accessing any parameters in the view as well.
Controller:
$this->bad_login = $this->getParameter('bad_login',false);
View:
if ($bad_login) { echo 'bad login'; }
Use forward()
Put all the logic required for the view population into separate method of a controller, and call it in both places.
Use cgratigny's solution - put login form and processing code in a single action, and redirect to welcome page if isMethod('post') && $login_success

Kohana 3: How to provide API functions in template/view like WordPress?

I'm working on a project which allows the advanced user to define their own way of showing the information and access some basic API. For example, I provide a show_search_box() function so that the user can call this function in the view file when they want to show the standard search box, or they could call the function with parameters to customize the search form.
e.g. this code in the template will show a search form with watermark text "Enter keyword here".
<div><?php show_search_box('Enter keyword here'); ?></div>
What I'm thinking actually is exactly like what WordPress does in its template tags. (http://codex.wordpress.org/Stepping_Into_Template_Tags)
My idea is to create a class that provide all those API functions and pass an object instance of the class to the view file, so users can call the API functions in view like:
<div><?php $API->show_search_box('Enter keyword here'); ?></div>
I think it will work, (but have not tested it yet), but I prefer providing a set of direct called functions just like WordPress. What's the best way to do this with kohana 3?
======Update: I have tested the method of pass $API object to view, and it works as expected.
class API {
public function show_search_box($watermark){....}
}
In the controller, pass the $API to the view/template
public function action_index()
{
$this->template->API = new API();
}
Then call the function inside view/template as described above.
Unlike those controller methods, $API cannot access the controller's variables unless they're explicitly assigned: e.g. $API->setVar('VarName', $a_controller_variable), which is quite tedious i think.
Well, unlike Kohana 2.3, views don't execute in the controller namespace, so you can't simply do $this->something().
If you have all your functions in one Model, let's call it API, then you could do this in the view (or base controller if you want it available everywhere)...
$this->template->internalView = View::factory('your_view')
->set('API', Model::factory('API));
(assuming you have a <?php echo $internalView; ?> in a parent view).
Then you could do in your view...
<div><?php $API->show_search_box('Enter keyword here'); ?></div>
Which will run your method on your model. Views shouldn't really know about the existence of models, but your case ma be an exception. Perhaps you could use a helper sort of class instead of a model, if you are worried about breaking the MVC paradigm.
If you want to do what WordPress does (have a bunch of global functions, which I don't recommend), then you will need to define them somewhere. Kohana doesn't really have an easy spot to place them, as it doesn't really cater for a bunch of global functions.