How to response a 404 page in phalcon? - phalcon

When id is not exists,I want to response a 404 page to client.
$something = Something::findFirst($id);
if (!$something) {
//response a 404 page
}
How to do it?

You want to use forward() method from Dispatcher class.
if ($somethingFailed) {
return $this->dispatcher->forward(['controller' => 'index', 'action' => 'error404']);
}
// Controller method
function error404Action()
{
$this->response->setStatusCode(404, "Not Found");
$this->view->pick('_layouts/error-404');
$this->response->send();
}
Question with similar problem: Redirecting to 404 route in PhalconPHP results in Blank Page

Assuming you are in a controller
$something = Something::findFirst($id);
if (!$something) {
return $this->response->redirect('/404');
}
or you can forward to a different action using the dispatcher
$this->dispatcher->forward(
[
'controller' => 'utils',
'action' => 'notfound',
]
);

Related

cakephp3 entities relationship error when login (the error is going after refresh)

I am struggling with this issue for a few days. I've tried to debug step by step with Xdebug, but I cannot find where it is the problem.
Basically when login into the cakephp3.9 I get this error:
App\Model\Table\UsersTable association "Roles" of type "manyToMany" to "Slince\CakePermission\Model\Table\RolesTable" doesn't match the expected class "App\Model\Table\RolesTable".
You can't have an association of the same name with a different target "className" option anywhere in your app.
As I mentioned above, I am using cakephp 3.9 and the slince package ("slince/cakephp-permission": "^1.0") to manage roles/permissions. After get this error if I refresh the browser evertyhing works as normal. The error only appears once, always after login.
Relations in UsersTable.php
$this->belongsToMany('Roles', [
'foreignKey' => 'user_id',
'targetForeignKey' => 'role_id',
'joinTable' => 'users_roles'
]);
UsersController.php
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
if (Configure::read('Options.status') == 2) {
$this->Flash->error('Please confirm your account - click on the validation link emailed to you');
return $this->redirect(['action' => 'login', 'controller' => 'Users']);
}
$UsersRoles = TableRegistry::getTableLocator()->get('UsersRoles');
// Get User role_id
$AuthRole = $UsersRoles
->find()
->select(['role_id'])
->where(['user_id' => $user['id']])
->first();
// if the status of the user is false an error appears and it will be redirected back || check if is an admin role?
if ($user['status'] != 1 || $AuthRole->role_id > 3) {
$this->Flash->error('Your account is not authorized to access this area. Contact the support team or check your inbox');
return $this->redirect(['action' => 'login', 'controller' => 'Users']);
}
$Roles = TableRegistry::getTableLocator()->get('Roles');
// Get Role name
$AuthRoleName = $Roles
->find()
->select('name')
->where(['id' => $AuthRole['role_id']])
->first();
$user['role_id'] = $AuthRole['role_id'];
$user['role_name'] = $AuthRoleName['name'];
// Set the use into the session
$this->Auth->setUser($user);
// Save the previous login date to the session and enable tour vars
$session = $this->getRequest()->getSession();
if (empty($user['last_login'])) {
$session->write('Options.run', true);
$session->write('Options.player', true);
}
// Now update the actual login time
$this->Users->updateLastLogin($this->Auth->user('id'));
// Handle case where referrer is cleared/reset
$nextUrl = $this->Auth->redirectUrl();
if ($nextUrl === "/") {
return $this->redirect(['action' => 'index', 'controller' => 'Adminarea']);
} else {
return $this->redirect($nextUrl);
}
}
$this->Flash->error(__('Invalid username or password, please try again'));
}
$this->viewBuilder()->setLayout('admin_in');
}
The issue it is in the relationship "Roles", it already exists in the file "PermissionsTableTrait.php" from the slice package, and it seems that cannot be two relationships with the same name.

About the implementation of Remember Me using AuthenticationPlugin's Cookie Authenticator

