It occurred to me that it would be possible to add a boolean field to the array that indicated whether the page required authentication to be viewed. So an admin could check any page in the Pages section as “private” – ie requiring a login.
So adding the key ‘is_private’ (line 8) to MY_fuel_layout.php:
1: $config['layout_fields']['main'] = array(
2: 'copy' => array('copy' => lang('layout_field_main_copy')),
3: 'page_title' => array('label' => lang('layout_field_page_title')),
4: 'meta_description' => array('label' => lang('layout_field_meta_description')),
5: 'meta_keywords' => array('label' => lang('layout_field_meta_keywords')),
6: 'body' => array('label' => lang('layout_field_body'), 'type' => 'textarea',
'description' => lang('layout_field_body_description')),
7: 'body_class' => array('label' => lang('layout_field_body_class')),
8: 'is_private' => array('type' => 'enum', 'options' => array('yes' => 'yes', 'no' => 'no'),
'default' => 'no', 'description' => 'Page requires authentication')
9: );
creates radio buttons in the “layout variables” section of the Pages edit/create form labelled yes, no. There could be a group requirement and all sorts of sophistication here, but ‘yes’ and ‘no’ will do for now.
How to intercept this variable, and where?
As per Codeigniter, we can use hooks. In application/config/hooks.php we can add an array to the ‘post_controller’ hook.
1: $hook['post_controller'][] = array(
2: 'class' => 'MY_auth',
3: 'function' => 'page_auth',
4: 'filename' => 'MY_auth.php',
5: 'filepath' => 'libraries',
6: 'params' => array()
7: );
Here we identify a class (in application/libraries it so happens) called MY_auth, and a method in it called page_auth(). This will be called after every controller. Note that the array is multi dimensional – the class here can be tacked on to existing hooks by declaring the arrays for a given hook in this manner, see the CI user guide.
In MY_auth we put:
1: <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
2: class MY_auth {
3: var $CI;
4: function __construct()
5: {
6: $this->CI = & get_instance();
7: $this->CI->load->library('ion_auth');
8: }
9:
10: function page_auth()
11: {
12: $this->CI->load->module_library(FUEL_FOLDER, 'fuel_pagevars');
13: $vars = $this->CI->fuel_pagevars->retrieve(uri_path(), 'db');
14: if(isset($vars['is_private']))
15: if($vars['is_private'] == 'yes')
16: if(!$this->CI->ion_auth->logged_in())
17: redirect('auth/login', 'refresh');
18: }
19: }
Page_auth() grabs the page variables associated with the current url (specified by uri_path()) from the Fuel_pagevars library in the Fuel modules folder. If one of these is “is_private” and it’s set to ‘yes’, then we whammy the visitor to the auth controller (in this case, courtesy of ion_auth).
No comments:
Post a Comment