Using aws smtp mail service in laravel 5.4 application - php

I want to send a mail to the company's office mail(other than email field for login) when a candidate appy for the job posting
Controller function
public function ImmediateApply(Request $request) {
try {
$request['resume'] = $this->image->uploadImage($request->resume, 'resumes');
if (ImmediateApply::where('job_post_id', '=', $request->job_post_id)->where('email', '=', $request->email)->count() == 0) {
$application = ImmediateApply::create($request->all());
$job = JobPost::find($request->job_post_id);
$company = Company::find($job->company_id);
$company->notify(new JobApplication($job));
return response()->json([
'message' => 'You have applied successfully',
'code' => '201']);
}
} catch (Exception $e) {
return response()->json([
'message' => $e->getMessage(),
'code' => 400,
], 400);
}
}
company model
public function routeNotificationForMail() {
return $this->office_mail;
}
Now I'am getting the error
1.Failed to authenticate on smtp server with username "x" using 2
possible authenticators
2.CredentialsException in InstanceProfileProvider.php line 79: Error
retrieving credentials from the instance profile metadata server.
(Error creating resource: [message]
fopen(http://169.254.169.254/latest/meta-data/iam/security-credentials/):
failed to open stream: Connection timed out [file]
/var/www/html/jobs-website/laravel5.4/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php
[line] 312)
But when i check in smtp online test, I'am recieving the mail correctly

Actually i don't know the reason for the 1st error.It doesn't persist now.
Changing
MAIL_DRIVER = ses
from
MAIL_DRIVER = smtp
solved the 2nd error.
now everything working fine.

Related

Laravel Eloquent doesn't want to save itself on DB

So here it is, I'm trying to make an email confirmation system. Everything is very simple, when creating the account, an account and a token are created and an email with a link containing the email address and the token is sent to the email address used to create the account. The links contained in the email bring back one on a route in GET which has as parameter the email address as well as the token and this route executes a function in a controller and what this function does is mainly to check if the account is already confirmed, if not, it checks if the token is valid and if it is, it changes the value of "emailConfirmed" from false to true. It is able to set itself to true, that is not the problem. The problem is that it does not send this new value of true to the database
Here is the function in my controller:
public function confirmMail($email, $theToken)
{
$user = ZUser::where('email', $email)->take(1)->get()[0];
if ($user->emailConfirmed == false) // If email is not confirmed
{
$token = Token::where('email', $email)->where('token', $theToken)->first(); // Get the line where there is the same email and token then in the URL
if (!is_null($token) || !empty($token)) // If $token is not null or not empty, so if the query found something
{
$user->emailConfirmed = true;
try
{
$user->save();
}
catch (Excpetion $e)
{
return response()->json(['message'=> "Error while saving", 'success' => false, 'status' => "Request Failed", 'id' => null], 400);
}
return response()->json(['message'=> "The value of emailConfirmed is $user->emailConfirmed", 'success' => false, 'status' => "Request Failed", 'id' => null], 400);
}
return response()->json(['message'=> "Cannot confirm the email, non-existent account", 'success' => false, 'status' => "Request Failed", 'id' => null], 400);
}
return response()->json(['message'=> "Email already confirmed", 'success' => false, 'status' => "Request Failed", 'id' => null], 400);
}
Here is my route:
Route::get('/confirm/mail/{email}/{token}', [ControllerUser::class, 'confirmMail'], function ($email, $token) {})->name('confirmMail');
Here is an example of the mail (it is the correct link the the confirmation page):
Here is the result of the confirmation page:
Here is the data in the database after "confirming" the email (emailConfirmed is still at 0):
I am really lost, I don't know why it isn't working since I did the same thing to be able to "create" an account, I had to execute a save on the DB. What can I do the solve the problem ?
I found the answer to my question. The problem was related with the primary key. In my model I had protected $primaryKey = 'iduser';but in my migration the name of the field was actually $table->id('idUser'); so I change my primary key in my model for protected $primaryKey = 'idUser';

how to send message remotely to kafka

I am very new to kafka. I am trying to send a message from my local machine producer to kafka server. I am not able to figure out the issue or what am doing worng.
$config = \Kafka\ProducerConfig::getInstance();
$config->setMetadataRefreshIntervalMs(10000);
$config->setMetadataBrokerList('localhost:9092');
$config->setBrokerVersion('1.0.0');
$config->setRequiredAck(1);
$config->setIsAsyn(false);
$config->setProduceInterval(500);
$producer = new \Kafka\Producer(
function() {
return [
[
'topic' => 'test',
'value' => 'test....message.',
'key' => 'testkey',
],
];
}
);
// $producer->setLogger($logger);
$producer->success(function($result) {
print_r($result);
});
$producer->error(function($errorCode) {
var_dump($errorCode);
});
$producer->send(true);
Output:-
Fatal error: Uncaught exception 'Kafka\Exception' with message 'Not has broker can connection metadataBrokerList' in C:\xampp\htdocs\vendor\nmred\kafka-php\src\Kafka\Producer\Process.php on line 193
So you're trying to produce from your local machine to a different server? If that's the case you'll need to update the line
$config->setMetadataBrokerList('localhost:9092');
to point to that server's domain name and not localhost:9092
This is the library https://github.com/weiboad/kafka-php I was using in codeigniter for the producer.
This library works fine.
The issue was that on server port number was changed, it was 29092 actually by default the port is 9092 that why the connection was failing.

How to send cURL request to Laravel App via Guzzle

I'm using Guzzle within my Laravel app to make a request to /oauth/token/ as a login request and see to be getting connection refused
My code in my custom controller is:
public function login(Request $request)
{
$http = new \GuzzleHttp\Client();
try {
$response = $http->post("https://mixapp.test/oauth/token/", [
'form_params' => [
'grant_type' => 'password',
'client_id' => config('services.passport.client_id'),
'client_secret' => config('services.passport.client_secret'),
'username' => $request->username,
'password' => $request->password,
]
]);
return $response->getBody();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if ($e->getCode() === 400) {
return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
} else if ($e->getCode() === 401) {
return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
}
return response()->json('Something went wrong on the server.', $e->getCode());
}
}
And the error seems to be:
local.ERROR: cURL error 7: Failed to connect to mixapp.test port 443: Connection refused (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) {"exception":"[object] (GuzzleHttp\Exception\ConnectException(code: 0): cURL error 7: Failed to connect to mixapp.test port 443: Connection refused
Both are be on https, and I am using laravel valet.
Actually ended up solving this. Thinking a bit harder about it, I was just calling the same server from the controller, so I changed my guzzle request to:
$response = $http->post("https://127.0.0.1/oauth/token/", [...
Thanks SO for being my rubber duck :)

force user to fill the form after obtaining the info using laravel and socialite

How to force the user to fill the form after login with google or facebook. I ma using laravel 5.4 with socials. In my app i want to allow google and facebook login but user can create a standard user too. When login with one of the social providers (facebook or google) i want the user to fill other fields in the form to complete the registration.
The handleProviderCallback:
public function handleProviderCallback($provider)
{
try{
$socialUser = Socialite::driver($provider)->stateless()->user();
}catch (Exception $e){
return redirect('/');
}
// check if we have logged PROVIDER
$socialProvider = Social::where('provider_id', $socialUser->getId())->first();
// if we don`t have a provider create a user and provider
if(!$socialProvider){
// i want the user to go back in the form and finish the registration
return view('auth.socials')->with('socialUser', $socialUser)->with('provider', $provider);
}
else{
// return the user
$user = $socialProvider->user;
}
// log the user in our app :)
auth()->login($user);
return redirect('/home');
the problem is when submiting the form i get an exception:
Client error: `POST https://accounts.google.com/o/oauth2/token` resulted in
a `400 Bad Request` response:
{
"error" : "invalid_grant",
"error_description" : "Invalid code."
}
If i use the method handleProviderCallback like this:
public function handleProviderCallback($provider)
{
try{
$socialUser = Socialite::driver($provider)->stateless()->user();
}catch (Exception $e){
return redirect('/');
}
// check if we have logged PROVIDER
$socialProvider = Social::where('provider_id', $socialUser->getId())->first();
// if we don`t have a provider create a user and provider
if(!$socialProvider){
$user = User::firstOrCreate(
['email' => $socialUser->getEmail()],
// i have to manualy add the missing fields
['name' => $socialUser->getName(), 'forename' => 'test', 'password' => '' ,'address' => 'adasda', 'country' => 'asasfasf', 'town' => 'asfasfsfsfs', 'legal_person' => '0', 'newsletter' => '1', 'phone' => '1235241521']
);
// add provider for this user
$user->socials()->create(
['provider_id' => $socialUser->getId(), 'provider' => $provider]
);
}
else{
// return the user
$user = $socialProvider->user;
}
// log the user in our app :)
auth()->login($user);
return redirect('/home');
}
the user get logged in, but as you can see i have to manually insert the missing fields in the firstOrCreate method (which are required in the users table)
Any suggestion how to do this?

Lumen 5.2 authentication

Trying to do a very simple api authentication using lumen 5.2
That is just check the header HTTP_key value to the hardcoded key value in lumen. If correct then process the api else throw an error.
I was able to implement it in php using the below code. I simply am not able to do the same in lumen. I previously used codeigniter only. So kind of new to the framework
public function auth() {
if (empty($_SERVER['HTTP_KEY'])) {
$_SERVER['HTTP_KEY'] = 0;
}
if (!($_SERVER['HTTP_KEY'] === $this->key)) {
$error = array('status' => 'Error', 'msg' => 'Authentication Failed');
$this->response($this->json($error), 401);
}
}

Categories