I use CakePHP's AuthenticationPlugin. I was trying to implement RememberMe functionality into this.
I found the following article when I was reading the Cakephp documentation.
Cookie Authenticator aka “Remember Me”
However, the documentation here is difficult for me to understand. I have no idea what to do with it.
I've successfully implemented EncryptedCookieMiddleware. I have no idea what to do after that.
I don't know how to use rememberMeField, how to use fields and how to use cookies.
$this->Authentication->rememberMeField
$this->Authentication->fields
I tried to see if I could use it like these, but it was still no good.
Please let me know how to use these.
Also, do you know of any RememberMe tutorials?
How do I implement it?
Sorry. Please help me...
// in config/app.php
'Security' => [
.....
'cookieKey' => env('SECURITY_COOKIE_KEY', 'AnyString'), // <- add
],
// in src/Application.php
use Cake\Http\Middleware\EncryptedCookieMiddleware; // <- add
// in middleware()
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
$cookies = new EncryptedCookieMiddleware( // <- add
['mail', 'password'],
Configure::read('Security.cookieKey')
);
$middlewareQueue
// . . .
->add($cookies) // <-add
->add(new AuthenticationMiddleware($this));
So far I've been able to implement it myself. I'm confident.
The problem is after this. We have no idea what to do with it...
A Remember me checkbox was implemented in the template Form.
$this->request->getData('rememberMe'); to get it.
If this is 1, the checkbox was pressed.
// in src/Controller/UsersController
public function login()
{
$this->request->allowMethod(['get', 'post']);
if ($this->request->is('post')) {
$result = $this->Authentication->getResult();
// If the user is logged in, whether POST or GET, we will redirect
$requestGetData = $this->request->getData('rememberMe');
if ($requestGetData['rememberMe'] == 1){
$this->Authentication->cookie['name'] = $requestGetData['mail'];
$this->Authentication->cookie['name'] = $requestGetData['password']
}
if ($result->isValid()) {
$redirect = $this->request->getQuery('redirect', [
'controller' => 'Stores',
'action' => 'index',
]);
return $this->redirect($redirect);
}
// If the user fails to authenticate after submitting, an error is displayed.
if (!$result->isValid()) {
$this->Flash->error(__('Your email address or password is incorrect.'));
}
}
$title = $this->config('Users.title.login');
$message = $this->config('Users.message.login');
$this->set(compact('login_now', 'title', 'message'));
}
I know that's not true. But I tried to implement something like this just in case.
Please help me!
Changed around the login.
public function login()
{
$this->request->allowMethod(['get', 'post']);
if ($this->request->is('post')) {
$result = $this->Authentication->getResult();
$requestData = $this->request->getData();
if ($result->isValid()) {
$redirect = $this->request->getQuery('redirect', [
'controller' => 'Stores',
'action' => 'index',
]);
$this->Authentication->getAuthenticationService()->loadAuthenticator( 'Authentication.Cookie', [
'fields' => ['mail', 'password']
]
);
return $this->redirect($redirect);
}
if ($this->request->is('post') && !$result->isValid()) {
$this->Flash->error(__('Your email address or password is incorrect.'));
}
}
$title = $this->config('Users.title.login');
$message = $this->config('Users.message.login');
$this->set(compact('title', 'message'));
}
You're not supposed to load authenticators in your controllers, authentication happens at middleware level, before any of your controllers are being invoked.
The cookie authenticator is ment to be loaded and configured just like any other authenticator, that is where you create the authentication service, usually in Application::getAuthenticationService() in src/Application.php.
By default the field in the form must be remember_me, not rememberMe, that is unless you would configure the cookie authenticator's rememberMeField option otherwise.
Furthermore the default cookie name of the cookie authenticator is CookieAuth, so if you wanted to encrypt it, you'd have to use that name in the EncryptedCookieMiddleware config accordingly.
tl;dr
Remove all cookie related code from your controller, and load the authenticator in your Application::getAuthenticationService() method:
use Authentication\Identifier\IdentifierInterface;
// ...
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface
{
$service = new AuthenticationService();
// ...
// The cookie authenticator should be loaded _after_ the session authenticator,
// and _before_ other authenticators like the form authenticator
$service->loadAuthenticator('Authentication.Cookie', [
// 'rememberMeField' => 'custom_form_field_name', // if you want to change the default
'fields' => [
IdentifierInterface::CREDENTIAL_USERNAME => 'mail',
IdentifierInterface::CREDENTIAL_PASSWORD => 'password',
],
]);
// ...
return $service;
}
set the authentication cookie name in the EncryptedCookieMiddleware config:
$cookies = new EncryptedCookieMiddleware(
['CookieAuth'],
Configure::read('Security.cookieKey')
);
and change the field name in your form to remember_me if you're using the cookie authenticator's defaults:
echo $this->Form->control('remember_me', [
'type' => 'checkbox'
]);
That's all that should be required, if you tick the checkbox in your login form, then the authentication middleware will set a cookie after successful authentication accordingly, and it will pick up the cookie if it's present on a request and no other authenticator successfully authenticates the request first (like the session authenticator for example).

CakePHP3 CRUD API and API Routing

