store session id in another table in codeigniter - mysql

i have one login page for vendor..after vendor logged in they redirect to vendor_dashboard..there i am getting vendor id with dashboard link..and i am getting that particular vendor name in my dashboard page..
In vendor dashboard..vendor has one tab called candidates..when they click on that tab they redirect to add_candidate page..so when vendor submit the form i want to store that vendor_id in candidates table..
In candidates_table there is one column called vendor_id..after submit i want to store that vendor_id for that particular candidate..
I am trying to do this..from past 6 hours..still it's not storing..
The problem is i didn't get anyidea on how to do this..
Login page:
if($this->input->post())
{
$user = $this->LoginModel->login($this->input->post());
if(count($user)>0)
{
$data = array(
'user_id' => $user['user_id'],
'first_name' => $user['first_name'],
'email' => $user['email'],
'password' => $user['password']
);
$this->session->set_userdata($data);
if($user['user_type_id'] == '1')
{
// redirect(base_url('index.php/Login/vendor_dashboard/'.$data['first_name']));
redirect(base_url('index.php/Login/vendor_dashboard/'.$this->session->user_id));
}
elseif($user['user_type_id'] == '2')
{
// (base_url('index.php/Login/user_dashboard/'.$this->session->user_id));
}
else
{
redirect(base_url('index.php/Login/dashboard'));
}
}
Dashboard:
<?= ($this->session->first_name)? $this->session->first_name : "" ?>
Can anyone help me..
Thanks in advance..

Your questions is some how related to this post. Anyway here is what you can do. Start with Authentication using User Controller or name it login or whatever you are comfortable with
class Users extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
}
public function index()
{
$data['title']='Vendors Application';
if($_POST)
{
$user=$this->user_model->checkUser($_POST);
if(count($user)>0)
{
$this->session->set_userdata($user);
redirect(base_url().'dasboard/vendor');
}
}
else
{
$this->load>view('login',$data);
}
}
}
The function to check your user in database in User Model is as follows
public function checkUser($data)
{
$st=$this->db->select('*')->from('users')
->WHERE('email',$data['email'])
->WHERE('password',md5(sha1($data['password'])))
->get()->result_array();
if(count($st)>0)
{
return $st[0];
}
else
{
return false;
}
}
Once you are logged in and redirected to dashboard, add the candidate using Dashboard Controller or whatever you are comfortable to call it.
class Dashboard extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
}
public function vendor()
{
$data['title']='Vendor Dashboard';
if($_POST)
{
//validation
$this->user_model->addCandidate($_POST);
$data['success']='Candidate Added Successfully';
$this->load->view('vendor_dashboard',$data);
}
else
{
$this->load->view('vendor_dashboard',$data);
}
}
}
The function in user model to add the candidate is as follows.
public function addCandidate($data)
{
$candidate=array(
'user_id'=>$this->session->userdata['id'],
'first_name'=>$data['first_name'],
'last_name'=>$data['last_name'],
'address'=>$data['address'],
'contact'=>$data['contact']
);
$this->db->insert('candidates',$candidate);
return $this->db->insert_id();
}
Remember you already have the vendor id in your session when you logged him in and stored his record in the session so there is no need to send the controller url any id to load the dashboard.
I hope you know about CI Form Validation if not please find it here

Related

CakePHP 4.x: How to access logged-in user info from within a custom Behavior?

