Zend framework 2 logoutAction - php

How to implement logout action in Zend Framework 2?
I am building my first ever zend application for matrimony site.
When I click on logout link user is logged out but his session is not expired,like when I click on the menu of edit profile or search profile the user session is still active.So how will I be able to implement that.
LoginController
public function indexAction()
{
$id=$this->params()->fromQuery('id');
if($id!="")
{
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$sql = "UPDATE projects SET confirmation='Y' where memcode = '$id'";
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
}
$form = new LoginForm();
$viewModel = new ViewModel(array('form' =>$form));
return $viewModel;
}
public function getAuthService()
{
if (! $this->authservice) {
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter,'projects','email','password', 'MD5(?)');
$authService = new AuthenticationService();
$authService->setAdapter($dbTableAuthAdapter);
$this->authservice = $authService;
}
return $this->authservice;
}
public function processAction()
{
$this->getAuthService()->getAdapter()->setIdentity($this->request->getPost('email'))->setCredential($this->request->getPost('password'));
$result = $this->getAuthService()->authenticate();
if ($result->isValid()) {
$this->getAuthService()->getStorage()->write($this->request->getPost('email'));
return $this->redirect()->toRoute(NULL , array(
'controller' => 'login',
'action' => 'confirm'
));
}
else {
return $this->redirect()->toRoute(NULL , array(
'controller' => 'login',
'action' => 'index1'
));
}
}
public function confirmAction()
{
$user_email = $this->getAuthService()->getStorage()->read();
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$sql = "SELECT name,memcode,gender,castenobar FROM projects where email = '$user_email'";
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$user = $result->current();
$user_session = new Container('user');
$user_name = $this->getAuthService()->getStorage()->read();
$user_session->username= $user['name'];
$user_session->usermemcode= $user['memcode'];
$user_session->usergender= $user['gender'];
$user_session->usercastenobar= $user['castenobar'];
$username = $user_session->username;
$usergender = $user_session->usergender;
$usercastenobar = $user_session->usercastenobar;
if($usercastenobar=='Y'){
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$selectData = array();
foreach ($result as $res) {
$selectData[]=$res;
}
return new ViewModel(array(
'selectData' => $selectData,
'user_name' => $username
));
}
else
{
$sql="select * from projects where gender !='".$usergender."' and castenobar='N'";
//echo $sql;
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$statement = $dbAdapter->query($sql);
$result = $statement->execute();
$selectData = array();
foreach ($result as $res) {
$selectData[]=$res;
}
return new ViewModel(array(
'selectData' => $selectData,
'user_name' => $username
));
}
}
public function logoutAction()
{
//$this->getAuthService()->clearIdentity();
$storage = new \Zend\Authentication\Storage\Session();
$storage->clear();
return $this->redirect()->toRoute(NULL , array(
'controller' => 'login',
'action' => 'index'
));
}

Your "logoutAction()" should look like this:
public function logoutAction()
{
$name = 'Zend_Auth' ;
$container = new Container($name);
$container->getManager()->getStorage()->clear($name);
return $this->redirect()->toRoute(NULL , array(
'controller' => 'login',
'action' => 'index'
));
}
If you don't define name of session's container, use the default name 'Zend_Auth' in $name, otherwise in $name you must use your own name for the session container.
Your "$this->redirect()..." doesn't logout user and it doesn't clear the 'Zend_Auth' container. It only redirects to another site. The user is still logged in / active. To be sure that the user is logged in or logged out you can use:
$auth = new AuthenticationService();
if ($auth->hasIdentity()) {
return $this->redirect()->toRoute(NULL , array(
'controller' => 'login',
'action' => 'index'
));
}

Related

Generate a unique link for each name - yii2

