我正在使用 Django 3.1.7 和 Python 3.9.0 来设置 Google 社交登录。
这是我的家庭视图的片段。
class Home(APIView):
def get(self, request, *args, **kwargs):
authenticated = request.user.is_authenticated
print("Authenticated: ", authenticated)
print("User: ", request.user)
return Response({"message": "Home"}, status=status.HTTP_200_OK)
这是我的 AuthURL 视图的片段。
class AuthURL(APIView):
@method_decorator(csrf_protect)
@method_decorator(never_cache)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
SCOPE = "profile+email"
uri = (
"https://accounts.google.com/o/oauth2/v2/auth?response_type=code"
"&client_id={}&redirect_uri={}&scope={}"
).format(CLIENT_ID, REDIRECT_URI, SCOPE)
return Response({"uri": uri}, status=status.HTTP_200_OK)
这是我的登录视图的片段。
class LoginView(APIView):
@method_decorator(csrf_protect)
@method_decorator(never_cache)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
code = request.GET["code"]
data = {
"code": code,
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"redirect_uri": REDIRECT_URI,
"grant_type": "authorization_code",
}
token = post("https://oauth2.googleapis.com/token", data=data)
response = post("https://oauth2.googleapis.com/tokeninfo", data=token)
data = response.json()
user = User.objects.filter(email=data["email"]).first()
if user is None:
user = User.objects.create_user(email=data["email"], username=data["name"])
login(request, user)
print("Request User: ", request.user)
return redirect("http://localhost:3000/")
应用程序.js
const logIn = () => {
fetch("http://localhost:8000/accounts/get-auth-url/")
.then((response) => response.json())
.then((data) => {
window.location.replace(data.uri);
});
}
const home = () => {
fetch("http://localhost:8000/accounts/home/")
.then((response) => response.json())
.then((data) => {
console.log(data);
});
}
return (
<div className="App">
<button type="button" onClick={logIn}>Log In</button>
<button type="button" onClick={home}>Home</button>
</div>
);
如果请求从主页(前端)发送到后端,我登录用户后,我将 request.user 作为匿名用户。我完全是初学者。