I am trying to add a custom Behavior that is a clone of the default Timestamp. Mine is "Userstamp" adding the current user to audit-trail fields on all tables. At the point where Timestamp sets the field to "new FrozenTime($ts)", I want to set to "$identity->get('username')" or similar. I am having trouble reaching anything from Authentication/Authorization or Identity from within the Behavior.
I know that the information is there, somewhere. But what do I need to include in my Behavior class in order to retrieve it?
I found this link, but I don't see where to put the suggested code.
In my Table:
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('users');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('Userstamp');
.
.
.
}
Cake's timestamp Behavior:
public function timestamp(?DateTimeInterface $ts = null, bool $refreshTimestamp = false): DateTimeInterface
{
if ($ts) {
if ($this->_config['refreshTimestamp']) {
$this->_config['refreshTimestamp'] = false;
}
$this->_ts = new FrozenTime($ts);
} elseif ($this->_ts === null || $refreshTimestamp) {
$this->_ts = new FrozenTime();
}
return $this->_ts;
}
My userstamp Behavior:
public function userstamp($userstamp = null, bool $refreshUserstamp = false)
{
// Variations of this do not work, the Property is not available in UserstampBehavior
// $currentUser = $this->Authentication
// ->getIdentity()
// ->getIdentifier();
$currentUser = 'abc'; <<<<<<<<<<<<< Hard-coded temporarily
if ($userstamp) {
if ($this->_config['refreshUserstamp']) {
$this->_config['refreshUserstamp'] = false;
}
$this->_userstamp = $currentUser;
} elseif ($this->_userstamp === null || $refreshUserstamp) {
$this->_userstamp = $currentUser;
}
return $this->_userstamp;
}
Your Auth-Informations lives also in the session.
So you can access Session-stuff in a table-class like this:
(new Session)->read('Auth')
And therefore you give this information from a table-class to your Behaviour like this:
$this->addBehavior('Userstamp', ['user_info'=>(new Session)->read('Auth')]);
Then you can access this information in your behaviour:
public function initialize(array $config){
$this->user_info = $config['user_info'];
}
public function myFunction(){
// do something with $this->user_info
}

Pull data from SqlServer Database into jQuery Full Calendar using codeigniter3