I am working on development of web app, Users are supposed to register on the web app.
This is my table where data is being stored post registration.
I would like to give every user a unique url which would be stored in the same table where details of the users is being saved so that their profile url shares their society name (society_name). For example, the website domain would be www.example.com and the users' url would be www.example.com/mysociety
I would like to save the unique generated url in in the field "url"(#14) of my table.
My User Register Controller looks like this
public function actionRegister() {
$this->layout = 'society';
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new User();
$society = new \app\models\Society();
if ($model->load(Yii::$app->request->post())) {
$password= $_POST['User']['password'];
$password_hash = Yii::$app->security->generatePasswordHash($password);
$auth_key = Yii::$app->security->generateRandomString();
$mobile=$_POST['User']['mobile'];
$society = new \app\models\Society();
$random_number=mt_rand(10000, 99999);
$society->society_name = $_POST['Society']['society_name'];
$society->contact_person = $_POST['Society']['contact_person'];
$society->address = $_POST['Society']['address'];
$society->society_id =$random_number;
$society->mobile = $mobile;
$society->status =0;
$society->save();
$session = Yii::$app->session;
return $this->redirect(['regsuccess']);
}
return $this->render('society', [
'model' => $model,
'society' => $society,
]);}
PS : English is not my native language. I am newbie to yii2 and stackoverflow, please excuse me for the mistakes.
Thanks.
I solved it.
Modified my Controller
public function actionRegister() {
$this->layout = 'society';
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new User();
$society = new \app\models\Society();
if ($model->load(Yii::$app->request->post())) {
$password= $_POST['User']['password'];
$password_hash = Yii::$app->security->generatePasswordHash($password);
$auth_key = Yii::$app->security->generateRandomString();
$mobile=$_POST['User']['mobile'];
$society = new \app\models\Society();
$random_number=mt_rand(10000, 99999);
$vp_string = trim($_POST['Society']['society_name']);
$vp_string = html_entity_decode($vp_string);
$vp_string = strip_tags($vp_string);
$vp_string = strtolower($vp_string);
$vp_string = preg_replace('[^ a-z0-9_\.]', ' ', $vp_string);
$vp_string = preg_replace('~ ~', '-', $vp_string);
$society->society_name = $_POST['Society']['society_name'];
$society->contact_person = $_POST['Society']['contact_person'];
$society->address = $_POST['Society']['address'];
$society->society_id =$random_number;
$society->mobile = $mobile;
$society->url = $vp_string;
$society->status =0;
$society->save();
$session = Yii::$app->session;
return $this->redirect(['regsuccess']);
}
return $this->render('society', [
'model' => $model,
'society' => $society,
]);}

how to get single result using mongo odm?

i make a setting action in which i used doctrine query for getting single result but it returns null while data exist in database,how i get single result?here is my code:
public function settingsAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('calendar', array(
'action' => 'create'
));
}
//echo $id;
//$calendar = $id;//$this->getCalendarTable()->getCalendar($id);
$calendar = $documentManager->getRepository('Calendar\Document\Calendar')->find($id);
$form = new CalendarForm();
$form->bind($calendar);
$form->get('submit')->setAttribute('value', 'Save');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($calendar->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
//$this->getCalendarTable()->saveCalendar($form->getData());
return $this->redirect()->toRoute('calendar', array('action' => 'show', 'id' => $id));
}
}
return array(
'id' => $id,
'form' => $form,
);
}
You don't need to create a query to fetch by id as the DocumentRepository already provides this via it's find($id) method.
Just use the document manager to fetch the repository
$document = $documentManager->getRepository('FooDocument')->find($id);
You can also use the convenience method find($documentName, $id) directly on the document manager.
$document = $documentManager->find('FooDocument', $id);

how i save data in zf2 using mongoDB with Doctrine 2 ODM?

i make a controller in zf2 for save data in mongodb but it not save any record in event table,how i save data?here is my code:
public function createAction()
{
$calendar_id = (int) $this->params()->fromRoute('id', 0);
if ($calendar_id == 0) {
return $this->redirect()->toRoute('calendar', array(
'action' => 'index'
));
}
//echo $calendar_id;
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
$form = new EventForm();
$update=false;
$message='';
$form->get('calendar_id')->setValue($id);
$form->get('submit')->setValue('Add');
if ($this->getRequest()->isPost()) {
$post = $this->getRequest()->getPost();
$form->setInputFilter($form->getInputFilter());
$form->setData($post);
if ($form->isValid()) {
$formData=$form->getData();
$s = new Event();
$s->setProperty('calendar_id',$calendar_id);
$s->setProperty('title',$post['title']);
$s->setProperty('description',$post['description']);
$s->setProperty('startdate',$post['begin']);
$s->setProperty('enddate',$post['end']);
$dm->persist($s);
$dm->flush();
$update=1;
$message='calendar Added Successfully.';
//$form = new CalendarForm();
//$this->redirect()->toRoute('calendar');
}
}
return array('form' => $form, 'add_message' => $message, 'update' => $update, 'calendar'=>$this->calendar);
}
I set code and save data using mongoodm,here is my code:
public function createAction()
{
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
$calendar_id = (int) $this->params()->fromRoute('id', 0);
if ($calendar_id == 0) {
return $this->redirect()->toRoute('calendar', array(
'action' => 'index'
));
}
$form = new EventForm();
$update=false;
$message='';
$form->get('calendar_id')->setValue($calendar_id);
$form->get('submit')->setValue('Add');
if ($this->getRequest()->isPost()) {
$post = $this->getRequest()->getPost();
$form->setInputFilter($form->getInputFilter());
$form->setData($post);
if ($form->isValid()) {
$formData=$form->getData();
$s = new Event();
$s->setProperty('calendar_id',$post['calendar_id']);
$s->setProperty('title',$post['title']);
$s->setProperty('description',$post['description']);
$s->setProperty('startdate',$post['begin']);
$s->setProperty('enddate',$post['end']);
$dm->persist($s);
$dm->flush();
$update=1;
$message='calendar Added Successfully.';
$form = new EventForm();
$this->redirect()->toRoute('calendar');
}
}
return array('form' => $form, 'add_message' => $message, 'update' => $update, 'calendar'=>$this->calendar);
}

