I am working on a job site.And using Yii.I have gridview which list all the jobs posted by user,but I just want to show the jobs which are posted by a particular user.like if the user is logged in as admin then it should show only jobs posted by admin.I have tried the following things but not working.
In Controller.
//codes
public function actionViewJob() {
$user_id = Yii::app()->session['user_id'];
/* For User Authentication */
if (Yii::app()->user->getId() === null)
$this->redirect(array('site/login'));
/* For User Authentication */
$model = ViewJob::model()->find(array(
'select' => array('*'), "condition" => "user_id= $user_id",
));
$params = array('model' => $model,
);
$this->render('viewjob', $params);
}
function as search() in model ViewJob.
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('key_skills','Admin',true);
return new CActiveDataProvider('viewjob', array(
// 'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'key_skills ASC',
),
));
}
What am I doing wrong here.?.Its still listing the whole data.
Try like
$model=ViewJob::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
Try this
$model = ViewJob::model()->findAll("user_id=$user_id");
/*
1. find() can fetch first matched row, where as findAll() fetches all matched rows in the db table
2. "user_id=$user_id" is equals to WHERE user_id=$user_id
*/
Code improvements(Yii way)
Register user sessions as bellow
Yii::app()->user->setState('user_id',$value_variable); //Set the session
Yii::app()->user->getState('user_id'); //Get the session
You can use accessRules() for bellow code
if (Yii::app()->user->getId() === null)
$this->redirect(array('site/login'));
Like
public function accessRules()
{
return array(
array('allow',
'actions' => array('viewJob'),
'users' => array('#'),
----
---
Related
I am working on a web application that allow users to have video conferences. Users are allowed to create video conferences and I want them to be able to also edit the scheduled video conferences but I am having trouble implementing that. Please help.
Edit button in index.php view
$html .= CHtml::ajaxLink('Edit',
Yii::app()->createAbsoluteUrl('videoConference/update/'.$vc->id),
array(
'type'=>'post',
'data' => array('id' =>$vc->id,'type'=>'update'),
),
array( "visible" => $ismoderator, 'role' => "button", "class" => "btn btn-info")
);
Video conference Controller actionUpdate
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model = $this->loadModel($id);
if (isset($_POST['VideoConference'])) {
$model->attributes = $_POST['VideoConference'];
if ($model->save())
$this->redirect(array('view', 'id' => $model->id));
}
$this->render('edit', array(
'model' => $model,
));
}
The first step is to find where is problem(frontend / backend). You need call action without ajax(just from url with param id). Try my version:
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model = $this->loadModel($id);
if ($model == null) {
throw new CHttpException(404, 'Model not exist.');
}
//if (isset($_POST['VideoConference'])) {
//$model->attributes = $_POST['VideoConference'];
$model->attributes = array('your_attr' => 'val', /* etc... */);
// or try to set 1 attribute $model->yourAttr = 'test';
if ($model->validate()) {
$model->update(); //better use update(), not save() for updating.
$this->redirect(array('view', 'id' => $model->id));
} else {
//check errors of validation
var_dump($model->getErrors());
die();
}
//}
$this->render('edit', array(
'model' => $model,
));
}
If on server side all working fine(row was updated) then check request params, console, tokens etc. Problem will be on frontend.
After troubleshooting a little I finally got it to work.
On the view I am calling the actionUpdate method like this:
$html .= CHtml::button('Edit', array('submit' => array('videoConference/update/'.$vc->id), "visible" => $ismoderator, 'role' => "button", "class" => "btn btn-info"));
On the controller just changed
$model->save() to $model->update()
and it works perfectly fine.
I've created a module to authenticate a user. Now, after login I go to the index action and the system tells me that the authentication is all working fine. But What I want is to print some more user details from the Users table. When I try:
print_r($this->getServiceLocator()->get('AuthService')->getAdapter()->getResultRowObject());
I get no result. What am I doing wrong?
Thanks for your help.
In my module.php I've the following code(snippet):
public function getServiceConfig()
{
return array(
'abstract_factories' => array(),
'aliases' => array(),
'factories' => array(
// Some more code here but removed for simplicity
// Autentication
'AuthService' => function ($sm) {
$adapter = $sm->get('master_db');
$dbAuthAdapter = new DbAuthAdapter ( $adapter, 'Users', 'email', 'password' );
$auth = new AuthenticationService();
$auth->setAdapter ( $dbAuthAdapter );
return $auth;
},
// Some more code here but removed for simplicity
}
In my IndexController.php I've the following (snippets):
public function indexAction()
{
if(!$this->getServiceLocator()->get('AuthService')->hasIdentity()){
return $this->redirect()->toUrl('login');
}
echo "hello, it works!";
exit;
}
public function loginAction(){
$form = $this->getServiceLocator()->get('LoginForm');
$viewModel = new ViewModel(array('form' =>
$form));
return $viewModel;
}
public function processAction(){
// Lots of code here
if($bcrypt->verify($loginData['password'], $userData->password))
{
$this->getAuthService()
->getAdapter()
->setIdentity($loginData['email'])
->setCredential($userData->password);
$result = $this->getAuthService()->authenticate();
}
// Lots of code here where I check if $result->isValid and route to the
// correct action
}
public function getAuthService() {
if(!isset($this->authservice)) {
$this->authservice = $this->getServiceLocator()->get('AuthService');
}
return $this->authservice;
}
Instead of refering to the authentication result object (which properly only exists in the authentication request) you can simply store user details in the authentication identity (#see http://framework.zend.com/manual/2.1/en/modules/zend.authentication.intro.html).
For your case you could also store user specific details right after the validation of the authentication result in the authentication storage:
if ($result->isValid()) {
//authentication success
$resultRow = $this->authService->getAdapter()->getResultRowObject();
$this->authService->getStorage()->write(array(
'id' => $resultRow->id,
'user_agent' => $request->getServer('HTTP_USER_AGENT'))
);
}
(This information was taken from this authentication tutorial http://samsonasik.wordpress.com/2013/05/29/zend-framework-2-working-with-authenticationservice-and-db-session-save-handler/)
I am working on a job site,And want to show only the jobs posted by a particular user in cgridview.My actuall aim is to authenticate the user so that only jobs posted by him/her will be visible in cgridview.I have done the following stuff,but not working.
In controller:
public function actionViewJob() {
$user_id = Yii::app()->session['user_id'];
/* For User Authentication */
if (Yii::app()->user->getId() === null)
$this->redirect(array('site/login'));
/* For User Authentication */
/* Have tried the following codes to filter */
$model= ViewJob::model()->findAll(array(
'select'=>'*',"condition"=>"user_id='$user_id'",
));
// $model=ViewJob::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
// $model = ViewJob::model()->findAll("user_id=$user_id");
$model = new Viewjob('search');
$params = array('model' => $model,
);
$this->render('viewjob', $params);
}
In view
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' =>$model->search()
// 'filter' => $model, /* not using this option ,so commented it */
))
In model
// Do I really Need This Function //
public function search() {
$criteria = new CDbCriteria;
$criteria->compare('user_id', $this->user_id, true);
return new CActiveDataProvider('viewjob', array(
'criteria'=>$criteria,
));
},,
What am I doing wrong here.It is still fetching all the available rows in table.
You define $model 3 times:
$model= ViewJob::model()->findAll(array(
'select'=>'*',"condition"=>"user_id='$user_id'",
));
Then
$model = new Viewjob('search');
And
'dataProvider' =>$model->search()
Choose one that you need, better last. And add to controller
$model->user_id = $user_id
It will works.
Create new CDbCriteria object and add condition using it and pass it to model.
In Controller:
public function actionViewJob() {
$criteria = new CDbCriteria ();
$criteria->condition = 'user_id=' . Yii::app()->user->id;
$model = ViewJob::model()->findAll($criteria);
$params = array('model' => $model);
$this->render('viewjob', $params);
}
And in View, simply:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' =>$model
Also for use Authentication, in your controller you don't need to check, if user has the user id, simply add access rules, which will automatically redirect user to the login page to view the job and once they are logged-in, will return them to the same page. So, add this at the top of our controller..
class YourController extends Controller {
public function filters() {
return array(
'accessControl', // perform access control
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules() {
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions' => array('index', 'view'),
'users' => array('*'),
),
array('allow', // allow authenticate user actions
'actions' => array('viewjob'),
'users' => array('#'),
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
In my site, only when I remove the filters() method, the captcha can show up. other time the captcha doesn't work. and my php gd support is enable.
now I am using a custome WebUser, if I remove it from config, the captcha also works well.
by the way, if I access user/captcha directly, it only show a picture box, but not content, maybe can not load the picture..
here are some code segments in my UserController:
actions();
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
'minLength' => 4,
'maxLength' => 4,
'testLimit' => 99999
)
);
}
filters():
public function filters()
{
// return the filter configuration for this controller, e.g.:
return array(
"accessControl",
);
}
accessRulse():
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('captcha'),
'users'=>array('*'),
),
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','login','signup'),
'expression'=>'Yii::app()->user->isGuest',
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('cpassword','info','logout'),
'expression'=>'!Yii::app()->user->isGuest',
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'users'=>array('admin#example.com'),
),
array('deny', // deny all users
'users'=>array('*'),
'message'=>'Access Denied.',
),
);
}
My WebUsers.php
<?php
// this file must be stored in:
// protected/components/WebUser.php
class WebUser extends CWebUser {
// Store model to not repeat query.
private $_model;
// Return first name.
// access it by Yii::app()->user->first_name
public function getDisplayName(){
$user = $this->loadUser(Yii::app()->user->id);
if($user)
return $user->display_name;
}
public function getGroupId(){
$user = $this->loadUser(Yii::app()->user->id);
return $user->group_id;
}
// This is a function that checks the field 'role'
// in the User model to be equal to 1, that means it's admin
// access it by Yii::app()->user->isAdmin()
public function isAdmin(){
$user = $this->loadUser(Yii::app()->user->id);
return intval($user->group_id) == 1;
}
public function isGroupAAS(){
$user = $this->loadUser(Yii::app()->user->id);
return intval($user->group_id) == 1001;
}
// Load user model.
protected function loadUser($id=null)
{
if($this->_model===null)
{
if($id!==null)
$this->_model=User::model()->findByPk($id);
}
return $this->_model;
}
protected function afterLogin($fromCookie){
$user = $this->loadUser($this->id);
$user->last_login_ip = Yii::app()->request->userHostAddress;
$user->last_login_time = new CDbExpression('NOW()');
$user->save();
}
}
?>
In your controller, make sure this is defined.
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
Then, allow the action as following.
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('captcha'),
'users'=>array('*'),
),
array('deny', // deny all users
'users'=>array('*'),
'message'=>'Access Denied.',
),
);
}
and in the form,
<?php $this->widget('CCaptcha'); ?><br>
<?php echo CHtml::textField('captcha'); ?>
if this doesnt work, try this way..
<?php $this->widget('CCaptcha', array('captchaAction' => 'site/captcha')); ?>
to validate the capthca, define it as following in your action
$captcha=Yii::app()->getController()->createAction("captcha");
$code = $captcha->verifyCode;
if($code === $_REQUEST['captcha']){
}
Your code looks fine and compare your code with this answer or please provide the source code to take a look at.
Give access to your captcha showing method ie actions
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('actions'),
'users'=>array('*'),
),
I have tested your code with one of my SiteController & it's (captcha action) working fine under contact action. Could you kindly post full UserController code to review & identify the exact cause?
Just add 'captcha' in the actions array like this
public function accessRules()
{
return array(array('allow', // allow admin user to perform these actions
'actions'=>array('index','view','add','captcha'),
'users'=>array('admin'),
), ...
Hello everybody i need help on codeigniter roles or permision. i have one user role (the admin) :
Table users ine the database :
id int(11)
email varchar(100)
password varchar(128)
name varchar(100)
in my admin panel i have (page.php controller)=page management, page order, (agent.php controller) = add,edit,delete... , (gyms) = add,edit,delete... ,(article.php controller)
and i have 21 sections, for each section i have more than one treatment, what i want is to assign to each section an admin than can edit and view only his section. so i will have 21 section_admin and one (or more) global_admin than can manage everything
i add an other field in users table named type :
type varchar(50)
it will have two values section_admin or global_admin. I searched but i found no tutorial that shows me how do that.
i don't know how to integrate roles management in my system. Can someone help me?
The controler : user.php
class User extends Admin_Controller
{
public function __construct ()
{
parent::__construct();
}
public function index ()
{
// Fetch all users
$this->data['users'] = $this->user_m->get();
// Load view
$this->data['subview'] = 'admin/user/index';
$this->load->view('admin/_layout_main', $this->data);
}
public function edit ($id = NULL)
{
// Fetch a user or set a new one
if ($id) {
$this->data['user'] = $this->user_m->get($id);
count($this->data['user']) || $this->data['errors'][] = 'User could not be found';
}
else {
$this->data['user'] = $this->user_m->get_new();
}
// Set up the form
$rules = $this->user_m->rules_admin;
$id || $rules['password']['rules'] .= '|required';
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->user_m->array_from_post(array('name', 'email', 'password'));
$data['password'] = $this->user_m->hash($data['password']);
$this->user_m->save($data, $id);
redirect('admin/user');
}
// Load the view
$this->data['subview'] = 'admin/user/edit';
$this->load->view('admin/_layout_main', $this->data);
}
public function delete ($id)
{
$this->user_m->delete($id);
redirect('admin/user');
}
public function login ()
{
// Redirect a user if he's already logged in
$dashboard = 'admin/dashboard';
$this->user_m->loggedin() == FALSE || redirect($dashboard);
// Set form
$rules = $this->user_m->rules;
$this->form_validation->set_rules($rules);
// Process form
if ($this->form_validation->run() == TRUE) {
// We can login and redirect
if ($this->user_m->login() == TRUE) {
redirect($dashboard);
}
else {
$this->session->set_flashdata('error', 'That email/password combination does not exist');
redirect('admin/user/login', 'refresh');
}
}
// Load view
$this->data['subview'] = 'admin/user/login';
$this->load->view('admin/_layout_modal', $this->data);
}
public function logout ()
{
$this->user_m->logout();
redirect('admin/user/login');
}
public function _unique_email ($str)
{
// Do NOT validate if email already exists
// UNLESS it's the email for the current user
$id = $this->uri->segment(4);
$this->db->where('email', $this->input->post('email'));
!$id || $this->db->where('id !=', $id);
$user = $this->user_m->get();
if (count($user)) {
$this->form_validation->set_message('_unique_email', '%s should be unique');
return FALSE;
}
return TRUE;
}
}
The model user_m.php :
protected $_table_name = 'users';
protected $_order_by = 'name';
public $rules = array(
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|xss_clean'
),
'password' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
)
);
public $rules_admin = array(
'name' => array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|callback__unique_email|xss_clean'
),
'password' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|matches[password_confirm]'
),
'password_confirm' => array(
'field' => 'password_confirm',
'label' => 'Confirm password',
'rules' => 'trim|matches[password]'
),
);
function __construct ()
{
parent::__construct();
}
public function login ()
{
$user = $this->get_by(array(
'email' => $this->input->post('email'),
'password' => $this->hash($this->input->post('password')),
), TRUE);
if (count($user)) {
// Log in user
$data = array(
'name' => $user->name,
'email' => $user->email,
'id' => $user->id,
'loggedin' => TRUE,
);
$this->session->set_userdata($data);
}
}
public function logout ()
{
$this->session->sess_destroy();
}
public function loggedin ()
{
return (bool) $this->session->userdata('loggedin');
}
public function get_new(){
$user = new stdClass();
$user->name = '';
$user->email = '';
$user->password = '';
return $user;
}
public function hash ($string)
{
return hash('sha512', $string . config_item('encryption_key'));
}
}
There's too many ways how you can incorporate permission system in your project and it all depends what you need. I will give you a basic idea for your case how I would do it IF I understood your question right:
Yes, you can add another field to user table and call it role
To your section table add a user_id field. This is how you connect user with section.
Once user logs in, veryfy if that user is section_user and if yes you need to pull the right section based on that user_id from db.
If not, it means its a global_admin and then display all sections.
I'm not sure if I understood your question right tho.
Let me know.
Save yourself the trouble and use this: Flexi-Auth. You'll have roles and permissions for all the admin types you want for example.
I'm not sure exactly what you're trying to achieve, but I'll explain roughly what I would do:
1) Define a URL scheme
For example if you had a website for car enthusiasts, each brand might be its own section:
somesite.com/section/honda
somesite.com/section/ford
somesite.com/section/toyota
Those URL slugs (honda, ford, toyota etc) effectively become the identifiers for the section you're trying to access. Each one is unique.
You would then want to make sure that each slug after /section/ is a parameter rather than a function call. You can do this by going into /application/config/routes.php and defining a route like this:
$route['section/(:any)'] = section_controller/$1;
// $1 is the placeholder variable for the (:any) regex. So anything that comes after /section will be used as a parameter in the index() function of the section_controller class.
2. Create a new database called 'section', and a corresponding model
For now just give it two fields: *section_id*, and *section_name*. This will store each unique section. The code for the model would be something like this:
class Section extends CI_Model
{
public $section_name;
public $section_id;
public function loadByName($section_name)
{
$query = $this->db->select('section_id', 'section_name')
->from('section')
->where('section_name', $section_name);
$row = $query->row();
$this->section_name = $row->section_name;
$this->section_id = $row->section_id;
return $row;
}
public function loadById($section_id)
{
$query = $this->db->select('section_id', 'section_name')
->from('section')
->where('section_id', $section_id);
$row = $query->row();
$this->section_name = $row->section_name;
$this->section_id = $row->section_id;
return $row;
}
}
3. In the user table, create an additional field called *section_id*
This will be the reference to the ID of the section which they are an admin of. For example if the Toyota section_id is 381, then use 381 as the number in the section_id field in the user table.
4. When the page is requested, look up the section_id based on the slug name.
In your controller file, you should then load the section model somewhere in the index() method like so:
class Section_controller extends CI_Controller
{
public function index($section_name)
{
// I will assume you've already loaded your logged in User somewhere
$this->load->model('Section');
$this->Section->loadByName($section_name);
if ($this->User->section_id == $this->Section->section_id)
{
// Render the page with appropriate permissions
}
else
{
// Throw an error
}
}
}
I won't get into any more specifics of doing all of that; you'll have to read the Codeigniter documentation for a grasp on how to handle routes, controllers, DB queries etc.
if you have only 2 roles then it can achieve easily. you know the user is admin or not if user >is admin then it activate all the section where admin has acess. if user is then he won,t able >to gain access.
if you are comfortalbe to use tankauth authentication library if you have enough time to do task then go to tankauth.
you can also use bonfire(HMVC) for user authentication.