发布于 2026-01-06 5 阅读
0

使用 Masonite 框架和 JSON Web Tokens 从零开始构建电子邮件验证

使用 Masonite 框架和 JSON Web Tokens 从零开始构建电子邮件验证

Masonite Framework是一个现代化的、以开发者为中心的 Python Web 框架。Masonite 的架构与 Laravel 框架非常相似。

在本教程中,我将向您展示如何从零开始为您的 Masonite 应用程序构建电子邮件验证功能。

Masonite 附带一个名为 Craft 的 CLI 工具。Craft 提供了一种简便的方法,可以使用简单的命令搭建身份验证所需的框架:

$ craft auth
Enter fullscreen mode Exit fullscreen mode

上述命令会生成身份验证所需的一切: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 
Enter fullscreen mode Exit fullscreen mode

设置数据库

为了注册用户,我们需要一个数据库。我们这里使用MySQL数据库。

$ pipenv install PyMySQL
Enter fullscreen mode Exit fullscreen mode

创建新数据库并将数据库凭据放入 .env 文件中:

DB_DRIVER=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=masonite
DB_USERNAME=root
DB_PASSWORD=root
Enter fullscreen mode Exit fullscreen mode

向用户模型添加“active”属性

让我们创建一个新的迁移:

$ craft migration add_active_to_users_table --table=users
Enter fullscreen mode Exit fullscreen mode

然后,添加新的活动属性:

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')
Enter fullscreen mode Exit fullscreen mode

应用你的迁移 😄

$ craft migrate
Enter fullscreen mode Exit fullscreen mode

为什么使用 JWT 进行电子邮件验证?

JSON Web Tokens是一种在各方之间安全传输信息的好方法。

为了进行邮箱验证,我们需要向注册用户发送一个随机哈希值。

注册时生成新的 JWT 令牌

我们需要在Python中使用JSON Web Token实现:

$ pipenv install PyJWT
Enter fullscreen mode Exit fullscreen mode

然后

data = {'email': user.email}
encoded = jwt.encode(data, os.environ.get('KEY'), algorithm='HS256')
token = str(encoded, 'utf-8')
Enter fullscreen mode Exit fullscreen mode

现在,我们需要寄送一封邮件。Masonite 提供包裹呼叫通知功能,可以帮助我们完成这项操作。

$ pipenv install masonite-notifications
Enter fullscreen mode Exit fullscreen mode

让我们创建一个电子邮件验证通知。

$ craft notification EmailVerificationNotification
Enter fullscreen mode Exit fullscreen mode

我们的通知将通过电子邮件发送一封包含验证令牌链接的电子邮件。

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)
Enter fullscreen mode Exit fullscreen mode

不错。

然后,让我们把这封邮件发送给用户:

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’)
Enter fullscreen mode Exit fullscreen mode

如果您的 SMTP 凭据正确,您将在邮件中看到以下内容:

电子邮件验证

创建电子邮件验证路由

get('/activate/@token', 'RegisterController@validate')
Enter fullscreen mode Exit fullscreen mode

在用户模型上定义可填充属性“activate”

class User(Model):
    __fillable__ = ['name', 'email', 'password', 'active']
Enter fullscreen mode Exit fullscreen mode

验证用户

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')
Enter fullscreen mode Exit fullscreen mode

最后一件事!登录用户:

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()
Enter fullscreen mode Exit fullscreen mode

您的用户已通过验证 🔥

我会把这些内容打包成 Masonite 软件包发布。如果你想参与软件包的开发,或者对 Masonite 的开发感兴趣,请务必加入Slack 频道或在GitHub上给仓库点赞

欢迎留言讨论。本教程的全部代码已上传至GitHub。谢谢!

文章来源:https://dev.to/nioperas06/build-email-verification-from-scratch-with-masonite-framework-and-json-web-tokens-mf7