I am developing api with Lumen 6.2.0 which gets GET request with certain parameters and token. When it gets parameters it process it in a certain way and then encode with a secret key which is in my .env file and then compares result with the token which was provided with the request, if comparison result is true then user is authenticated else he is not. So the problem is sometimes env() function returns null. It doesn't happen pretty often, just like 1 request out of 15, but it's still a serious problem for me.
I googled a lot but found just few approaches. Firstly I found out that env() function should be only invoked in config file and since Lumen doesn't have a config directory and config files I have created it, but the issue remains the same. The second advice was for Laravel specifically - php artisan config:clear and php artisan config:cache but Lumen doesn't have such commands, although I ran the php artisan cache:clear command to no avail. So here is my code:
.env file
APP_NAME=Example
APP_ENV=local
APP_KEY=ApPkEyHeRe
APP_DEBUG=true
APP_URL=https://example.com
APP_TIMEZONE=UTC
LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=dbname
DB_USERNAME=dbuser
DB_PASSWORD=dbpass
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
VK_APP_SECRET=SoMeFaNcYkEy
config/config.php
<?php
return [
'vk_app_secret' => env('VK_APP_SECRET'),
'events_per_page' => 16
];
And UsersController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class UsersController extends Controller
{
public function check(Request $request) {
$query_params = $request->all();
$sign_params = [];
foreach ($query_params as $name => $value) {
if (strpos($name, 'vk_') !== 0) {
continue;
}
$sign_params[$name] = $value;
}
ksort($sign_params);
$sign_params_query = http_build_query($sign_params);
$secret = config('config.vk_app_secret');
$hash_hmac = hash_hmac('sha256', $sign_params_query, $secret, true);
$base_encode = base64_encode($hash_hmac);
$trim_chars = strtr($base_encode, '+/', '-_');
$sign = rtrim($trim_chars, '=');
$status = $sign === $query_params['sign'];
return json_encode($status);
}
}
I also logged every line of this algorithm, and noticed an interesting thing, the failing case contains [date] production.INFO: prefix before log's rows, and every successful case [date] local.INFO: So maybe it's affecting env() function somehow? I also don't get it why it sometimes logged as production when I have APP_ENV=local
Related
I want to run my tests without receiving "CSRF token mismatch" exceptions. In the laravel documentation is noted that:
The CSRF middleware is automatically disabled when running tests.
the line of code where the exception is thrown looks like this:
$response = $this->json('POST', route('order.create'), [
'product_id', $product->id
]);
and for running tests I am working in my zsh terminal:
php artisan test --env=testing
This is my test class:
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;
class SessionCartTest extends TestCase
{
public function testExample()
{
$product = \App\Product::inRandomOrder()->first();
$response = $this->postJson(route('order.insert'), [
'product_id' => $product->id,
]);
$response->assertStatus(200); // here I receive 419
}
}
What am I doing wrong and how could I fix this? I am using laravel 7.
I ran into this problem x times now and each time I fix it by running:
php artisan config:clear
Probably the APP_ENV is not being set to testing.
You can set a ENV variable in the command line by preceding the php command.
So on your case set the environment to testing and run the artisan command by:
APP_ENV=testing php artisan test
Your data array is wrong. Try the following change:
$response = $this->postJson(route('order.insert'), [
'product_id' => $product->id, // use the arrow notation here.
]);
When you are running tests on Docker where the APP_ENV is hard coded with other values than testing (dev, local) in docker-compose.yaml file, phpunit cannot execute tests properly.
You will need to delete the all APP_ENV in docker files.
This works by setting a custom csrf-token
$this
->withSession(['_token' => 'bzz'])
->postJson('/url', ['_token' => 'bzz', 'other' => 'data']);
Hello im trying to get information about user on my view.
Here is my UserController
public function getUser(Request $request, $id)
{
$user = User::findOrFail($id);
return view('admin.user', ['user' -> $user]);
}
here is my web.php
Route::get('admin/user/{id}', "UsersController#getUser");
and my user view
#extends('admin.layouts.app')
#section('contents')
<h1>User {{ $user }} </h1>
#endsection
I am trying to display user information in this view, like name etc, but im recives 404
Not Found page. What im doing wrong. Im using Laravel 6
404 error may refer to a User not being found, since you have a findOrFail() query. It may have nothing to do with your routes.
Just double check with:
php artisan route:list
just to make sure the route is being registered correctly.
I think you firstly use any prefix for this route.For this it will give you an error.To check route list.
php artisan route:list
it will give you all route.
And Here you don't need (Request $request) because here you just need the id.it not the problem..i give you just this suggestion
public function getUser($id)
{
$user = User::findOrFail($id);
return view('admin.user', ['user'=> $user]);
}
why you use '-> ' you should use '=>'
I'm having a problem with Auth. I'm just learning about Laravel, I'm doing login. I don't know how to fix it it says:
Method Illuminate\Auth\SessionGuard::users does not exist.
this is my code in login function
public function getlogin(Request $request){
$this->validate($request, [
'email'=> 'required|max:32',
'password'=> 'required|max:32|min:8',
]);
if (Auth::attempt(['email'=>$request->email,'password'=>$request->password])) {
$user = users::where('email','=',$request->email)->first();
return redirect('/messenger')->with('usersignin');
}
return "ooopps something wrong";
}
and this is where the name from the database will be display
<div class="">
<h1>Welcome
#if(session('user'))
{{session('user')}}
#elseif(session('usersignin'))
{{ucwords(Auth::users()->fname)}}
#endif</h1>
</div>
You need to use user instead of users, user is provided with Auth and will get the current logged in user id.
$id = \Auth::user()->id;
Or you want to get the user
$user = \Auth::user();
I solved this error by running the below command
php artisan jwt:secret
php artisan cache:clear
php artisan config:cache
in your if statement just use it as below
if (auth()->attempt(['email'=>$request->email,'password'=>$request->password])) {
$user = users::where('email','=',$request->email)->first();
return redirect('/messenger')->with('usersignin');
}
I have named routes:
admin.post.category
admin.post.tag
admin.post.theme
routes\admin.php
Route::group(['prefix' => 'post', 'as' => 'post.'], function () {
Route::resource('category', 'Admin\Post\TermsController');
Route::resource('theme', 'Admin\Post\TermsController');
Route::resource('tag', 'Admin\Post\TermsController');
});
Http\Controller\Admin\Post\TermsController
public function __construct(Request $request)
{
$this->request = $request;
$route_name = Route::currentRouteName();
$arr = explode('.', $route_name);
echo "<pre>".print_r($arr[2], 1)."</pre>"; exit;
}
When I visit the page http://localhost/admin/post/category, it can show category. But when I run command
php artisan route:list
It shows
[ErrorException]
Undefined offset: 2
If I move the three lines from __construct() to index()
$route_name = Route::currentRouteName();
$arr = explode('.', $route_name);
echo "<pre>".print_r($arr[2], 1)."</pre>"; exit;
Then "php artisan route:list" runs well.
How to fix this?
It's throwing the error because you have some routes with names that contain only 1 dot. So when you access $arr[2] it's undefined and thus the error Undefined offset: 2. Looks like your shoving every route method into a single controller. When you try to run php artisan route:list it checks every route, thereby invoking the constructor, so it fails for routes with names with just 1 dot. Change your code to this and it should work.
$route_name = \Route::currentRouteName();
$arr = explode('.', $route_name);
if (isset($arr[2])) {
echo "<pre>".print_r($arr[2], 1)."</pre>";
}
exit;
After long searches in the forum, I can't find a helpful solution for my case.
I did alot of functions for sending emails in laravel and always that works fine.
This time, I got an error as you see below:
ErrorException in StreamBuffer.php line 95:
stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
Here my .env file
APP_ENV=local
APP_DEBUG=true
APP_KEY=base64:FMtA/k/okcPZB/HbWGbw5YiBM4EC3njxxLbgcdM1GrA=
APP_URL=http://localhost
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=myDB
DB_USERNAME=root
DB_PASSWORD=
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=suckerblood2010#gmail.com
MAIL_PASSWORD=<<Here_my_password>>
MAIL_ENCRYPTION=tls
MAIL_SENDER=Administration
Here my function to send the mail (in the controller Auth):
public function register(Request $request)
{
$this->validateLogin($request);
$token = hash('sha256', str_random(100) . time(), false);
$user = new User();
$user->email = $request->get('email');
$user->password = bcrypt($request->get('password'));
$user->remember_token = $token;
//$user->save();
$sent = Mail::send('auth.emails.createAccount', ['token' => $token], function ($m) use ($user) {
$m->from(getenv('MAIL_USERNAME'), getenv('MAIL_SENDER'));
$m->to($user->email, $user->email)->subject(config('constants.AccountCreated'));
});
if($sent == 1)
{
$msg = Lang::get('messages.EmailSent');
$this->showLoginForm($msg);
}
else
{
return redirect('/login')->withErrors([
'email' => Lang::get('messages.UserAddingError')
]);
}
}
I tried to change the protocol from tls to ssl, even the prot from 587 to 465
I have this problem only with this project and I can't understand why, despite all the searches I made...
Any suggestion please?
Thanks alot :)
Your root certificate is missing or corrupted, try installing one
# 1) Download a valid root ca
http://curl.haxx.se/ca/cacert.pem
# 2) Setup php.ini to point it
openssl.cafile=C:\php5\etc\cacert.pem
To make sure they are loaded, review this console command response
php -r 'var_dump(openssl_get_cert_locations());
You may need to restart your webserver
You can also disable ssl peer verification in php.ini, but it is not recommend (please don't do this in production!)
openssl.verify_peer 0
Useful docs: http://php.net/manual/migration56.openssl.php