Yii auth with aply dynamic bizrules - authentication

I am using Yii auth extension for user's authentication wise can get access.
In initial level of auth module only describe give operations,assignment,task according to user role.
I want give task according to bizrule at assign by user can access(update,listing,delete) own data.
I want to change one file for apply bizrule
AuthFilter.php
class AuthFilter extends CFilter
{
public $params = array();
public $enableBizRule = true;
public $enableBizRuleData = true;
protected function preFilter($filterChain)
{
$itemName = '';
$controller = $filterChain->controller;
$user = Yii::app()->getUser();
if (($module = $controller->getModule()) !== null) {
$itemName .= $module->getId() . '.';
if ($user->checkAccess($itemName . '*')) {
return true;
}
}
$itemName .= $controller->getId();
//print_r($itemName);
if ($user->checkAccess($itemName . '.*')) {
return true;
}
$itemName .= '.' . $controller->action->getId();
if ($user->checkAccess($itemName, $this->params)) {
return true;
}
if ($user->isGuest) {
$user->loginRequired();
}
throw new CHttpException(401, Yii::t('yii', 'You are not authorized to perform this action.'));
}
}
http://www.yiiframework.com/extension/auth/
http://www.cniska.net/yii-auth/en_us/auth/assignment/index

Related

signin page redirecting again to signin page in codeigniter

Controller
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Signin extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->helper('cias');
$this->load->model('home_model');
$this->load->model('signin_model');
}
public function index(){
$this->is_signed_in();
}
function is_signed_in()
{
$is_signed_in = $this->session->userdata('is_signed_in');
if(!isset($is_signed_in) || $is_signed_in != TRUE)
{
// header
$data['logo'] = $this->home_model->get_logo_by_id();
// footer
$data['contact']=$this->home_model->get_contact();
$this->load->view('front/signin');
}
else
{
redirect('front/dashboard');
}
}
public function signinme()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|max_length[128]|trim');
$this->form_validation->set_rules('password', 'Password', 'required|max_length[32]');
if($this->form_validation->run() == FALSE)
{
$this->index();
}
else
{
$email = strtolower($this->security->xss_clean($this->input->post('email')));
$password = $this->input->post('password');
$result = $this->signin_model->sign_in_me($email, $password);
if(!empty($result))
{
$session_array = array('user_id'=>$result->user_id,
'name'=>$result->name,
'email'=>$result->email,
'phone'=>$result->phone,
'is_signed_in' => TRUE );
$this->session->set_userdata('logged_in', $session_array);
redirect('./dashboard');
}
else
{
$this->session->set_flashdata('error', 'Email Address or password mismatch');
$this->index();
}
}
}
}
Model
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Signin_model extends CI_Model
{
// This function used to check the login credentials of the user
function sign_in_me($email, $password)
{
$this->db->select('*');
$this->db->from('user_login');
$this->db->where('email', $email);
$this->db->where('isdeleted', 0);
$query = $this->db->get();
$user = $query->row();
if(!empty($user)){
if(verifyHashedPassword($password, $user->password)){
return $user;
} else {
return array();
}
} else {
return array();
}
}
function get_user_info_id($user_id){
$this->db->select('*');
$this->db->from('user_login');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
return $query->row();
}
}
Want to redirect
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
require APPPATH . '/libraries/FrontController.php';
class Dashboard extends FrontController {
public function __construct(){
parent::__construct();
$this->load->helper('cias');
$this->load->model('home_model');
$this->load->model('signin_model');
$this->is_signed_in();
}
public function index(){
$this->load->view("front/dashboard", $data);
}
function signout() {
$this->session->sess_destroy ();
redirect ( 'signin' );
}
}

How to login using sql password() function in laravel?

