首页 文章

如何在我的应用程序中实现内置的django auth和第三方social-auth?

提问于
浏览
1

我使用过去4-5个月的django并且最近开始学习django-rest-framework并且我对正确的身份验证系统感到困惑,实际上我正在尝试构建一个主要使用REST API的应用程序,因为我的客户端可以是浏览器和Android,所以我需要一个身份验证系统,用户可以使用django内置身份验证(django.contrib.auth.model.User)以及第三方社交身份验证(Google,Facebook等)进行注册 .

现在,我对如何创建我的数据库感到困惑,因为当我创建一个表/模型让我们说'Book'时,那么这个模型需要一个用户模型的外键,这里用户可以同时使用'django.contrib.auth.model.User'和使用第三方身份验证的用户注册,

那么我将如何在我的模型的外键字段中引用User?

而且我还决定自定义django的buit-in auth,因为我希望用户使用他们的电子邮件登录而不是用户名 .

class Book(models.Model):
  title = models.CharField(...)
  author = models.ForeignKey(?) ? Here, how do i refer to both
                                 'django.contrib...User' and users signed-up                     
                                 using thrid-party auth.

1 回答

  • 0

    让我详细说明你的问题 . 首先:你很幸运 . 对于你的问题,有一个(几乎)开箱即用的版本 .

    对于社交和普通身份验证和注册,包括电子邮件验证等,您可以依赖django-allauth:

    https://github.com/pennersr/django-allauth

    django-restauth提供了一个 Build 在all-auth之上的平台,因此您甚至不必从头开始构建auth rest api:

    https://github.com/Tivix/django-rest-auth

    说到db模式,有几个选项 . 您可以继续构建自己的身份验证系统,在我看来,这种系统有点过分 . 更确切地说,我将实现一个配置文件模型,该模型与django.contrib.auth.models.User中的User模型具有OneToOne关系,如Django文档的this chapter中所述 .

    您的模型(当然是在分开的应用程序中)看起来像这样:

    from django.contrib.auth.models import User
    from django.db import models
    #other imports
    
    class UserProfile(models.Model):
        user = models.OneToOneField(User, related_name='profile')
        books_read = models.IntegerField(default=0)
        books_recommended = models.IntegerField(default=0)
    
    class Book(models.Model):
        title = models.CharField(...)
        author = models.ForeignKey('UserProfile', related_name='books')
    

    您将遇到的另一个问题是如何在序列化程序中更新和/或显示这些嵌套关系 .

    来自django-restauth docs的This FAQ article和官方django-rest_framework docs的this chapter将让你快速启动 .

    最好的,D

相关问题