Generate 404 Error in yii2 - yii

I am new to Yii framework and i want to generate 404 error if user not logged in.
Here is the code from view/item/index.php:
<?php
if(Yii::$app->user->isGuest)
{
throw new CHttpException(404, 'Oops. Not logged in.');
}
?>
But I get following Error:Class 'app\models\CHttpException' not found
Thanks in advance.

wrong here : "CHttpException"
CHttpException using in Yii1
in yii2 you use
throw new NotFoundHttpException('your message');
and first of controller
use yii\web\NotFoundHttpException;

CHttpException if for Yii 1 .. for Yii2 you need HttpException
<?php
if(Yii::$app->user->isGuest)
{
throw new \yii\web\HttpException(404,'Oops. Not logged in.');
}
?>

Related

What is the correct way to return a 403 response in YII when the user enters the wrong password

Helping a friend update the code on his website for an app. Went through the code and there were tons of errors coming from the function below. I tested it and apparently every time a user put in an improper password it would throw an error that would show up in the Application Performance Console.
What is the correct way to return 403 but not consider it an error for the purposes of the Application Performance Console.
public function actionLogin($username, $password) {
if (!Yii::app()->user->isGuest) {
$this->tokenResponse();
}
$identity = new ApiClientIdentity($username, $password);
if ($identity->authenticate()) {
if (Yii::app()->user->login($identity)) {
$this->getModule('api')->onAuthenticate();
$this->tokenResponse();
}
} else {
throw new ApiBaseException(403, Yii::t('api', 'Incorrect login or password'));
}
}
If you only want to return the error code and get the code to do other things, then just use
http_response_code(403);
it will return a 403 but it will still run the following codes.

Yii - trouble at the beginning

What i did:
Instaled XAMPP (default settings)
Downloaded and instaled newest version of Yii (c:\xampp\htdocs\yii)
Made PATH (;c:\xampp\php)
I did everything what i should in CMD, after that localhost/yii/test is working but when i make new controller and i try go to site localhost/yii/test/bazadanych, then i have 404 error.
(c:\xampp\htdocs\yii\test\protected\controllers\BazadanychController.php)
<?php
class BazadanychController extends CController
{
public function actionIndex()
{
$Polaczenie = Yii::app()->db;
$Zapytanie = $Polaczenie->createCommand('CELECT * FROM osoby');
$DaneZBazy = $Zapytanie->query();
while(($Rekord=$DaneZBazy->read())!==false)
{
echo $Rekord['imie'].'<br>';
}
}
}
?>
Where did i mistake? I read polish book "yiiframework" (Author: Łukasz Sosna, printed this year) and i made step by step so i don't know what is wrong. Any ideas?

FOSRestBundle: Returning JSON/XML meta data for "Bad Credentials" Exception

I'm using FOSRestBundle for my REST API and so far it has been a great tool. I use HTTP Basic Auth and in most of the cases it works just fine. However, I have problems with the bundle's exception behaviour when bad credentials are submitted. When handling exceptions (via the integrated authentication handlers or the exception mapping configuration), the bundle always gives me a response with the correct HTTP status and JSON/XML content similar to this:
{
"code": 401,
"message": "You are not authenticated"
}
This is fine, it also works when no authentication information is submitted at all. However, when submitting bad credentials (e.g. unknown username or incorrect password) I get the HTTP code 401 Bad credentials (which is fine) with an empty message body. Instead, I would have expected something similar to the JSON above.
Is it a bug or a configuration issue on my side? I would also love to know how these kinds of authentication errors are exactly handled by the bundle, since overriding the BadCredentialsException's status code in the codes section of the bundle's exception configuration section seems to be ignored.
Thanks!
Alright, after digging into the bundle's code some more, I figured it out. The problem results from the way bad credentials are handled by Symfony's HTTP Basic Authentication impementation. The 401 Bad Credentials response is a custom response created by BasicAuthenticationEntryPoint, which is called by the BasicAuthenticationListener's handle function, immediately after an AuthenticationException has been thrown in the same function. So there is no way of catching this exception with a listener:
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (false === $username = $request->headers->get('PHP_AUTH_USER', false)) {
return;
}
if (null !== $token = $this->securityContext->getToken()) {
if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && $token->getUsername() === $username) {
return;
}
}
if (null !== $this->logger) {
$this->logger->info(sprintf('Basic Authentication Authorization header found for user "%s"', $username));
}
try {
$token = $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey));
$this->securityContext->setToken($token);
} catch (AuthenticationException $failed) {
$this->securityContext->setToken(null);
if (null !== $this->logger) {
$this->logger->info(sprintf('Authentication request failed for user "%s": %s', $username, $failed->getMessage()));
}
if ($this->ignoreFailure) {
return;
}
$event->setResponse($this->authenticationEntryPoint->start($request, $failed));
}
}
The entry point's start function creates the custom response, with no exceptions involved:
public function start(Request $request, AuthenticationException $authException = null)
{
$response = new Response();
$response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', $this->realmName));
$response->setStatusCode(401, $authException ? $authException->getMessage() : null);
return $response;
}
The fist if-clause in the handle function above also explains why it works in the case of "no user credentials at all", since in that case, the listener just stops trying to authenticate the user, and therefore an exception will be thrown by Symfony's firewall listeners (not quite sure where exactly), so FOSRestBundle's AccessDeniedListener is able to catch the AuthenticationException and do its thing.
You can extend AccessDeniedListener and tell FOSRestBundle to use your own listener with the parameter %fos_rest.access_denied_listener.class%. (service definition)
parameters:
fos_rest.access_denied_listener.class: Your\Namespace\For\AccessDeniedListener
Then add an additional check for BadCredentialsException and emmit an HttpException with the desired code/message similar to the check for AuthenticationException at Line 70.

Yii framework, Login , SQL injection

Recently I receive a email, claiming that he can change my admin password by sql injection.
Here is my code. It is developed using Yii php framework. Can anyone see the flaws?
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}
Every where you are creating sql queries, you must bind all external variable with sql variables, It will remove sql injection possibility.

how to retrieve login status while using offline_access

I'm facing a little problem because of the offline_access permission I'm requesting for my website.
I'm using the code that is given in the documentation in order to define if someone is logged or not :
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
But as I have an offline access, it seems that I'm always having a value for $user. So how can i log out someone from my website ?
Is there any way to retrieve a status via the php SDK ?
Thanks for the help,
Stéphane
In PHP try using GetLogoutUrl and sending the user there. You can also call the JS FB.logout() call from client-side. If you want to remove the app from the user, call HTTP delete to me/permissions.