• Home
  • Get Noticed 2017
  • PHP
  • Quick Tips
  • Contact
  • About me

Bartosz Sosna Blog

Bartosz Sosna Blog

PHP BLOG

Slim Framework authorization with email confirmation
Get Noticed 2017, PHP, Slim Framework

Slim Framework authorization with email confirmation

Slim Framework authorization with email confirmation

Slim framework is top if you don’t need to many stuff on start. All that you need, must you write or implement yourself. In my project “Image optimizer API” I need authorization and authentication functions. I found a great tutorial how to build that:
https://www.youtube.com/watch?v=RhcQXFeor9g

Repository from this tutorial can you find here:
https://github.com/brtsos/slim-born forked from HavenShen/slim-born

That work great but I need email confirmation too, so today I show you how to do it yourself.

Email library

We need a library to send the emails with a confirmation code. I use “Nette Mail”:
https://github.com/nette/mail

Time to install. Add this line to yours composer.json:

"nette/mail": "^2.4"

And run in console:

composer update

Library is now in vendor folder and we can use it. It is effortless to use.

At the beginning, you must add baseUrl and email server access data to bootstrap/app.php.
Your settings array should be like:

$app = new \Slim\App([
    'settings' => [
        'displayErrorDetails' => true,
        'mailer' => [
        'host' => getenv('MAIL_HOST'),
        'username' => getenv('MAIL_USERNAME'),
        'password' => getenv('MAIL_PASSWORD')
    ],
    'baseUrl' => getenv('BASE_URL')
...

In this same file must we add email library to a container:

$container['mailer'] = function($container) {
    return new Nette\Mail\SmtpMailer($container['settings']['mailer']);
};

All setting can you adjust in “.env” file. If you have not “.env” file yet then copy “.env.dist” to “.env”.

Database prepare

Now must you prepare database. We adding 2 parameters:
activ – default 0. When 1 then user confirmed email address.
activ_code – here storage we a activation code.

Run this Sql query in PhpMyAdmin or in yours MySql client:

ALTER TABLE `users` ADD `activ` INT(1) NOT NULL DEFAULT '0' AFTER `email`, 
ADD `activ_code` VARCHAR(32) NOT NULL AFTER `activ`;

We still have to make “activ_code” writible in app/Model/Users.php:

protected $fillable = [
	'email',
	'name',
	'password',
	'activ_code' // <-- add this line
];

Check if user account is active

That is easy too. We must add only one condition in app/Auth/Auth.php (function attempt).

if (!$user) {
    return false;
}
 
if ($user->activ == 0){ // <-- That need we
    return false;
}
 
if (password_verify($password,$user->password)) {
    $_SESSION['user'] = $user->id;
...

Send the email

We are ready to generate a activation code and send it by email.

“Sing Up” controller you can find in app/Controllers/Auth/AuthController.php

On top must you add Email library:

use Nette\Mail\Message;

And now can we adjust postSignUp function:

if ($validation->failed()) {
	return $response->withRedirect($this->router->pathFor('auth.signup'));
}
 
$activCode = md5('yourSalt' . date('Ymdhis'));
 
$user = User::create([
	'email' => $request->getParam('email'),
	'name' => $request->getParam('name'),
	'password' => password_hash($request->getParam('password'),PASSWORD_DEFAULT),
	'activ_code' => $activCode // <-- add the activation code to database
]);
 
$mail = new Message;
$mail->setFrom('your@email.com')
	->addTo($request->getParam('email'))
	->setSubject('Plaease confirm your email')
	->setHTMLBody("Hello, to confirm this Email click this URL: <br />
	<a target='_blank' href='" . $this->container->settings['baseUrl'] . "auth/confirm?code=" . $activCode ."'>
	" . $this->container->settings['baseUrl'] . "/auth/confirm?code=" . $activCode . "</a>");
 
$this->mailer->send($mail);
 
$this->flash->addMessage('info','Please confirm your email. We send a Email with activate Code.');
 
//$this->auth->attempt($user->email,$request->getParam('password')); // ← we don't need auto login anymore
 
return $response->withRedirect($this->router->pathFor('home'));

Confirm email

First adding we new route (app/routes.php):

$this->get('/auth/confirm','AuthController:confirmEmail');

And now can we add “confirm email” function in app/Controllers/Auth/AuthController.php

public function confirmEmail($request,$response)
{
 
    if (!$request->getParam('code')) {
        return $response->withRedirect($this->router->pathFor('home'));
    }
 
    $user = User::where('activ_code', $request->getParam('code'))->first();
    $user->activ = 1;
    $user->save();
 
    $this->flash->addMessage('info','Congratulation! Your email is confimed. You can sing on now.');
 
    return $this->view->render($response,'auth/signin.twig');
}

Repository with email confirmation can you find here:
https://github.com/brtsos/slim-auth

That’s it. You can enjoy yours new authorization functionality.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Google+ (Opens in new window)

Related

Written by Bartosz Sosna in April 2, 2017 / 9527 Views
Tags | get notice 2017, php, slim framework
AUTHOR
Bartosz Sosna

I'm Web and App developer. I love gadgets and new technologies. I'm also productivity freak.

You Might Also Like

Capistrano

Capistrano – PHP, deploy without stressful

March 16, 2017

Phinx – PHP database migration

April 30, 2017

Whoops – pretty PHP errors and exceptions

March 5, 2017

1 Comment

  • michael May 29, 2018 at 6:51 am

    nice tutorials but i will like to know how to make use of phpmailer with slim where user registers with only name and email and the system generates a password token for that user and is inserted into the database. A confirmation email is sent to the user when clicked, changes activated form 0 to 1. then a condition is done to check if activated. if true pick the clearText password from database and send to that user via email. plan on using twig for templating. Any ideas how to achieve this.. Total beginner and thanks in advance

    Reply
  • Please Post Your Comments & Reviews
    Cancel reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Previous Post
    Next Post

    Serach

    Newsletter

    Latest Posts

    • API, Get Noticed 2017, PHP“Image Optimizer API” is ready“Get Notice 2017” contest is over My project “Image Optimizer…May 21, 2017
    • Get Noticed 2017, Quick Tips, zshZ shell (zsh) – better bashWhy zsh is better? I use console from years and…May 18, 2017
    • API, Get Noticed 2017, Quick TipsPostman – powerful tool to work with APIPostman – powerful tool to work with API I’m creating…May 7, 2017
    • Capistrano, Get Noticed 2017, PHP, Quick TipsHow to add tasks to capistranoHow to add tasks to Capistrano I wrote in post…May 5, 2017
    • Get Noticed 2017, MySQL, PHP, Quick TipsPhinx – PHP database migrationWhat is “database migration” I meet migrations first time in…April 30, 2017

    STAY UPDATED

    About Me

    About Me

    Web and App developer.

    I'm Web and App developer. I love gadgets and new technologies. I'm also productivity freak.

    About me (de)

    Latest Posts

    • API, Get Noticed 2017, PHP“Image Optimizer API” is ready“Get Notice 2017” contest is over My project “Image Optimizer…May 21, 2017
    • Get Noticed 2017, Quick Tips, zshZ shell (zsh) – better bashWhy zsh is better? I use console from years and…May 18, 2017
    • API, Get Noticed 2017, Quick TipsPostman – powerful tool to work with APIPostman – powerful tool to work with API I’m creating…May 7, 2017
    • Capistrano, Get Noticed 2017, PHP, Quick TipsHow to add tasks to capistranoHow to add tasks to Capistrano I wrote in post…May 5, 2017
    • Get Noticed 2017, MySQL, PHP, Quick TipsPhinx – PHP database migrationWhat is “database migration” I meet migrations first time in…April 30, 2017
    Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
    To find out more, including how to control cookies, see here: Cookie Policy

    FOLLOW ME ON TWITTER

    • RT @DamianNaprawa: Festiwal Docker & Kubernetes - DZIEŃ 3 BARTOSZ SOSNA @brtsos Palec wskazujący skierowany w prawo Konfiguracja środowi…33 days ago
    • W końcu MacBook Pro bez bezużytczego touch bara? https://t.co/5tweGBUxP245 days ago
    Bartosz Sosna Blog

    Copyright © Bartosz Sosna