如何在使用用户限制资源访问保护的 python eve api 中创建新用户帐户

2024-04-21

我首先使用 python-eve 框架创建了一个 Web api,无需身份验证或用户帐户,效果非常好!我现在正在尝试添加身份验证和用户帐户,但遇到了一些困难。我想使用用户限制的资源访问,但是如果资源受到限制,用户如何创建新的用户帐户?我缺少什么?

我一直在努力遵循安心账户管理教程 http://python-eve.org/tutorials/account_management.html以及介绍认证与授权 http://python-eve.org/authentication.html#user-restricted-resource-access在 python-eve.org 上,我搜索了 stackoverflow,包括这个在这里回答 https://stackoverflow.com/questions/27029842/in-eve-how-can-you-store-the-users-password-securely.

这是我的实现:

run.py

import os.path
from eve import Eve
import my_auth
from flask.ext.bootstrap import Bootstrap
from eve_docs import eve_docs

app = Eve(auth=my_auth.BCryptAuth, settings = 'deployed_settings.py')

app.on_insert_accounts += my_auth.create_user
Bootstrap(app)
app.register_blueprint(eve_docs, url_prefix='/docs')

if __name__ == '__main__':
    app.run()

my_auth.py

import bcrypt
from eve import Eve
from eve.auth import BasicAuth 

class BCryptAuth(BasicAuth):
    def check_auth(self, username, password, allowed_roles, resource, method):
         # use Eve's own db driver; no additional connections/resources are used
         accounts = Eve.app.data.driver.db['accounts']
         account = accounts.find_one({'username': username})
         if account and 'user_id' in account:
             self.set_request_auth_value(account['user_id'])
         return account and bcrypt.hashpw(
             password.encode('utf-8'),account['salt'].encode('utf-8')) == account['password']

def create_user(documents):
    for document in documents:
        document['salt'] = bcrypt.gensalt().encode('utf-8')
        password = document['password'].encode('utf-8')
        document['password'] = bcrypt.hashpw(password, document['salt'])

部署设置.py

# We are running on a local machine, so just use the local mongod instance.
# Note that MONGO_HOST and MONGO_PORT could very well be left
# out as they already default to a bare bones local 'mongod' instance.
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
MONGO_USERNAME = ''
MONGO_PASSWORD = ''
MONGO_DBNAME = 'practice'

# Name of the field used to store the owner of each document
AUTH_FIELD = 'user_id'

# Enable reads (GET), inserts (POST) and DELETE for resources/collections
# (if you omit this line, the API will default to ['GET'] and provide
# read-only access to the endpoint).
RESOURCE_METHODS = ['GET', 'POST', 'DELETE']

# Enable reads (GET), edits (PATCH), replacements (PUT) and deletes of
# individual items  (defaults to read-only item access).
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
IF_MATCH = False  # When set to false, older versions may potentially replace newer versions

XML = False  # disable xml output

# Schemas for data objects are defined here:

classes = {
# ... Contents omitted for this question
}

people = {
# ... Contents omitted for this question
}

logs = {
# ... Contents omitted for this question
}

sessions = {
# ... Contents omitted for this question
}


accounts = {
    # the standard account entry point is defined as '/accounts/<ObjectId>'.
    # an additional read-only entry point is accessible at '/accounts/<username>'.
    'additional_lookup': {
        'url': 'regex("[\w]+")',
        'field': 'username',
    },

    # disable endpoint caching to prevent apps from caching account data
    'cache_control': '',
    'cache_expires': 0,

    # schema for the accounts endpoint
    'schema': {
        'username': {
            'type': 'string',
            'required': True,
            'unique': True,
        },
        'password': {
            'type': 'string',
            'required': True,
        },
    },
}

# The DOMAIN dict explains which resources will be available and how they will
# be accessible to the API consumer.
DOMAIN = {
    'classes': classes,
    'people': people,
    'logs': logs,
    'sessions': sessions,
    'accounts': accounts,
}

一种简单的解决方案是not限制您的用户创建方法。像这样:

class BCryptAuth(BasicAuth):
    def check_auth(self, username, password, allowed_roles, resource, method):

        # allow anyone to create a new account.
        if resource == 'accounts' and method == 'POST':
            return True

        accounts = Eve.app.data.driver.db['accounts']
        account = accounts.find_one({'username': username})
        if account and 'user_id' in account:
           self.set_request_auth_value(account['user_id'])
        return account and bcrypt.hashpw(password.encode('utf-8'),account['salt'].encode('utf-8')) == account['password']

或者,尤其是如果您只允许 POSTing 到account端点,您可以选择退出端点身份验证:

'accounts': {
    # or you could provide a different custom class here, 
    # so you don't need the guard in the general-purpose auth class.
    'authentication': None,
    ...
}

