iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0
Modern Web

Python x Django 網站實作&學習記錄系列 第 8

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/


上一篇
D7 allauth 採坑日記 Extending & Substituting User model (2)
下一篇
D9 文件系統核心開始 系統頁面功能規劃
系列文
Python x Django 網站實作&學習記錄30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言