I am using the Friends of Cake CRUD plugin for my back-end API. I am also using API prefixes for my routes:
Router::prefix('Api', function ($routes) {
$routes->extensions(['json', 'xml', 'ajax']);
$routes->resources('Messages');
$routes->resources('ReportedListings');
$routes->fallbacks('InflectedRoute');
});
So far so good. My controller is as follows:
namespace App\Controller\Api;
use App\Controller\AppController;
use Cake\Event\Event;
use Cake\Core\Exception\Exception;
class MessagesController extends AppController {
use \Crud\Controller\ControllerTrait;
public function initialize() {
parent::initialize();
$this->loadComponent(
'Crud.Crud', [
'actions' => [
'Crud.Add',
'update' => ['className' => 'Crud.Edit']
],
'listeners' => ['Crud.Api'],
]
,'RequestHandler'
);
$this->Crud->config(['listeners.api.exceptionRenderer' => 'App\Error\ExceptionRenderer']);
$this->Crud->addListener('relatedModels', 'Crud.RelatedModels');
}
public function beforeFilter(Event $event){
parent::beforeFilter($event);
}
public function add() {
return $this->Crud->execute();
}
When I make a call as follows:
[POST] /api/messages.json
I get an error:
Action MessagesController::index() could not be found, or is not accessible.
I instead use:
[POST] /messages.json
I don't get the error and I can add a message. So the question is why with my api prefix routing does the CRUD look for index and how can I avoid this behavior?
I found the issue:
Router::prefix('Api', function ($routes) {
....
}
The 'Api' should be lowercase!
Router::prefix('api', function ($routes) {
....
}

Laravel API give json response when got error This action is unauthorized

I newbie in Laravel API. There is an update function which only allows users to update their own post. It worked. When users try to update other user's post, it alswo worked, but it shows the error like this image. Actually i want it show in response json.
I want to show message like this
{
"status": "error",
"message": "This action is unauthorized",
}
This is my code for PostController.
public function update(Request $request, Post $post)
{
$this->authorize('update', $post);
//this will check the authorization of user but how to make if else statement, if the post belong to the user it will show this json below but if the post belong to other, it will show error message(response json)
$post->content = $request->get('content', $post->content);
$post->save();
return fractal()
->item($post)
->transformWith(new PostTransformer)
->toArray();
}
This code for PostPolicy
public function update(User $user, Post $post)
{
return $user->ownsPost($post);
}
This is code for User model
public function ownsPost(Post $post)
{
return Auth::user()->id === $post->user->id;
}
This code for AuthServiceProvider
protected $policies = [
'App\Post' => 'App\Policies\PostPolicy',
];
Hope anyone can help me.
I'm using Laravel 5.4
In the app/Exceptions/Handler.php class you can change the render function like so
public function render($request, Exception $exception)
{
$preparedException = $this->prepareException($exception);
if ($preparedException instanceof HttpException) {
return response(
[
'message' => sprintf(
'%d %s',
$preparedException->getStatusCode(),
Response::$statusTexts[$preparedException->getStatusCode()]
),
'status' => $preparedException->getStatusCode()
],
$preparedException->getStatusCode(),
$preparedException->getHeaders()
);
}
return parent::render($request, $exception);
}
Or if you look further in the rendering, overriding the renderHttpException might be a little safer. This will remove the custom error pages in views/errors
protected function renderHttpException(HttpException $e)
{
return response(
[
'message' => sprintf(
'%d %s',
$e->getStatusCode(),
Response::$statusTexts[$e->getStatusCode()]
),
'status' => $e->getStatusCode()
],
$e->getStatusCode(),
$e->getHeaders()
);
}

yii friendly url for modules does not work

I created a modules called calculator and am trying to create the freindly url for it.
here is my code
'<action:(calc1|calc2|calc3)>' => '/calculator/<action>',
the view files are in
modules/calculator/view/default/pages/calc2.php
when i type in my address bar
localhost/dev/cal2
i get this error
Error 404
Unable to resolve the request "calculator/calc2".
in my controller i have this
class DefaultController extends Controller
{
public function actions() {
return array(
'page' => array('class' => 'CViewAction'),
);
}
public function actionIndex()
{
$this->render('index');
}
}
the default page shows when i go to http://localhost/dev/calculator but the inner pages in the modules doesn't.
here is my regex
'<view:(about|terms|faq|privacy)>' => 'site/page',
'<action:(contact|login|logout)>' => 'site/<action>',
'<fileName:(calc1|calc2|calc3)>' => '/calculator/default/page/view/<fileName>',
'<action:(registration|create)>' => 'user/<action>',
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
any idea what i'm doing wrong?
In order to use the page action your urls should resolve to /<module>/<controller>/page/view/<fileName> where fileName is calc1, calc2 etc. Therefore in your case your rules should be:
'<fileName:(calc1|calc2|calc3)>' => '/calculator/default/page/view/<fileName>',
Reference: http://www.yiiframework.com/wiki/22/how-to-display-static-pages-in-yii/
First you need to define your action in your calculator controller:
class CalculatorController extends Controller
{
public function actionCalc1()
{
$this->render('calc1');
}
public function actionCalc2()
{
$this->render('calc2');
}
public function actionCalc3()
{
$this->render('calc3');
}
}
Of course you've to change your view paths and then you should see something when you type into your browser <your domain>/calculator/calc2.