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.
1 Comment
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