Доступ к почтовым данным, отправленным в Auth.redirect

Я столкнулся с проблемой с функциональностью Auth.redirect в Cakephp 2.5.3. Ниже приведен сценарий:

сценарий

Существует действие (controller => TalkComments, action => add), которое защищено входом в систему. Данные передаются в это действие с использованием метода POST HTML.
Теперь, если пользователь не вошел в систему, он переходит к представлению входа в систему. Как только пользователь входит в систему, он успешно перенаправляет пользователя на требуемый контроллер и действие.
Проблема в том, что он также не отправляет данные POST, из-за чего функция add () не выполняется.

Как я могу сделать Auth.redirect, чтобы он также сохранял мои данные и отправлял их после вызова redirectUrl.

Ниже приведен мой код:

UsersController.php

class UsersController extends AppController {

//put your code here

public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'login');
}

public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}

public function logout() {
return $this->redirect($this->Auth->logout());
}
public function isAuthorized() {
return true;
}
}

TalkCommentsController.php

class TalkCommentsController extends AppController {

//put your code here
public function add() {
if ($this->request->is('post')) {
$this->TalkComment->create();
if ($this->TalkComment->save($this->request->data)) {
$this->Session->setFlash(__('Comment Saved'));
return $this->redirect($this->referer());
}
$this->Session->setFlash(__('Could not post comment'));
}
}

public function isAuthorized() {
return true;
}
}

Пожалуйста, дайте мне знать, если что-то еще потребуется от моего конца.

Заранее спасибо 🙂

0

Решение

Единственный способ сделать эту работу нормально, это использовать Сессионный компонент !

AuthComponent не позволит вам получить доступ к действию добавления, пока вы не пройдете проверку подлинности. Таким образом, мы будем использовать функцию beForeFilter в нашем AppController, как это правильно задокументировано Вот, как это:

  public function beforeFilter() {
//i used strtolower function the test is a case sensitive & i do not know the output of $this->params['controller'] and $this->params['action'] in your application but in this case it will work fine !
if((strtolower($this->params['controller']) == 'talkcomments') && (strltolower($this->params['action']) == 'add') && ($this->is('post')){
//do not forget to use Session Component in AppController before to use!
$this->Session->write('data',$this->data);
}
}

Теперь настало время использовать данные, хранящиеся в нашей сессии, чтобы автоматически добавлять записи!

  public function login() {

if ($this->request->is('post')) {
if ($this->Auth->login()) {
$comment = $this->Session->read('data');
if(isset($comment) && !empty($comment)){
$this->loadModel('TalkComment');
$this->TalkComment->set($comment);
if($this->TalkComment->validate()){
if($this->TalkComment->save($comment))
$this->Session->setFlash(__('Comment Saved'));
else
$this->Session->setFlash(__('Could not post comment'));
}
else
$this->Session->setFlash(__('Could not post comment'));
}
return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}

это должно работать для вас как шарм.


private function DYnamicAdd($model, $data, $success_message, $error_message){
$record = $data;
if(isset($record) && !empty($record)){
App::uses($model,'model');
$this->$model->set($record);
if($this->$model->validate()){
if($this->$model->save($data))
$this->Session->setFlash($success_message);
else
$this->Session->setFlash($error_message);
}
else
$this->Session->setFlash($error_message);
}

Давайте сделаем пример:

мы предполагаем, что у нас есть два контроллера, у которых есть метод добавления, TestOnesController, TestTwosController! Тогда метод входа будет таким

public function login(){
if ($this->request->is('post')) {
if ($this->Auth->login()) {

//in the case of TestOnesController
$this->DynamicAdds('TestOne', $this->Session->read('TestOne'), 'Testone Saved', 'Could not post Testone');

//in the case of TestTwosController
$this->DynamicAdds('TestTwo', $this->Session->read('TestTwo'), 'Testtwo Saved', 'Could not post Testtwo');

return $this->redirect($this->Auth->redirectUrl());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}

В действии beforeFilter на AppController!

Также динамическое письмо в Сессии с:

public function beforeFilter(){
//C1 C2 C3 C4 are the controllers you may have a Add method in
if(in_array(strtolower($this->params['controller']), array('C1','C2','C3','C4')) && (strltolower($this->params['action']) == 'add') && ($this->is('post')){
//ucfirst and singularize to extract the name of the model from controller name !
$this->Session->write(ucfirst(Inflector::singularize($this->params['controller'])),$this->data);
}
}
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector