使用 Django 实现 LINE 登录功能
做过的事情 (Zuò guò de
我在使用Django构建的Web应用中实现了LINE登录功能,并将其记录下来。
根据这篇文章的指示,(paraphrase may vary depending on the content of the article, so I cannot provide a specific paraphrase without more context)。
-
- LINEアカウントでのログイン
-
- LINEアカウント表示名の取得
- LINEプロフィール画像の取得
我让其能够做到。
前提背景
电脑型号:MacBook Air M2
操作系统:macOS Ventura Ver. 13.2.1
Homebrew 版本:4.0.9
Docker 版本:20.10.23
docker-compose 版本:v2.15.1
运用技术
基础设施:Docker
后端:Python(Django REST框架)
前端:TypeScript(React)
设定的内容
设置.py
频道ID和频道密钥是从.env文件中获取的。
SOCIAL_AUTH_LINE_KEY = os.environ.get('SOCIAL_AUTH_LINE_KEY')
SOCIAL_AUTH_LINE_SECRET = os.environ.get('SOCIAL_AUTH_LINE_SECRET')
登入/登出后,将显示稍后要介绍的模板。
LOGIN_REDIRECT_URL = "/account_management/complete/line"
LOGOUT_REDIRECT_URL = "/account_management/complete/line"
我们正在使用Pipeline将用户显示名称和个人资料图片URL与Django用户模型关联起来。
SOCIAL_AUTH_PIPELINE = (
"social_core.pipeline.social_auth.social_details",
"social_core.pipeline.social_auth.social_uid",
"social_core.pipeline.social_auth.social_user",
"social_core.pipeline.user.get_username",
"social_core.pipeline.social_auth.associate_by_email",
"social_core.pipeline.user.create_user",
"social_core.pipeline.social_auth.associate_user",
"social_core.pipeline.social_auth.load_extra_data",
"social_core.pipeline.user.user_details",
"auth_management.pipeline.set_user_data",
)
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
class CustomUserManager(BaseUserManager):
"""
Custom manager for CustomUser
"""
def create_user(self, email, password=None, **extra_fields):
"""
Create and return a regular user with an email and password.
"""
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password=None, **extra_fields):
"""
Create and return a superuser with an email and password.
"""
user = self.create_user(email, password, **extra_fields)
user.is_staff = True
user.is_superuser = True
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
user.save(using=self._db)
return user
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True, blank=True, null=True)
username = models.CharField(max_length=200, unique=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
sns_icon_url = models.URLField(blank=True, null=True)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def icon_url(self):
"""
ユーザーのSNSアイコン画像URLを返す。
1. SNS認証時にプロフィール画像を取得できた場合: sns_icon_url
2. SNS認証時にプロフィール画像を取得できない場合: デフォルト画像
"""
if self.sns_icon_url:
return self.sns_icon_url
else:
return staticfiles_storage.url('config/初期プロフィール画像.png')
def set_user_data(backend, strategy, details, response, user=None, *args, **kwargs):
"""
SNS認証時にプロバイダから取得したデータをプロフィールに設定する。
"""
if backend.name == "line":
# ユーザー名を取得。取得できなかった場合はuserIdをユーザー名とする。
username = response.get('displayName', response['userId'])
# アイコン未設定の場合は空文字を設定する。
icon_url = response.get('pictureUrl', '')
user.username = username
user.sns_icon_url = icon_url
user.save()
安装图书馆
我将social-auth-app-django添加到了requirements.txt文件中,并在构建docker-compose时进行了安装。
Django==4.2
djangorestframework==3.14.0
django-currentuser
social-auth-app-django
mysqlclient==2.2.0
登录网址

from django.urls import path, include
from django.contrib import admin
from django.contrib.auth import views as auth_views
from social_django.views import auth
from . import views
urlpatterns = [
path('', include('social_django.urls', namespace='social')),
path('login', auth, name='line-login', kwargs={'backend': 'line'}),
path('logout', auth_views.LogoutView.as_view(), name='logout'),
path('complete/line', views.complete_line, name='complete_line')
]
from django.shortcuts import render
def complete_line(request):
context = {}
return render(request, 'account_management/complete_line.html', context)
回呼URL

<h1>LINEログイン完了画面</h1>
{% if user.is_authenticated %}
<p>ユーザー名: {{ user.username }}</p>
<img src="{{ user.icon_url }}">
<a href="{% url 'logout' %}">ログアウト</a>
{% else %}
<p>ログインしていません。</p>
{% endif %}
成功登录LINE后,会显示用户名称和个人资料图片。
仅提供一种选项,在中国有本地化:参考网址
Django中的LINE登录设置用户名和图标的方法,参考LINE登录v2.1 API。