Silex - How to pass Request $request to $app->error(function (\Exception $e, $code) use ($app) { - error-handling

I am new to Silex. I am trying to pass Request $request to $app->error(...){...}. Normally it would look like so:
$app->error(function(\Exception $e, $code) use ($app) { ...
I want to use Request within the error controller. The code below will generate en error. Any idea how to snick the Request $request object into this controller ? so I will have access to request->getPathInfo() ?
//...
$app->error(function(\Exception $e, $code, Request $request) use ($app) {
if (404 === $code) {
$path = $request->getPathInfo();
$path = explode('/',$path);
if($path[1] == 'php'){
return $app->redirect($app['url_generator']->generate('php'));
}
if($path[1] == 'css'){
return $app->redirect($app['url_generator']->generate('css'));
}
//...
return $app->redirect($app['url_generator']->generate('home'));
}
// Do something else (handle error 500 etc.)
});
// RUN
$app->run();

$path = $app['request']->getPathInfo();
$app->error(function(\Exception $e, $code) use ($app) {
if (404 === $code) {
$path = $app['request']->getPathInfo();
$path = explode('/',$path);
echo $path[1];
if($path[1] == 'php'){
return $app->redirect($app['url_generator']->generate('php'));
}
if($path[1] == 'css'){
return $app->redirect($app['url_generator']->generate('css'));
}
//...
return $app->redirect($app['url_generator']->generate('home'));
}
// Do something else (handle error 500 etc.)
});
// RUN
$app->run();
Now I can redirect users when 404 based on the area they are in - to different predefined paths.

$this->error(
function (\Exception $e, Request $request, $code) {
//yours code here
}
);

Try this code,
Request::createFromGlobals()

Related

How can I properly redirect to a route in Laravel 8?

I tried every similar question I found here, but none worked.
I have these two groups and I just want to redirect to each specific route according to the type of user, i`m using Laravel 8 + inertia and vue 3
Route::prefix('user')->namespace('App\Http\Controllers\Customer')->middleware(['role', 'auth'])->group(function () {
Route::resource('dashboard', DashboardController::class)->only('index');
Route::resource('accounts', MyAccountController::class);
});
Route::prefix('staff')->namespace('App\Http\Controllers\Staff')->middleware(['role', 'auth'])->group(function () {
Route::resource('dashboard', DashboardController::class)->only('index');
Route::resource('accounts', MyAccountController::class);
});
// role middleware
public function handle(Request $request, Closure $next)
{
if (!\Auth::check())
return redirect('login.index');
if ($request->user() && $request->user()->isAdmin()) {
$path = $request->path();
if( strpos($request->path(), 'user/') !== FALSE ) {
$path = str_replace('staff/', 'user/', $request->path());
}
return redirect($path);
} else {
$path = $request->path();
if( strpos($request->path(), 'staff/') !== FALSE ) {
$path = str_replace('staff/', 'user/', $request->path());
}
return redirect($path);
}
return $next($request);
}

how to show results one by one in codeigniter 4 for loop with ob_flush

my problem is: i wan to show data in real time with codeigniter 4
This code results will be out once the for loop is ended
what i wan to do is echo results one by one
i have alrady done this before but not with codeigniter, it's was my own code without any framwork
but now i am stiked here 1 week and no rsults
i use codeigniter 4
and i use aapanel in my server
and this is my phpinfo
my function in my controller Count.php
function startcounter(){
$count = $this-\>request-\>getPost("count");
if (ob_get_level() == 0) ob_start();
for($i=0; $i\<=$count; $i++){
echo $i;
ob_flush();
flush();
sleep(1);
}
ob_end_flush();
exit();
}
My javascript
function startcounter(){
data = "count=5";
var xhr = new XMLHttpRequest();
xhr.open('POST', baseUrl+'/count/startcounter', true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState == 1) {
resp = xhr.response;
arrs = resp;
if (xhr.readyState == XMLHttpRequest.LOADING) {
console.log(xhr.responseText);
}
if (xhr.readyState == XMLHttpRequest.DONE) {
alert('Done')
}
}
}
}
function testflush(){
ini_set('output_buffering','on');
ini_set('zlib.output_compression', 0);
ini_set('max_execution_time', '3000');
ob_implicit_flush();
$response = service('response');
$response->send();
ob_end_flush();
flush();
for($i=0; $i<=99; $i++){
echo "Test".$i;
ob_flush();
flush();
sleep(1);
}
return $this->response->setJSON(''); // send empty json response (This is
the most important thing)
}

Flutter : How to delete Rest Api Using Http.Client?

I develope App for CRUD Operation rest api using Http Client. GET and POST work perfectly, but problem come after DELETE Operation.
Console Message show me response code Bad Request 400 **, I Check code rest Api (in my codeigniter) **Bad Request 400 it's means the ID is null or not passing the ID on URL Rest Api.
It's Console Message Image
But I try on POSTMAN and **DELETE* is perfectly work , i dont know why in flutter http.delete not working.
It's Result POSTMAN Working
My Api Url for Delete
http://192.168.43.159/wpu-rest-server/apii/mahasiswa/delete/
It's My API.dart :
Future<bool> checkPost(Map<String, dynamic> id) async {
final client = http.Client();
try {
final response = await client.send(http.Request(
"DELETE", Uri.parse("${Urls.BASE_API_URL}mahasiswa/delete/"))
..headers['Content-type']= 'application/x-www-form-urlencoded'
..body = jsonEncode(id));
print(response.reasonPhrase);
print(response.statusCode.toString());
print(response.request.toString());
return response.statusCode == 204;
} finally {}
}
It's My list.dart :
void _checkPost() async{
final post = {"id":widget.id};
bool result = await api.checkPost(post);
if (result) {
_showSnackBar(
context, 'Success ');
} else {
_showSnackBar(context, 'Failed');
return null;
}
}
If you need Rest Api Code :
Controller
public function delete_delete()
{
$id = $this->delete('id');
$msgDelete = ['id' => $id, 'message' => 'Deleted the resource'];
$msgEmpty = ['status' => false, 'message' => 'ID Not Found'];
$msgBadRequest = ['status' => false, 'message' => 'Provide an ID'];
if ($id === null) {
$this->set_response($msgBadRequest, 400);
} else {
if ($this->mahasiswa->deleteMahasiswa($id) > 0) {
$this->set_response($msgDelete, 204);
} else {
$this->set_response($msgEmpty, 404);
}
}
}
Model
public function deleteMahasiswa($id = null)
{
if ($id === null) {
return false;
} else {
$this->db->delete('mahasiswa', ['id' => $id]);
return $this->db->affected_rows();
}
}
I'm mistake something ?
I ever heard httpclient.delete can't add body , but in POSTMAN need add body for deleting data, how to handle this ?

ZF2 - init or something that is called in every module controller

I have a Module called "Backend" and in this module I want to check for valid authentication on all pages except the backend_login page. How do I do this? I tried to add it to the onBootstrap in the Backend/Module.php , but it turns out that is called in my other modules as well... which is of course not what I want.
So how do I do this?
Thanks in advance!
To get clear information about zf2 authentication you can follow:
ZF2 authentication
adapter auth
database table auth
LDAP auth
digest auth....These all are different methods here is an example of database table auth:
in every controller's action, where you need user auth something should like this:
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Db\Adapter\Adapter as DbAdapter;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;
public function login($credential)
{
$bcrypt = new Bcrypt();
$user = new User();
$auth = new AuthenticationService();
$user->exchangeArray($credential);
$password = $user->password;
$data = $this->getUserTable()->selectUser($user->username);
if (!$data){
$message = 'Username or password is not correct!';
}
elseif($auth->getIdentity() == $user->username){
$message = 'You have already logged in';
}
elseif($bcrypt->verify($password, $data->password)){
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$authAdapter = new AuthAdapter(
$dbAdapter,
'user',
'username',
'password'
);
$authAdapter -> setIdentity($user->username) -> setCredential($data->password);
$result = $auth->authenticate($authAdapter);
$message = "Login succesfull.Welcome ".$result->getIdentity();
} else {
$message = 'Username or password is not correct';
}
return new ViewModel(array("message" =>$message));
}
Like this in every action you can check whether it is authenticated or not
if($auth -> hasIdentity()){
//your stuff
}
else{
//redirected to your login route;
}
I had once a similar problem and figured it out within my Module.php in the onBootstrap() function. Try this, it worked for me:
class Module {
// white list to access with being non-authenticated
//the list may contain action names, controller names as well as route names
protected $whitelist = array('login');
//....
public function onBootstrap($e){
$app = $e->getApplication();
$em = $app->getEventManager();
$sm = $app->getServiceManager();
$list = $this->whitelist;
$auth = new AuthenticationService();
$em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($list, $auth) {
$match = $e->getRouteMatch();
// No route match, this is a 404
if (!$match instanceof RouteMatch) {
return;
}
// Route is whitelisted
$action = $match->getParam('action');
if (in_array($action, $list) ) {
return;
}
// User is authenticated
if ($auth->hasIdentity()){
return;
}
// the user isn't authenticated
// redirect to the user login page, as an example
$router = $e->getRouter();
$url = $router->assemble(array(
'controller' => 'auth',
'action'=>'login'
), array(
'name' => 'route_name',
));
$response = $e->getResponse();
$response->getHeaders()->addHeaderLine('Location', $url);
$response->setStatusCode(302);
return $response;
}, -100);
}
}
Or you may see bjyauthorize.

Yii::app()->user->isGuest always returns true even though login was successful

I started to make some differences between those users which have authenticated and those that not. For this, i am using
Yii::app()->user->id;
However, in a determined view i put the following code:
<?php
if(Yii::app()->user->isGuest) {
print("Welcome back Guest!");
print("Your id is ".Yii::app()->user->id);
} else {
print("Welcome back ".Yii::app()->user->name);
print("Your id is ".Yii::app()->user->id);
}?>
And i always get the "welcome back guest!", whether i have logged in (successfully) or not. And if i have logged in, then it displays the welcome message together with the user's id!
EDIT
#briiC.lv
Hey.. sorry for the late reply, I hope you are still following this! I am not extending the given UserIdentity class. Is this mandatory? Since i still dont get very well the whole authorization issue, i thought it would be best to give a try with the class they provide, and then extend with my own functionality.. Anyway, next i post my UserIdentity class with its small tweaks.. maybe the problem lies here??
<?php class UserIdentity extends CUserIdentity{
private $_id;
public function authenticate()
{
$user = Users::model()->findAll('username=\''.$this->username.'\' AND password=\''.$this->encryptedPassword.'\'');
if(!isset($user[0]))
{
return false;
}
else
{
$this->setState('id', $user[0]->id);
$this->username = $user[0]->username;
$this->errorCode=self::ERROR_NONE;
return true;
}
}
public function getId()
{
return $this->_id;
}
}
Here is the output i got when i started to log as you suggested; i got this output immediately after successfully logging in.
[05:23:21.833][trace][vardump] CWebUser#1 (
[allowAutoLogin] => true
[guestName] => 'Guest'
[loginUrl] => array ( '0' => '/site/login' )
[identityCookie] => null
[authTimeout] => null
[autoRenewCookie] => false
[autoUpdateFlash] => true
[CWebUser:_keyPrefix] => '0f4431ceed8f17883650835e575b504b'
[CWebUser:_access] => array()
[behaviors] => array()
[CApplicationComponent:_initialized] => true
[CComponent:_e] => null
[CComponent:_m] => null
)
Any help is much appreciated!
Maybe you can try to debug harder:
change messages to something like this:
if(Yii::app()->user->isGuest) {
print("Not logged");
} else {
print_r(Yii::app()->user);
print("Welcome ".Yii::app()->user->name);
print("Your id is ".Yii::app()->user->id);
}
And check session variable in your config/main.php file
...
'session' => array(
'autoStart'=>true,
),
...
The error is in the following line
$this->setState('id', $user[0]->id);
As seen in the official yii documentation regarding auth & auth, setState should be used for anything but the id field. In order to implement the key Yii will use to identify your user, return a unique value per user in the Identity getId() function.
In your case, this means you simply have to change the above line into the following:
$this->_id = $user[0]->id;
Regarding the actual inner working of the login procedure, I'd recommend a look at the CWebUser class, and especially at its login function, which is responsible for the actual storage of the Identity getId() return value.
when you call authenticate function login user as
$userIdentity = new UserIdentity($username, $password);
$userIdentity->authenticate();
if ($userIdentity->errorCode===UserIdentity::ERROR_NONE) {
Yii::app()->user->login($userIdentity,0);
}
and fetch id as
echo 'id='.Yii::app()->user->getId();
apply this code and check
I have faced same problem and found that only one line in UserIdentity Component will resolve this issue.
This is your code:
else
{
$this->setState('id', $user[0]->id);
$this->username = $user[0]->username;
$this->errorCode=self::ERROR_NONE;
return true;
}
Update this code by this one
else
{
$this->_id = $user[0]->id;
$this->setState('id', $user[0]->id);
$this->username = $user[0]->username;
$this->errorCode=self::ERROR_NONE;
return true;
}
First of all, you need to know condition that sets guest and logged-in user apart.
Based on Yii master's branch CWebUser::getIsGuest():
public function getIsGuest()
{
return $this->getState('__id')===null;
}
Compared to your code:
$user = Users::model()->findAll('username=\''.$this->username.'\' AND password=\''.$this->encryptedPassword.'\'');
if(!isset($user[0])) {
// false
} else {
$this->setState('id', $user[0]->id); // this is for persistent state sakes
...
}
}
In short: you did supply 'id' to Identity persistent state but Yii CWebUser expecting '__id' based on UserIdentity::getId().
Solution is pretty dead simple. You just need to set $this->_id
$user = Users::model()->findAll('username=\''.$this->username.'\' AND password=\''.$this->encryptedPassword.'\'');
if(!isset($user[0])) {
// false
} else {
$this->setState('id', $user[0]->id); // this is for persistent state sakes
$this->_id = $user[0]->id; // this is UserIdentity's ID that'll be fetch by CWebUser
...
}
}
This routine explains how CWebUser get UserIdentity's ID: https://github.com/yiisoft/yii/blob/master/framework/web/auth/CWebUser.php#L221
Please do test it out.
Please try following code. Its working well
//config/main.php
return array (
'component' => array(
'session' => array(
'savePath' => INSTANCE_ROOT.DS.'runtime'.DS.'session',
'autoStart' => true,
),
)
);
// LoginController
class LoginController extends CController {
public function actionLogin () {
if(isset($_POST['LoginForm']))
{
$form = new LoginForm;
$form->setAttributes($_POST['LoginForm']);
if ($form->validate()) {
$user = Users::model()->find('upper(username) = :username', array(
':username' => strtoupper($form->username)));
if($user)
return $this->authenticate($user, $form);
else {
Yii::log( 'som.....', 'error');
$form->addError('password', Yii::t('Username or Password is incorrect'));
}
return false;
}
}
}
protected function authenticate($user, $form) {
$identity = new UserIdentity($user->username, $form->password);
$identity->authenticate();
switch($identity->errorCode) {
case UserIdentity::ERROR_NONE:
$duration = $form->rememberMe ? 3600*24*30 : 0; // 30 days
Yii::app()->user->login($identity,$duration);
return $user;
break;
case UserIdentity::ERROR_EMAIL_INVALID:
$form->addError("password",Yii::t('Username or Password is incorrect'));
break;
case UserIdentity::ERROR_STATUS_INACTIVE:
$form->addError("status",Yii::t('This account is not activated.'));
break;
case UserIdentity::ERROR_STATUS_BANNED:
$form->addError("status",Yii::t('This account is blocked.'));
break;
case UserIdentity::ERROR_STATUS_REMOVED:
$form->addError('status', Yii::t('Your account has been deleted.'));
break;
case UserIdentity::ERROR_PASSWORD_INVALID:
Yii::log( Yii::t(
'Password invalid for user {username} (Ip-Address: {ip})', array(
'{ip}' => Yii::app()->request->getUserHostAddress(),
'{username}' => $form->username)), 'error');
if(!$form->hasErrors())
$form->addError("password",Yii::t('Username or Password is incorrect'));
break;
return false;
}
}
}
class UserIdentity extends CUserIdentity {
const ERROR_EMAIL_INVALID=3;
const ERROR_STATUS_INACTIVE=4;
const ERROR_STATUS_BANNED=5;
const ERROR_STATUS_REMOVED=6;
const ERROR_STATUS_USER_DOES_NOT_EXIST=7;
public function authenticate()
{
$user = Users::model()->find('username = :username', array(
':username' => $this->username));
if(!$user)
return self::ERROR_STATUS_USER_DOES_NOT_EXIST;
if(Users::encrypt($this->password)!==$user->password)
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else if($user->status == YumUser::STATUS_INACTIVE)
$this->errorCode=self::ERROR_STATUS_INACTIVE;
else if($user->status == YumUser::STATUS_BANNED)
$this->errorCode=self::ERROR_STATUS_BANNED;
else if($user->status == YumUser::STATUS_REMOVED)
$this->errorCode=self::ERROR_STATUS_REMOVED;
return !$this->errorCode;
}
}
class Users extends CActiveModel
{
const STATUS_INACTIVE = 0;
const STATUS_ACTIVE = 1;
const STATUS_BANNED = -1;
const STATUS_REMOVED = -2;
// some ..........
public static function encrypt($string = "")
{
$salt = 'salt';
$string = sprintf("%s%s%s", $salt, $string, $salt);
return md5($string);
}
}
check your security configuration for cookies and sessions.
disable session.use_only_cookies & session.cookie_httponly in php.ini
file.
in PHP.INI => session.use_only_cookies = 0