I want to login using the sql password() function in laravel. This is because the master database of employee table contains password in the format insert into tbl_name(' ') values (' ', password('abc'));
So I need to use this master table for login so can anyone suggest me as to how can this be possible?
public function login(Request $request) {
// dd($request->all());
if(Auth::attempt([
'tgi' => $request->tgi,
'password' => $request->password
]))
{
// $user = \DB::where('tgi', $request->tgi)->first();
$user = MasterLogin::where('tgi', $request->tgi)->first();
if($user->is_admin() == '1') {
return redirect()->route('dashboard');
}
elseif($user->is_admin() == '0'){
return redirect()->route('home');
}
elseif($user->is_admin() == '3'){
return redirect()->route('manager');
}
}
return redirect()->back();
}
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
In validateCredentials i would like to know how can I pass the password here.
As of now I tried this as said:
public function login(Request $request) {
// dd($request->all());
if(Auth::attempt([
'tgi' => $request->tgi,
'password' => sha1($request->password)
]))
{
$user = User::select("SELECT * FROM emp_username_db WHERE tgi = $request->tgi AND password = sha1('$request->password')");
if (Hash::check(sha1($request->password), $user['password'])) {
// The passwords match...
return redirect()->route('dashboard');
}
}
return redirect()->back();
}
My code that I am working on
class LoginController extends Controller
{
public function login(Request $request) {
//$user = User::where('tgi', $request->tgi)->first();
$result = User::where('tgi',$request->tgi)->where('password',\DB::raw('password("$request->password")'))->exists();
if ($result) {
if($result->is_admin() == '1'){
// Authentication passed...
return redirect()->intended('dashboard');
}elseif($result->admin == '0'){
return redirect()->route('home');
}
elseif($result->admin == '3'){
return redirect()->route('manager');
}
return redirect()->back();
}
}
As SQL default password is hashed using SHA1 so we can compare user's password by using laravel raw query like this.
$result = User::where('tgi',$request->tgi)->where('password',\DB::raw('password("$request->password")'))->exists();
if($result){
your code....
}
It's redirecting to dashboard but getting 302 found.

Cakephp 3 and Authentication

Is there an easy way like in Cakephp 3 to work with roles
APP Controller
public function isAuthorized($user)
{
// Admin can access every action
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
// Default deny
return false;
}
POSTS Contoller
public function isAuthorized($user) {
// All registered users can add posts
if ($this->action === 'edit') {
return true;
}
return parent::isAuthorized($user);
}
I know from http://book.cakephp.org/3.0/en/controllers/components/authentication.html#testing-actions-protected-by-authcomponent that
$this->auth->deny('add');
Is doing it, but how can I add the user/admin ?
I have used ACL authentication in very simple way with isAuthorised() method. I hope it would be help you.
AppController.php
you can make have to define property
/**
* ACCESS CONTROL LIST BASED ON METHODS OF CLASS FOR USER ROLES
*/
var $accessControllList = array();
Define private method
private function _checkAccessControll() {
if ($this->Auth->user('id')) {
if (!isset($this->accessControllList) || empty($this->accessControllList)) {
return true;
}
$action_name = $this->request->params['action'];
$user_role = $this->Auth->user('role');
if (isset($this->accessControllList['allowed']) && !empty($this->accessControllList['allowed']) && in_array($action_name, $this->accessControllList['allowed'])) {
return true;
} else if (isset($this->accessControllList['role_base'][$user_role]) && !empty($this->accessControllList['role_base'][$user_role]) && in_array($action_name, $this->accessControllList['role_base'][$user_role])) {
return true;
}
throw new \Cake\Network\Exception\ForbiddenException(__('You not have access for this page'));
}
return true;
}
in isAuthorized() add below line.
$this->_checkAccessControll();
In any controller, you need to mapping your ACL with roles. For you PostsController.php file something as below
/**
* List of all accessible Action from URL
* #var array
*/
var $accessControllList = array(
'allowed' => array('view','index'), // allowed for any role.
'role_base' => array(
'administrator' => array('delete', 'approve'), //specially allowed for administrator only
'publisher' => array('view','create','index','replyComment'), // specially allowed for publisher only
'reader' => array('postComment','replyComment') // specially allowed for reader
)
);

Phalcon keep a model persistant in all the controllers?

my website application is mostly model around a User Model which has all the key data that needed for most of the times.
Once the user is logged into the website I would like to keep it as a persistent variable across all the controllers. How do i achieve this as i cannot use session to hold a class object of Type Model.
My application is based on phalcon. However any suggestions are welcome.
I suggest you to write a simple class for user authentication & other user data manipulation, i wrote this Component and using in my project :
use Phalcon\Mvc\User\Component;
class Auth extends Component {
public function login($credentials) {
if(!isset($credentials['email'],$credentials['password'])) {
return FALSE;
}
if($this->isAuthorized()) {
return true;
}
$user = Users::findFirstByEmail($credentials['email']);
if($user == false) {
//block user for seconds
return false;
}
if($this->security->checkHash($credentials['password'],$user->password) && $user->status == 1) {
$this->_saveSuccessLogin($user);
$this->_setUserLoginSession($user);
return true;
} else {
return false;
}
}
public function isAuthorized() {
return $this->session->has('auth');
}
public function logout() {
$this->session->remove('auth');
return true;
}
public function user($key = null) {
if(!$this->isAuthorized()) {
return null;
}
if(is_null($key)) {
return $this->session->get('auth');
} else {
$user = $this->session->get('auth');
return array_key_exists($key, $user) ? $user[$key] : null;
}
}
private function _saveSuccessLogin(Users $user){
$userLogin = new UserLogins();
$userLogin->user_id = $user->id;
$userLogin->ip = $this->request->getClientAddress();
$userLogin->user_agent = $this->request->getUserAgent();
$userLogin->dns = gethostbyaddr($userLogin->ip);
if(!$userLogin->save()) {
return false;
}
return true;
}
private function _setUserLoginSession(Users $user) {
if(!$user) {
return false;
}
$this->session->set('auth',array(
'id' => $user->id,
'firstname' => $user->firstname,
'lastname' => $user->lastname,
'email' => $user->email,
'role_id' => $user->role_id
));
return true;
}
}
And in my services.php added into DI with this code :
$di->setShared('auth', function () {
return new Auth();
});
So when i want to get user info i use this :
$this->auth->user('email')
Also you can add more functionality to this component & modify it.
I hope that's useful for You.
You can use memcached and save it as key => value:
userId => serialized User model

how rename image before upload in Yii framework

I have follow yii site to work with upload image, code here:
class ItemController extends CController
{
public function actionCreate()
{
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
{
$model->image->saveAs('path/to/localFile');
// redirect to success page
}
}
$this->render('create', array('model'=>$model));
}
}
however how can I rename file by currentdate+filename.png and upload to path,also I need code for update and delete.
thankyou very much
I have resolve this problem:
public function currentDate(){
$date = date('m-d-Y-h-i-s', time());
return $date;
}
public function actionCreate(){
$model = new News();
if(isset($_POST['News']))
{
$model->attributes=$_POST['News'];
$uploadedFile = CUploadedFile::getInstance($model, 'images');
$fileName = "{$this->currentDate()}-{$uploadedFile}";
$model->images = $fileName;
if($model->save()){
$uploadedFile->saveAs("upload/".$fileName);
$this->redirect(array('news/index'));
}else{
$model = new News();
$this->render('create',
array('model' =>$model,
'result'=>'insert new fail !',
));
}
}else{
$this->render('create',
array(
'model'=>$model,
));
}
}
public function actionCreate()
{
$model=new News;
if(isset($_POST['News']))
{
$model->attributes=$_POST['News'];
$name = $_FILES['News']['name']['images'];
$filename = pathinfo($name, PATHINFO_FILENAME);
$ext = pathinfo($name, PATHINFO_EXTENSION);
$newName = date("m-d-Y-h-i-s", time())."-".$filename.'.'.$ext;
$model->images = CUploadedFile::getInstance($model,'images');
if($model->save())
$fullImgSource = Yii::getPathOfAlias('webroot').'/upload/'.$newName;
$model->images->saveAs($fullImgSource);
$model->images = $newName;
$model->save();
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array('model'=>$model,));
}
To rename the file after upload and update in DB, try this code.
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
if($model->save())
{
$imageName = #$_FILES["MenuItems"]["name"]["image"];
$uniqueName = (imageName . $model->id) . '.' . (end(explode('.', $imageName)));
$model->image=CUploadedFile::getInstance($model,'image');
$model->image->saveAs('path/to/localFile/'.$uniqueName);
$model->image = $uniqueName;
$model->save();
// redirect to success page
}
}
$this->render('create', array('model'=>$model));
you can use this method that I had created later to upload file and change its name before upload it :
public static function createAttach($model, $imageAttrName) {
$model->$imageAttrName = CUploadedFile::getInstance($model, $imageAttrName);
$fecha = date('YmdHms');
if ($model->$imageAttrName) {
$attach_src = Yii::app()->basePath . '/../upload/' . $fecha.'.'.$model->$imageAttrName->getExtensionName(); //. '_' . $model->$imageAttrName;
$model->$imageAttrName->saveAs($attach_src);
$model->$imageAttrName = $fecha.'.'.$model->$imageAttrName->getExtensionName();// . '_' . $model->$imageAttrName;
}
}