使用 Masonite 框架和 JSON Web Tokens 从零开始构建电子邮件验证
Masonite Framework是一个现代化的、以开发者为中心的 Python Web 框架。Masonite 的架构与 Laravel 框架非常相似。
在本教程中,我将向您展示如何从零开始为您的 Masonite 应用程序构建电子邮件验证功能。
Masonite 附带一个名为 Craft 的 CLI 工具。Craft 提供了一种简便的方法,可以使用简单的命令搭建身份验证所需的框架:
$ craft auth
上述命令会生成身份验证所需的一切:4 个新控制器、5 个新模板和 6 个新路由。所以,你想处理用户电子邮件验证并验证电子邮件。搞定!
创建新的 Masonite 项目和脚手架认证
$ pipenv install masonite-cli
$ craft new masonite-app-with-user-verification
$ cd masonite-app-with-user-verification
$ craft install
$ craft auth
设置数据库
为了注册用户,我们需要一个数据库。我们这里使用MySQL数据库。
$ pipenv install PyMySQL
创建新数据库并将数据库凭据放入 .env 文件中:
DB_DRIVER=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=masonite
DB_USERNAME=root
DB_PASSWORD=root
向用户模型添加“active”属性
让我们创建一个新的迁移:
$ craft migration add_active_to_users_table --table=users
然后,添加新的活动属性:
from orator.migrations import Migration
class AddActiveToUsersTable(Migration):
def up(self):
with self.schema.table('users') as table:
table.boolean('active').default(False)
def down(self):
with self.schema.table('users') as table:
table.drop_column('active')
应用你的迁移 😄
$ craft migrate
为什么使用 JWT 进行电子邮件验证?
JSON Web Tokens是一种在各方之间安全传输信息的好方法。
为了进行邮箱验证,我们需要向注册用户发送一个随机哈希值。
注册时生成新的 JWT 令牌
我们需要在Python中使用JSON Web Token实现:
$ pipenv install PyJWT
然后
data = {'email': user.email}
encoded = jwt.encode(data, os.environ.get('KEY'), algorithm='HS256')
token = str(encoded, 'utf-8')
现在,我们需要寄送一封邮件。Masonite 提供包裹呼叫通知功能,可以帮助我们完成这项操作。
$ pipenv install masonite-notifications
让我们创建一个电子邮件验证通知。
$ craft notification EmailVerificationNotification
我们的通知将通过电子邮件发送一封包含验证令牌链接的电子邮件。
from notifications import Notifiable
class EmailVerificationNotification(Notifiable):
def mail(self):
return self.subject('New account signup!') \
.driver('smtp') \
.heading('Masonite App With User Verification') \
.line('In order to use your account, you have to validate your email address.') \
.line('Please click on the link below.') \
.action('Validate my account', href=self._link)
不错。
然后,让我们把这封邮件发送给用户:
if token:
Notify.mail(EmailVerificationNotification, to=user.email, link='http://localhost:8000/activate/{0}'.format(token))
Session.flash(‘success’, ‘Almost done! Please check your email to complete the registration process.’)
return Request.redirect(‘/login’)
如果您的 SMTP 凭据正确,您将在邮件中看到以下内容:
创建电子邮件验证路由
get('/activate/@token', 'RegisterController@validate')
在用户模型上定义可填充属性“activate”
class User(Model):
__fillable__ = ['name', 'email', 'password', 'active']
验证用户
def validate(self, Request):
if Request.param('token'):
data = jwt.decode(Request.param('token'), os.environ.get('KEY'), algorithms=[‘HS256’])
user = User.where('email', data['email']).first()
if user:
user.active = True
user.save()
Session.flash('success', 'You\'re in! Let\'s login!')
return Request.redirect('/login')
最后一件事!登录用户:
def store(self, Request, Session):
user = User.where('email', Request.input('email')).first()
if user.active:
if Auth(Request).login(Request.input('email'), Request.input('password')):
return Request.redirect('/home')
return Request.redirect('/login')
else:
Session.flash('warning', 'Please check your email to complete the registration process.')
return Request.back()
您的用户已通过验证 🔥
我会把这些内容打包成 Masonite 软件包发布。如果你想参与软件包的开发,或者对 Masonite 的开发感兴趣,请务必加入Slack 频道或在GitHub上给仓库点赞。
欢迎留言讨论。本教程的全部代码已上传至GitHub。谢谢!
文章来源:https://dev.to/nioperas06/build-email-verification-from-scratch-with-masonite-framework-and-json-web-tokens-mf7