希望这可以帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在使用用户限制资源访问保护的 python eve api 中创建新用户帐户 的相关文章

  • Python串口通信

    我正在开发一个 Arduino 项目 由于内存限制 我将其与 Python 脚本连接起来 在Python方面 我有一个二维矩阵 其中包含各自的x y坐标值 并且在此列表中有26000个坐标对 因此 为了向大家澄清数据结构 pathlist
  • 在云服务器中运行 python 脚本的最简单方法是什么?

    我有一个网络爬行 python 脚本 需要几个小时才能完成 并且无法在我的本地计算机上完整运行 有没有一种方便的方法可以将其部署到简单的 Web 服务器 该脚本基本上将网页下载到文本文件中 如何最好地实现这一点 谢谢 既然你说性能是一个问题
  • 在 Heroku 应用程序中同时运行 Django 和 Node

    我想在我的 heroku 实例上同时运行 django 应用程序和节点应用程序 这是我的进程文件 web python manage py runserver 0 0 0 0 PORT web node bin node modules a
  • 尝试通过 API 将成员添加到 Google 群组时出现“缺少必填字段:成员”

    尝试使用 Google 管理目录 API 来读取 google 群组 组织 的成员 它工作正常 当我尝试添加成员时 我得到 errors domain global reason required message Missing requi
  • 如何解决 Python 'Pyzbar' 库的导入错误?

    我刚刚开始熟悉 Pyzbar 库 但是当使用decode方法我得到一个错误 这是代码 import cv2 import numpy as np import pyzbar code image cv2 imread C Users Ace
  • python 线程是如何工作的?

    我想知道 python 线程是并发运行还是并行运行 例如 如果我有两个任务并在两个线程中运行它们 它们是同时运行还是计划同时运行 我知道GIL并且线程仅使用一个 CPU 核心 这是一个复杂的问题 需要大量解释 我将坚持使用 CPython
  • 将numpy字符串数组转换为int数组[重复]

    这个问题在这里已经有答案了 我有一个 numpy ndarray a 0 99 0 56 0 56 2 02 0 96 如何将其转换为int 输出 a 0 99 0 0 0 56 0 56 2 02 0 96 我想要 0 0 代替空白 im
  • 这是在 python 中美白图像的正确方法吗?

    我在尝试着zero center and whiten CIFAR10数据集 但我得到的结果看起来像随机噪声 Cifar10数据集包含60 000尺寸的彩色图像32x32 训练集包含50 000和测试集包含10 000分别是图像 以下代码片
  • Python 有哪些重要的语言特性(习语)需要尽早学习[重复]

    这个问题在这里已经有答案了 我有兴趣了解 StackOverflow 社区认为 Python 的重要语言特性 习语 是什么 将程序员定义为 Pythonic 的特征 Python pythonic 习语 Python 语言自然的或特有的 代
  • 使用 openCV 和 python 检测物体

    我正在尝试使用 OpenCV 和 Python 检测下图中的白点 我尝试使用函数 cv2 HoughCircles 但没有成功 我需要使用不同的方法吗 这是我的代码 import cv2 cv import numpy as np impo
  • Pymacs 助手在 30 秒后未启动

    我见过其他关于此的问题 但没有一个得到真正的回答 而且没有一个是我的问题 我有一个新系统 emacs 23 1 Centos 6 2 我认为 我下载了最新的 pymacs 并安装了它 但是 我得到 error Pymacs helper d
  • 将 Pandas 列转换为日期时间

    我在 pandas DataFrame 中有一个字段以字符串格式导入 它应该是一个日期时间变量 如何将其转换为日期时间列 然后根据日期进行过滤 Example raw data pd DataFrame Mycol 05SEP2014 00
  • 计算两个表中等效行的交集

    我有两个 FITS 文件 让我们考虑一下例如第一个文件有 100 行和 2 列 第二个文件有 1000 行和 2 列 FITS FILE 1 FITS FILE 2 A B C D 1 2 1 2 1 3 1 2 2 4 1 2 我需要采取
  • 如何找到运行代码的 conda 环境的名称?

    我正在寻找一种好方法来从正在运行的代码或交互式 python 实例中找出我所在的 conda 环境的名称 用例是我通过 miniconda 安装运行带有 Python 2 和 Python 3 内核的 Jupyter 笔记本 默认环境是Py
  • pyspark:将 schemaRDD 保存为 json 文件

    我正在寻找一种将数据从 Apache Spark 以 JSON 格式导出到各种其他工具的方法 我认为一定有一种非常简单的方法来做到这一点 示例 我有以下 JSON 文件 jfile json key value a1 key2 value
  • 带日志图的 Type 1 字体

    我正在尝试使用 Matplotlib 图表作为相机就绪的一部分 提交 出版社要求使用Type 1字体 仅有的 我发现 PDF 后端很乐意输出 Type 1 字体 具有线性 Y 轴的简单图形 但输出 Type 3 字体 对数 Y 轴 使用对数
  • python:Windows终端中的unicode,使用的编码?

    我在 Windows 7 终端中使用 Python 解释器 我正在尝试了解 unicode 和编码 I type gt gt gt s gt gt gt s x89 gt gt gt u u gt gt gt u u xeb 问题1 字符串
  • Python:使用 FOR 循环插入字典

    我已经在论坛中进行了搜索 但不明白是否可以使用以下构造将新条目插入到我的 Python 字典中 而不将其转换为列表 for x in range 3 pupils dictionary new key input Enter new key
  • 将 2D 数组中的每一列与另一个 2D 数组中的每一列相乘

    我有两个 Numpy 数组x有形状 m i and y有形状 m j 所以行数是相同的 我想将每一列相乘x每一列y逐元素 使结果具有形状 m i j Example import numpy as np np random seed 1 x
  • 将下载的字体添加到 Tkinter

    我想下载一个开源字体并在我的 Python Tkinter 程序中使用它 如何告诉 Tkinter 从目录导入字体或将字体放在与程序相同的文件夹中 Note 我已经寻找答案一段时间了 甚至阅读了 Tkinter 的 API 参考 了解我能找

随机推荐