I am facing same issue from so many days... Previously I worked with same calendar with PHP, but my project is in Codeigniter, so it is not fitted into my project... So now I am working with Codeigniter..
Controller Code
class Calendar extends CI_Controller
{
public function __construct()
{
Parent::__construct();
$this->load->model('Calendar_model');
}
public function index()
{
$this->load->view('Calendar_view');
}
public function load()
{
$query = $this->Calendar_model->load_events();
$data_events = array();
foreach($query->result() as $row)
{
$data_events[] = array(
"title" => $row->title,
"start" => date('Y-m-d H:i:s',strtotime($row->start_event)),
"end" => date('Y-m-d H:i:s',strtotime($row->end_event))
);
}
echo json_encode($data_events);
}
}
Model Code
class Calendar_model extends CI_Model
{
public function __construct()
{
Parent::__construct();
}
public function load_events()
{
$query = $this->db->get("events");
return $query;
}
}
When I run the above with this url http://localhost/calendar_sql_copy/index.php/Calendar/load,
I got following data
[{"title":"Meeting2","start":"2019-09-30 00:00:00","end":"2019-09-30 00:00:00"},{"title":"Meeting2","start":"2019-02-08 00:00:00","end":"2019-03-08 00:00:00"}]
But when I try to pull same data into Fullcalendar in following way..
<script>
$(document).ready(function(){
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
selectable:true,
selectHelper:true,
// events:[
// {
// "title":"Meeting2",
// "start":"2019-09-30 00:00:00",
// "end":"2019-09-30 00:00:00"
// }
// ]
events:'<?php echo site_url('Calendar/load'); ?>'
</script>
If I show same data in static way as
events:[
{
"title":"Meeting2",
"start":"2019-09-30 00:00:00",
"end":"2019-09-30 00:00:00"
}
]
It pops up into calendar,
But when I try to render with URL like below,
events:'<?php echo site_url('Calendar/load'); ?>'
Here is the data from the browser Network tool: https://intouchsystems-my.sharepoint.com/:u:/g/personal/gurubaran_k_icsoft_co_in/EZE8m-w3Pn1HoktYxL2yHPQBKcuosFXP1M3uT69bh9qn9Q?e=4%3a5RjKNu&at=9
It does not show even my Calendar....
Where I done mistake please tell me....
It is very important module in my project...
In my organization no WebDevelopers are there, and I am new to this Codeigniter...
Based on the information provided both in the question and the comments, the the reason for the problem is this:
<!-- Calendar.php --> <!-- Calendar_model.php -->
in your AJAX Response. Your response must contain JSON only and nothing else. No other text, no whitespace at the start and end...nothing except the JSON. If you include other data like this then jQuery (and thus fullCalendar) cannot parse the JSON correctly.
Please ensure that the server is not outputting extra data in the response. That will fix the problem.

how to add data from Employee table to user table in YII2 advanced

I am working on my collage project i.e. Employee Management. I have Employee table in sql(crud is also generated from gii). only Admin is having rights to create Employee (there is no Signup).
My Problem: when I am creating employee then I am not able to save data in user table also, please help me to save data in both Employee and user table.
Thanks in advance
Update:
Below is the code:
public function actionCreate() {
$model1=new Employee;
$model2=new User;
if(isset($_POST['Employee']) && isset($_POST['User']))
{
$model1->attributes=$_POST['Emoloyee'];
$model2->attributes=$_POST['User'];
$model1->save();
$model2->save();
echo 'data is saved in both tables';
}
$this->render('create',array('model1'=>$model1,model2'=>$mod‌​‌​el2));
}
could be you have some validation problem
try check this way
......
$model1->attributes=$_POST['Emoloyee'];
$model2->attributes=$_POST['User'];
if ($model1->validate() && $model2->validate() ) {
$model1->save();
$model2->save();
} else {
$errors1 = $model1->errors;
$errors2 = $model2->errors;
var_dump($errors1);
var_dump($errors2);
exit();
}
then just for debug try using
$model1->attributes=$_POST['Emoloyee'];
$model2->attributes=$_POST['User'];
$model1->save(false);
$model2->save(false);
and check in db if the value are saved ..
You can try this example,
public function actionCreate()
{
$model = new Employee();
$user = new User();
if ($model->load(Yii::$app->request->post()) && $user->load(Yii::$app->request->post())) {
if($model->save() && $user->save()) {
Yii::$app->session->setFlash('success', 'Record saved successfully.');
} else {
//var_dump($model->getErrors());
//var_dump($user->getErrors());
Yii::$app->session->setFlash('error', 'Record not saved.');
}
return $this->redirect(['index']);
} else {
var_dump($model->getErrors());
var_dump($user->getErrors());
die();
}
return $this->render('create', [
'model' => $model,
'user' => $user,
]);
}
Follow the instruction given in below link . This should work
how to insert data to 2 tables i.e Employee and User(migrated) from single form(Employee Create) and controller in yii2

ZF2AuthAcl Module doesnt work out of the box

I picked up this ZF2AuthAcl module to make my life easier. For some reason it does not work out of the box. As soon as i activate it in Zend2 Application.config it takes over the whole site. Meaning it goes straight to login on any page i have. There is a "white list" and i tried to add pages to this in an array and it does not seem to work. I will show the Acl page that it has with the "white list" maybe i did not add them correctly or there is a better way. It is data driven also. Has anyone used this with success or know about it?
The author is the one who told me it probably has to do with the white list.
The area that i added to looked like this:
public function initAcl()
{
$this->roles = $this->_getAllRoles();
$this->resources = $this->_getAllResources();
$this->rolePermission = $this->_getRolePermissions();
// we are not putting these resource & permission in table bcz it is
// common to all user
$this->commonPermission = array(
'ZF2AuthAcl\Controller\Index' => array(
'logout',
'index'
),
);
$this->_addRoles()
->_addResources()
->_addRoleResources();
}
This is the whole thing with parts i added.
namespace ZF2AuthAcl\Utility;
use Zend\Permissions\Acl\Acl as ZendAcl;
use Zend\Permissions\Acl\Role\GenericRole as Role;
use Zend\Permissions\Acl\Resource\GenericResource as Resource;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class Acl extends ZendAcl implements ServiceLocatorAwareInterface
{
const DEFAULT_ROLE = 'guest';
protected $_roleTableObject;
protected $serviceLocator;
protected $roles;
protected $permissions;
protected $resources;
protected $rolePermission;
protected $commonPermission;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
return $this;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
public function initAcl()
{
$this->roles = $this->_getAllRoles();
$this->resources = $this->_getAllResources();
$this->rolePermission = $this->_getRolePermissions();
// we are not putting these resource & permission in table bcz it is
// common to all user
$this->commonPermission = array(
'ZF2AuthAcl\Controller\Index' => array(
'logout',
'index'
),
'Frontend\Controller\Index' => array(
'index'
),
'Blog\Controller\Blog' => array(
'blog',
'list',
'view',
'UsMap',
'maps'
)
);
$this->_addRoles()
->_addResources()
->_addRoleResources();
}
public function isAccessAllowed($role, $resource, $permission)
{
if (! $this->hasResource($resource)) {
return false;
}
if ($this->isAllowed($role, $resource, $permission)) {
return true;
}
return false;
}
protected function _addRoles()
{
$this->addRole(new Role(self::DEFAULT_ROLE));
if (! empty($this->roles)) {
foreach ($this->roles as $role) {
$roleName = $role['role_name'];
if (! $this->hasRole($roleName)) {
$this->addRole(new Role($roleName), self::DEFAULT_ROLE);
}
}
}
return $this;
}
protected function _addResources()
{
if (! empty($this->resources)) {
foreach ($this->resources as $resource) {
if (! $this->hasResource($resource['resource_name'])) {
$this->addResource(new Resource($resource['resource_name']));
}
}
}
// add common resources
if (! empty($this->commonPermission)) {
foreach ($this->commonPermission as $resource => $permissions) {
if (! $this->hasResource($resource)) {
$this->addResource(new Resource($resource));
}
}
}
return $this;
}
protected function _addRoleResources()
{
// allow common resource/permission to guest user
if (! empty($this->commonPermission)) {
foreach ($this->commonPermission as $resource => $permissions) {
foreach ($permissions as $permission) {
$this->allow(self::DEFAULT_ROLE, $resource, $permission);
}
}
}
if (! empty($this->rolePermission)) {
foreach ($this->rolePermission as $rolePermissions) {
$this->allow($rolePermissions['role_name'], $rolePermissions['resource_name'], $rolePermissions['permission_name']);
}
}
return $this;
}
protected function _getAllRoles()
{
$roleTable = $this->getServiceLocator()->get("RoleTable");
return $roleTable->getUserRoles();
}
protected function _getAllResources()
{
$resourceTable = $this->getServiceLocator()->get("ResourceTable");
return $resourceTable->getAllResources();
}
protected function _getRolePermissions()
{
$rolePermissionTable = $this->getServiceLocator()->get("RolePermissionTable");
return $rolePermissionTable->getRolePermissions();
}
private function debugAcl($role, $resource, $permission)
{
echo 'Role:-' . $role . '==>' . $resource . '\\' . $permission . '<br/>';
}
}
06/10/2016 Additional information
I have also found that this ACL page is not in any of the pages in the module. The functions are not called out anywhere in any page nor is it "use" on any page. So how is it supposed to work?
Update 06/10/2017 - Area that has been fixed.
I have found where this is used in the module.php there is a whitelist that the pages have to be added too. Below is where you add them.
$whiteList = array(
'Frontend\Controller\Index-index',
*Add whatever modules/controller/action you do not want included*
'ZF2AuthAcl\Controller\Index-index',
'ZF2AuthAcl\Controller\Index-logout'
);
Above is the conclusion of my issue. I stumbled upon it. I did not look in the module.php file. That is where the answer was.
Here is a general implementation of Zend ACL. I followed this one. If you wish you can follow this one too.
Create a file named module.acl.php in the config/ folder of your module. This file contains configuration for roles and permissions. Modify this script as you need.
ModuleName/config/module.acl.php
return array(
'roles' => array(
'guest',
'member'
),
'permissions' => array(
'guest' => array(
// Names of routes for guest role
'users-signup',
'users-login'
),
'member' => array(
// Names of routes for member role
// Add more here if you need
'users-logout'
)
)
);
You need to import the following three classes and define and initialize some methods in the Module.php.
ModuleName/Module.php
use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Role\GenericRole;
use Zend\Permissions\Acl\Resource\GenericResource;
// Optional; use this for authentication
use Zend\Authentication\AuthenticationService;
Now lets create methods that will deploy ACL and check roles and permissions.
Module::initAcl()
public function initAcl(MvcEvent $e)
{
// Set the ACL
if ($e->getViewModel()->acl == null) {
$acl = new Acl();
} else {
$acl = $e->getViewModel()->acl;
}
// Get the roles and permissions configuration
// You may fetch configuration from database instead.
$aclConfig = include __DIR__ . '/config/module.acl.php';
// Set roles
foreach ($aclConfig['roles'] as $role) {
if (!$acl->hasRole($role)) {
$role = new GenericRole($role);
$acl->addRole($role);
} else {
$role = $acl->getRole($role);
}
// Set resources
if (array_key_exists($role->getRoleId(), $aclConfig['permissions'])) {
foreach ($aclConfig['permissions'][$role->getRoleId()] as $resource) {
if (!$acl->hasResource($resource)) {
$acl->addResource(new GenericResource($resource));
}
// Add role to a specific resource
$acl->allow($role, $resource);
}
}
}
// Assign the fully prepared ACL object
$e->getViewModel()->acl = $acl;
}
Module::checkAcl()
public function checkAcl(MvcEvent $e) {
// Get the route
$route = $e->getRouteMatch()->getMatchedRouteName();
// Use this if you have authentication set
// Otherwise, take this off
$auth = new AuthenticationService();
// Set role as you need
$userRole = 'guest';
// Use this if you have authentication set
// Otherwise, take this off
if ($auth->hasIdentity()) {
$userRole = 'member';
$loggedInUser = $auth->getIdentity();
$e->getViewModel()->loggedInUser = $loggedInUser;
}
// Check if the resource has right permission
if (!$e->getViewModel()->acl->isAllowed($userRole, $route)) {
$response = $e->getResponse();
// Redirect to specific route
$response->getHeaders()->addHeaderLine('Location', $e->getRequest()->getBaseUrl() . '/404');
$response->setStatusCode(404);
return;
}
}
Now call those above methods on the onBootstrap() method in your Module.php. Initialize Module::initAcl() and check resource permission by adding Module::checkAcl() to the route event.
Module::onBootstrap()
public function onBootstrap(MvcEvent $e)
{
$this->initAcl($e);
$e->getApplication()->getEventManager()->attach('route', array($this, 'checkAcl'));
}
Let us know it helps you or not!

Base Table not found on unique value validation in MongoDB with laravel

I'm using laravel 5.3 with jenssegers/laravel-mongodb package for managing mongodb connections.
I want to check every time a user send a request to register a website in my controller if it's unique then let the user to register his/her website domain.
I wrote below code for validation but What I get in result is :
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'iranad.seat' doesn't exist (SQL: select count(*) as aggregate from `seat` where `domain` = order.org)
my controller code :
public function store(Request $request) {
$seat = new Seat();
$validator = Validator::make($request->all(), [
'domain' => 'required|regex:/^([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/|unique:seat', //validating user is entering correct url like : iranad.ir
'category' => 'required',
]);
if ($validator->fails()) {
return response()->json($validator->messages(), 400);
} else {
try {
$statusCode = 200;
$seat->user_id = Auth::user()->id;
$seat->url = $request->input('domain');
$seat->cats = $request->input('category');
$seat->filter = [];
if($request->input('category') == 'all') {
$obj['cats'] = 'false';
$seat->target = $obj;
} else {
$obj['cats'] = 'true';
$seat->target = $obj;
}
$seat->status = 'Waiting';
$seat->save();
} catch (\Exception $e) {
$statusCode = 400;
} finally {
$response = \Response::json($seat, $statusCode);
return $response;
}
}
}
My Seat Model :
namespace App;
use Moloquent;
use Carbon\Carbon;
class Seat extends Moloquent {
public function getCreatedAtAttribute($value) {
return Carbon::createFromTimestamp(strtotime($value))
->timezone('Asia/Tehran')
->toDateTimeString();
}
}
Obviously The validator is checking if domain is unique in mysql tables which causes this error, How can I change my validation process to check mongodb instead of mysql ?
I solved the problem, The solution is that you should add Moloquent to your model and define database connection :
namespace App\Models;
use Moloquent;
use Carbon\Carbon;
class Seat extends Moloquent
{
protected $collection = 'seat';
protected $connection = 'mongodb';
}