D8 新增使用google account 登入的功能

前面做的那些都是让使用者直接在local端注册跟登入
今天处理一下怎麽做google登入

docsystem_5/settings.py
新增google providers 相关设定
更多provider可以参考https://django-allauth.readthedocs.io/en/latest/providers.html

INSTALLED_APPS = [
    'allauth.socialaccount.providers.google',
]
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            'profile',
            'email',
        ],
        'AUTH_PARAMS': {
            'access_type': 'online',
        }
    }
}

浏览器到http://127.0.0.1:8000/accounts/login/
会看到已经出现使用google登入的选项
但现在点下去只有错误
Imgur

先选Oauth同意画面 选择外部
Imgur
Imgur
Imgur
Imgur

设定完成到凭证选择新增Oauth ID
Imgur
新增完成後会得到Oauth ID, secret key
Imgur

浏览器到http://127.0.0.1:8000/admin
进到sites把domain name 改成http://127.0.0.1:8000
进到Social applications 新增social app 把 Oauth ID, secret key打进去 储存
然後回到http://127.0.0.1:8000/accounts/login/
按下google就可以登入google帐号了

social account在创建的时候不会经过我们自制的sign up form 所以不会在auth_info.userprofile table 新增一个onetoone连接的id
到auth_info/views.py
将profile改成如下
因为我们预设登入之後会跳转到profile所以藉由views来建立auth_info.userprofile

@login_required
def profile(request):
    user = request.user
    print(f"user id : {user.id}")
    print(f"user email : {user.email}")
    # Create userprofile for social account
    try:
        user_profile_2 = UserProfile(user_id=user.id)
        user_profile_2.save()
        print("Create userprofile for social account sign in")
    except Exception as e:
        print(e)
    return render(request, 'account/profile.html', {'user': user})

完成!
另外介绍一下我用来看SQLite DB的工具是https://sqlitebrowser.org/


<<:  Day 14 ( 中级 ) 键盘钢琴 ( 音符动画 )

>>:  【Day14】 Pytorch 转 Tensorflow

NetSuite Order to Cash flow - Create Sales Order

Order to Cash 所有 ERP 最基础的功能, 主要用来表现从 订单 -> 收到款项...

图的走访 - DFS 篇

5 图的走访 - DFS 篇 今天要跟大家分享另一种在图上面遍历所有节点的深度优先搜索 (Depth...

Day 5 - Using Argon2 for Password Verifying with ASP.NET Web Forms C# 使用 Argon2 验证密码

=x= 🌵 Sign In page 後台登入密码验证。 验证流程介绍 : 📌 使用者於登入页面输入...

TailwindCSS 从零开始 - 新增自己的 Utility

除了可以新增元件外,也可以增加自订义的功能。 虽然 TailwindCSS 已经提供非常多好用的 ...