Sending mails with laravel for android app forgot password functionality - laravel-5.3

I am trying to create a forgot password module for my android project which has laravel running as backend. What I'm trying to achieve is to create a random string and send it as a mail but I don't know how to do it.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App;
class FgtPswdController extends Controller
{
public function CheckEmail(Request $request){
$email = $request['email'];
$checkEmail = App\Login::where('email', '=', $email)->first();
if ($checkEmail){
$randomString = str_random(6);
App\Forgot_Password::where('email', $email)->update('reset_code', $randomString);
}
else{
$response['verification'] = false;
return json_encode($response);
}
}
}
But how do I send a mail using inbuilt functions of laravel

You can use this
Mail::raw('Your Text', function($message){
$message->to(to#host.com)->subject('Your Subject');
$message->from('email#host.com', 'Your Name');
});

Related

Using Swift Mailer with smtp on Symfony 4

I installed Swift Mailer on Symfony 4 to send a registration email for new users. What I noticed is that it works fine when I use my Gmail account to send emails, but it doesn't work when I use my Outlook.
So after reading the documentation, I set the MAILER_URL on my .env file like this
> MAILER_URL=smtp://localhost:25?encryption=ssl&auth_mode=login&username=*****%40live.com&password=******
I also used :
> MAILER_URL=smtp://smtp-mail.outlook.com:25/encryption=ssl&auth_mode=login&username=*******%40live.com&password=********
I have changed the port from 25 to 587 to 465 and none of those worked either.
This is the method where I call the mailer :
public function sendMail($subject, $fromEmail, $toEmail, $emailTemplate, $argumentsArray, $emailType, $imgPath)
{
$message = $this->setBasicEmailMessage($subject, $fromEmail, $emailTemplate, $argumentsArray, $emailType, $imgPath);
$message->setTo($toEmail);
$this->mailer->send($message);
}
private function setBasicEmailMessage($subject, $fromEmail, $emailTemplate, $argumentsArray, $emailType, $imgPath)
{
$message = (new \Swift_Message($subject))->setFrom($fromEmail);
$img = $message->embed(\Swift_Image::fromPath($imgPath));
$argumentsArray['img'] = $img;
$message->setBody(
$this->templating->render(
$emailTemplate,
$argumentsArray
),
$emailType
);
return $message;
}
And this is my swiftmailer.yaml:
swiftmailer:
url: '%env(MAILER_URL)%'
spool: { type: 'memory' }
The code doesn't raise an exception but the email never makes it to the users.
Does anyone have an idea how to fix this?
Put send function in try and catch block you will get definitely any clue:
try {
$this->mailer->send($message);
} catch (\Swift_RfcComplianceException $e) {
echo "\nException :: " . $e->getMessage();
}

Drupal 8 Class 'Drupal\Core\Session\AccountInterface' not found

I am trying to write a custom php script in my Drupal site root that checks if the user is logged in. To check this I import bootstrap.inc. However when I do this it throws me this error
This is the code of the php script in my site root:
<?php
require_once './core/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
global $user;
var_dump($user->uid);
?>
Anyone has a solution to this?
To bootstrap Drupal 8, you need different code. Drupal 8 doesn't have any drupal_bootstrap() function, so the code you are using would throw a PHP error.
You can use authorize.php as guideline to write your own script.
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$autoloader = (require_once 'autoload.php');
try {
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->prepareLegacyRequest($request);
} catch (HttpExceptionInterface $e) {
$response = new Response('', $e->getStatusCode());
$response
->prepare($request)
->send();
exit;
}
\Drupal::moduleHandler()
->addModule('system', 'core/modules/system');
\Drupal::moduleHandler()
->addModule('user', 'core/modules/user');
\Drupal::moduleHandler()
->load('system');
\Drupal::moduleHandler()
->load('user');
$account = \Drupal::service('authentication')
->authenticate($request);
if ($account) {
\Drupal::currentUser()
->setAccount($account);
if (\Drupal::currentUser()->isAuthenticated() {
// The user is logged-in.
}
}
I fixed this by using a complete different approach. I wrote a module which sets a cookie on the moment that the user logs in to drupal (I use the hook_user_login for this). When the user logs out I delete that cookie (I use the hook_user_logout for this). This is the code of my test.module:
/**
* #param $account
*/
function intersoc_content_user_login($account)
{
setcookie("user", "loggedin", time() + (86400 * 30),"/");
}
/**
* #param $account
*/
function intersoc_content_user_logout($account)
{
if (isset($_COOKIE['user']))
{
unset($_COOKIE['user']);
setcookie('user', '', time() - 3600, '/'); //Clearing cookie
}
}
Then in my custom script in the site root I check if the cookie is set. When the cookie exists => The user is logged in. If the cookie doesn't exist then the user isn't logged in. The isLoggedIn() function below:
/**
* #return bool which indicates if the user is logged in or not
*/
private function isLoggedIn()
{
if(isset($_COOKIE["user"]))
{
return TRUE;
}
else
{
return FALSE;
}
}
It isn't the most beautiful solution, but it works!!!

Symfony 1.4 - Login to frontend(as client) from backend

I'm using SfGuardPlugin and on the backend of my site I have the full list of users and I want to be able to login on the frontend with the user that I choose from the list.
I've tried this method:
public function executeListLogin(sfWebRequest $request) {
// client that I've selected from list
$client = $this->getRoute()->getObject();
// create instance if doesn't exist
if(!sfContext::hasInstance('frontend')){
sfContext::createInstance(ProjectConfiguration::getApplicationConfiguration('frontend', 'prod', false));
}
// switch to frontend
sfContext::switchTo('frontend');
// also tried with: sfContext::getInstance('frontend')
sfContext::getInstance()->getUser()->signin($client->getSfGuardUser(), true);
// redirect to frontend homepage
$this->redirect('#homepage');
}
It redirects me to the frontend homepage, but I'm not logged in.
After more digging I've found out that I'm logged out from backend and now I'm logged in on frontend with admin instead of the user I choose. So the sfContext::switchTo doesn't work correctly.
I've found a workaround.
Create a new column(login_frontend_key) on the users table.
Create a new frontend route with a required parameter(named key)
Create the action in frontend controller witch is responsible for sign in the user, ex:
public function executeLoginClientKey(sfWebRequest $request){
// get the client by key
$this->forward404Unless($user = ClientPeer::getByLoginFrontendKey($request->getParameter("key")));
// if you already logged in with another user, signout
if($this->getUser()->isAuthenticated())
{
$this->getUser()->signOut();
}
// signin with the new user
$this->getUser()->signIn($user->getsfGuardUser(), false);
$user->setLoginFrontendKey(null); // delete the key from DB
$user->save();
$this->redirect('#homepage');
}
Use this to generate cross application links http://symfony.com/blog/cross-application-links
Create the object action on the backend users page:
public function executeListLogin(sfWebRequest $request)
{
// get the selected client
$client = $this->getRoute()->getObject();
$key = $client->generateLoginFrontendKey(); // generate a random key
$client->setLoginFrontendKey($key); // store the key in DB
$client->save();
// generate the frontend url for login
$url = $this->getContext()->getConfiguration()->generateFrontendUrl('login_frontend_key', array('key' => $key, 'sf_culture' => 'nb'));
$this->redirect($url);
}

fosuserbundle ldap configuration for strange use case

I'm trying to create a fosuserbundle for a quite strange use case, which is mandatory requirement, so no space to diplomacy.
Use case is as follow:
users in a mongo db table populated by jms messages -no registration form
users log in by ldap
user record not created by ldap, after a successful login username is checked against mongodb document
Considering that ldap could successfully log in people that exhist in ldap but cannot access site (but login is still successful), what could be the best way to perform such authentication chain?
I was thinking about some possible options:
listen on interactive login event, but imho there's no way to modify an onSuccess event
create a custom AuthenticationListener to do another check inside onSuccess method
chain authentication using scheb two-factor bundle
any hint?
I've used Fr3DLdapBundle which can be incorporate with FOSUserBundle quite easily (I'm using the 2.0.x version, I have no idea if the previous ones will do the same or be as easy to set up).
In the LdapManager (by default) it creates a new user if one is not already on the database which is not what I wanted (and doesn't seem to be what you want) so I have added my own manager that checks for the presence of the user in the database and then deals with the accordingly.
use FR3D\LdapBundle\Ldap\LdapManager as BaseLdapManager;
.. Other use stuff ..
class LdapManager extends BaseLdapManager
{
protected $userRepository;
protected $usernameCanonicalizer;
public function __construct(
LdapDriverInterface $driver,
$userManager,
array $params,
ObjectRepository $userRepository,
CanonicalizerInterface $usernameCanonicalizer
) {
parent::__construct($driver, $userManager, $params);
$this->userRepository = $userRepository;
$this->usernameCanonicalizer = $usernameCanonicalizer;
}
/**
* {#inheritDoc}
*/
public function findUserBy(array $criteria)
{
$filter = $this->buildFilter($criteria);
$entries = $this->driver->search(
$this->params['baseDn'], $filter, $this->ldapAttributes
);
if ($entries['count'] > 1) {
throw new \Exception('This search can only return a single user');
}
if ($entries['count'] == 0) {
return false;
}
$uid = $entries[0]['uid'][0];
$usernameCanonical = $this->usernameCanonicalizer->canonicalize($uid);
$user = $this->userRepository->findOneBy(
array('usernameCanonical' => $usernameCanonical)
);
if (null === $user) {
throw new \Exception('Your account has yet to be set up. See Admin.');
}
return $user;
}

Correct way to retrieve mails by IMAP in symfony2

I have to develop simple mail client in symfony2 using IMAP. Im wondering what is best way to retrieve messages from server (lets take a gmail as example)?
I did something like this:
public function indexAction($name)
{
$user = 'adress#gmail.com';
$password = 'password';
$mailbox = "{imap.gmail.com:993/imap/ssl}INBOX";
$mbx = imap_open($mailbox , $user , $password);
$ck = imap_check($mbx);
$mails = imap_fetch_overview($mbx,"1:5");
return $this->render('HtstMailBundle:Mail:index.html.twig',array('name'=>$name,'mail'=>$mails));
}
is this right way, or not? It works, but is it compatible with symfony "standards"?
This has nothing to do with symfony "standards". But you can make your code more OOP if you move all login to a service class and use symfony DepencyInjection to create and get your service:
public function indexAction($name)
{
$user = 'adress#gmail.com';
$password = 'password';
$mailbox = "{imap.gmail.com:993/imap/ssl}INBOX";
$mails = $this->get("mail.checker")->receive($user, $password, $mailbox);
return $this->render('HtstMailBundle:Mail:index.html.twig',array('name'=>$name,'mail'=>$mails));
}
Class declaration:
class MailChecker
{
public function receive($user, $password, $mailbox)
{
...imap_check()...
}
}
service declartion:
services:
mail.checker:
class: Project\YourBundle\Service\MailChecker
You can also use this Symfony bundle for that and use it as a service. I is designed for old Symfony2 but tested it with Symfony 3 and works :)

Resources