How to get last inserted id in zf2?

I am new in zf2. I make a create action and want to get last inserted id but calender_id always equal to zero. How can I get the last insert id in create action ?
Here is my code:
public function createAction()
{
if ($this->zfcUserAuthentication()->hasIdentity())
{
$form = new CalendarForm();
$form->get('user_id')->setValue($this->zfcUserAuthentication()->getIdentity()->getId());
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost()) {
$calendar = new Calendar();
$form->setInputFilter($calendar->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$calendar->exchangeArray($form->getData());
$this->getCalendarTable()->saveCalendar($calendar);
if($request->isXmlHttpRequest()) {
//$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
//$calender = new \Calendar\Model\Calendar($dm);
$response = new Response();
$calender_id = $calendar->calendar_id;
$userid =$calendar->user_id;
$title=$calendar->title;
$description=$calendar->description;
$output = array('success' => true, 'calendar_id' => $calender_id, 'user_id' => $userid, 'title' => $title, 'description' => $description);
//$response->headers->set('Content-Type', 'application/json');
$response->setContent(json_encode($output));
return $response;
}
return $this->redirect()->toRoute('calendar');
}
}
return array('form' => $form);
}
else
{
$this->redirect()->toRoute('zfcuser/login');
}
}
how i get last inserted id?
If your calendarTable extends TableGateway you can use $calendarTable->getLastInsertValue() to get the last insert id. You can also use this method in your saveCalendar method.

Why is Zend DB Update not posting?

Other modules in the application are updating, besides this one.
Here, I am using a model mapper in attempts to update a row set, as found in http://framework.zend.com/manual/en/learning.quickstart.create-model.html
public function SomeAction()
{
$mapper = new Application_Model_SomeMapper();
$model = new Application_Model_SomeModel(); //getters and setters
// action body
$request = $this->getRequest();
$data = $this->_request->getParams();
$someId = $data['someid'];
$get = $mapper->find($someId, new Application_Model_SomeModel, true); //find the row by id, and return array
/*
instantiating a form object and adding "submit"
*/
$form = new Module_Form_FormName();
$form->setAction("/module/controller/action/params/$someId");
$form->setMethod('post');
$form->setName('some_edit');
$submit = $form->createElement('button', 'submit');
$submit->setAttrib('ignore',true);
$submit->setLabel('Edit Something');
$form->addElement($submit);
if ($this->_request->isPost())
{
if($form->isValid($request->getPost()))
{
$data = $this->_request->getPost();
if(empty($data['some_id' ]))
{
$data['tier_models_id'] = NULL;
}
unset($data['submit']);
$setters = $model->setId($data['id'])
->setField1($data['field_1']);
if ($mapper->save($someId, $setters))
{
$this->_redirect("/index/");
}
}
}
$form->populate($tier);
$this->view->form = $get;
}
Here is an example of the save mapper function, except I've included an additional $id parameter
public function save(Application_Model_Guestbook $guestbook)
{
$data = array(
'email' => $guestbook->getEmail(),
'comment' => $guestbook->getComment(),
'created' => date('Y-m-d H:i:s'),
);
if (null === ($id = $guestbook->getId())) {
unset($data['id']);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('id = ?' => $id)); //not happening, although the 'id' is passed as a param
}
}
Is there something missing?
Try this instead
$where = $this->getDbTable()->getAdapter()->quoteInto('id = ?', $id);
$this->getDbTable()->update($data, $where);

Categories