Assert 403 Access Denied http status with PHPUnit test case - unit-testing

I have a custom error templates in my projects for 404, 403 and other exceptions. I want to create unit test case to assert http errors. When I am logging with user and accessing authorized page of Vendor I am getting 403 Access denied in browser but in Unit test case I am always getting 404 page not found error.
Here is my test scenario:
class ErrorExceptionTest extends WebTestCase
{
public function testAccessDeniedException()
{
$server['HTTP_HOST'] = 'http://www.test.com/';
$client = static::createClient(array('debug' => false), $server);
$client->disableReboot();
$session = $client->getContainer()->get('session');
$firewall = 'main';
$token = new UsernamePasswordToken('user', null, $firewall, array('ROLE_USER'));
$session->set("_security_$firewall", serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$client->getCookieJar()->set($cookie);
$client->request('GET', '/vendor/profile/edit');
$this->assertEquals(403, $client->getResponse()->getStatusCode());
$this->assertContains('Sorry! Access Denied', $client->getResponse()->getContent());
}
}
My test case is being failed, when I print response content it will show 404 error template.

Worked around it and find the issue. So, my solution is no need to use http host.
public function testAccessDeniedException()
{
$client = static::createClient(array('debug' => false));
$session = $client->getContainer()->get('session');
$firewall = 'main';
$token = new UsernamePasswordToken('user', null, $firewall, array('ROLE_USER'));
$session->set("_security_$firewall", serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$client->getCookieJar()->set($cookie);
$client->request('GET', 'fr/vendor/profile/edit');
$this->assertEquals(403, $client->getResponse()->getStatusCode());
$this->assertContains('Sorry! Access Denied', $client->getResponse()->getContent());
}

Related

POST failed via Postman API to Laravel migrations database

GET is working, but POST does not. This is because it fails via Postman API to the Laravel migrations database.
function add_user(Request $request)
{
$user = new user_a;
csrf_token();
$user->user_name = $request->user_name;
$user->password = $request->password;
$res = $user->save;
if ($res) {
return ["operationn" => "Done"];
} else {
return ["operation" => "failed_404"];
}
}
in API file:
Route::post('registeruser',[dynamic_small_controller::class,'add_user']);
You are trying to send the password in integer format so it is not accepting try with giving password also in ""
{
"user_name":"yahay",
"password":"8888"
}

How can I properly get the errors in unit testing laravel as well as disable csrf checks?

I'm trying to test my post method in the controller. The method definition is something like :
public function store(Request $request)
{
$article = new Article;
$article->id = $request->input('article_id');
$article->title = $request->input('title');
$article->body = $request->input('body');
return response(["success"], 200);
}
I've created a test which just stores the data and checks if the response is 200.
Please also show me how can I make this test better new to testing. But I'm getting 404 error I don't know what is the error. How can I display the errors what are the setting I need to configure?
Test:
public function test_post_new_article(){
$article = factory(Article::class)->make();
$this->call('POST', 'article', [
'_token' => csrf_token(),
'article_id' => 6,
'title'=>"hey",
'body' => "this is a body"
])->assertStatus(200);
}
phpunit error:
There was 1 failure:
1) Tests\Unit\ExampleTest::test_post_new_article
Expected status code 200 but received 404.
Failed asserting that false is true.
I'm assuming you defined the route in routes/api.php such that the prefix of your particular route is /api/.
You have to call the full path to the API route:
$this->call('POST', '/api/article', [
'_token' => csrf_token(),
'article_id' => 6,
'title'=>"hey",
'body' => "this is a body"
])->assertStatus(200);
Also, since CSRF should be implemented in your Middleware layer, and it's tedious and silly to add _token to all your test requests, you should probably just disable middleware in your tests:
use Illuminate\Foundation\Testing\WithoutMiddleware;
class MyControllerTest {
use WithoutMiddleware;
... public function testmyUnitTest() { ... }
}

Error message: "The SMTP server requires a secure connection or the client was not authenticated."

I have searched other posts and set required things in my gmail account(https://myaccount.google.com/lesssecureapps)
but somehow it still throws exception with the message "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at"
[HttpPost]
public ActionResult SaveAppointment(Appointment mdl)
{
try
{
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.Credentials = new System.Net.NetworkCredential("username", "mypass");
smtpClient.UseDefaultCredentials = false;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
//Setting From , To and CC
mail.From = new MailAddress("username#gmail.com", "MyWeb Site");
mail.To.Add(new MailAddress("username#gmail.com"));
smtpClient.Send(mail);
return View();
}
catch(Exception ex)
{
return null;
}
}
What should it be I missing?
Check your web.config, msdn and code (because there could be no matching EnableSsl in the configuration file.
You may also need to enable access for "less secure apps" in your gmail settings page. here
This is necessary if you are getting the exception "`The server response was: 5.5.1 Authentication Required. Then below code should works.
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("username", "password"),
EnableSsl = true
};
client.Send("username#gmail.com", "username#gmail.com", "subject", "body");

Box API newbie connection problems

I'm trying to connect to the box-api to read the files of my user in my folder. I've created the folder and uploaded the files, then i went to the OAuth2 interface to obtain an API Key. It has given the api key to me so i pasted it in the code:
public function indexAction()
{
try {
$uri = "https://api.box.com/2.0/folders/0/items?limit=100&offset=0";
$config = array(
'adapter' => 'Zend_Http_Client_Adapter_Curl',
'curloptions' => array(CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTPHEADER=>array("Authorization: Bearer MYKEY"),
CURLOPT_SSL_VERIFYPEER, false,
CURLOPT_USERPWD, "user:password"),
);
$client = new Zend_Http_Client($uri, $config);
$response = $client->request();
$text= $response->getBody();
} catch (Zend_Exception $e) {
echo "Message: " . $e->getMessage() . "\n";
// Other code to recover from the error
}
}
Following this tutorial on youtube.
The error i'm getting is the following:
Message: Error in cURL request: unable to use client certificate (no key found or wrong pass phrase?)
I registered the application with the name "test". What have I done wrong? What am I missing?
You might try passing the request without the CURLOPT_SSL_VERIFYPEER and CURLOPT_USERPWD options. I don't think those are strictly necessary -- to my knowledge Box doesn't do any client certificate validation -- and they may be causing the problem.
The use of Zend http client by itself is better than using the curl adapter.Besides the username and password are not required to authenticate. You can perform the operation only after you have received th access token from the authorization procedure of Oauth2 of Box-API. The zend http client call that can be used is the following:
$client = new Zend_Http_Client('https://api.box.com/2.0/folders/0');
$client->setMethod(Zend_Http_Client::GET);
$client->setHeaders('Authorization: Bearer '.$access_token);
$response = $client->request()->getBody();
My 2 cents.

Facebook OAuthException: (#1)

I have a few applications which upload image to user profile. A few hours ago all applications were working fine but now when uploading is requested, it gives this error
Fatal error: Uncaught OAuthException: (#1) An unknown error occurred thrown in applications/fb-sdk/facebook.php on line 543
I'm using the following code to publish image.
$FILE = "images/$image";
$args = array('message' => 'My msg ');
$args['image'] = '#' . realpath($FILE);
$data = $facebook->api('/'.$uid.'/photos', 'post', $args);
Is it because of some policy change or some new feature?
I have all the permissions like upload is set to true and application takes permission to upload file.
P.s: when the application is used 2nd time, it works fine.
You need to verify if the user is logged in AND has the permissions to post on wall. We're going to do that with a TRY/CATCH with a call to the user.
$userId = $facebook -> getUser();
if ($userId) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$userId = NULL;
error_log($e);
}
}
$app_permissions = array(
'scope' => 'publish_stream'
);
$logoutUrl = $facebook->getLogoutUrl();
$loginUrl = $facebook->getLoginUrl($app_permissions);
If the user is not logged in OR has authorized the app, you'll need to redirect him via header redirect or with a link.
if ($userId){
//Then you can call the facebook api
$data = $facebook->api('/'.$uid.'/photos', 'post', $args);
//... ...
}
That's the easiest way i've found.
EDIT : This question on stack has helped me : Facebook PHP SDK Upload Photos
No, the error is caused by the system cannot get the image file. Facebook will not allow the empty image field appear in the api. So it return Fatal error: Uncaught OAuthException: (#1) --- although it does not relate to the OAuth and OAuthException.