The Django project uses qq q third party login.

Keywords: Python Session JSON Database Django

The premise of using qqq login is to create website application on QQ interconnected official website and obtain APP ID and APP KEY of website application in QQ interconnection.

1. Routing

#     qq Sign in
    path('loginQq/',qq.loginQq,name='loginQq/'),
    path('returns/',qq.returns,name='returns/'),

2. The front page writes the link of qq login. This article does not use icon, but temporarily uses a link request.

<a data-wow-delay=".5s" href="/blog/loginQq/"> »  QQ Sign in</a>

3, create a utils folder under the application of the project and create function.py to encapsulate the function. The encapsulated function is used to extract openid from the returned data (user id in the database).

The encapsulated functions are as follows.

import re

def parse_jsonp(jsonp_str):
    try:
        return re.search('^[^(]*?\((.*)\)[^)]*$', jsonp_str).group(1)
    except:
        raise ValueError('Invalid data!')

4. Background code

from django.shortcuts import render,redirect,HttpResponse,HttpResponseRedirect
from blog.models import Member
from urllib import parse
from urllib import request as req
import re
import json
import random
from blog.utils import function
def loginQq(request):
    state = str(random.randrange(100000,999999)) # Define a random state code to prevent cross-domain forgery attacks.
    request.session['state'] = state  # Store random state codes in Session,Used for authentication when authorization information returns.
    client_id = '101716344'  # QQ Web site application in interconnection APP ID. 
    # The callback address is encoded, and the user agrees to authorize it to call the link.
    callback = parse.urlencode({'redirect_uri':'http://127.0.0.1:8000/blog/returns'})   #redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fblog%2Freturns
    # organization QQ Third party login link
    login_url = 'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=%s&%s&state=%s'%(client_id,callback,state)
    return HttpResponseRedirect(login_url)  # Redirection to QQ Third party login authorization page
def returns(request):
    if request.session['state'] == request.GET['state']:  # Verify the status code to prevent cross-domain forgery attacks.
        code = request.GET['code']  # Getting User Authorization Code
        client_id = '101716344'  # QQ Web site application in interconnection APP ID. 
        client_secret = '7f42aaac69f866750078fbe1edd9d2a4'  # QQ Web site application in interconnection APP Key. 
        callback = parse.urlencode({'redirect_uri': 'http://127.0.0.1:8000/blog/returns'})
        # The callback address is encoded, and the user agrees to authorize it to call the link.
        login_url = 'https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s&%s' % (code, client_id, client_secret, callback)  # Organizations get links to access tokens
        # return HttpResponse(login_url)
        response = req.urlopen(login_url).read().decode()  # Open a link to get access tokens   access_token:123456789&

        access_token = re.split('&', response)[0]  # access token  access_token:123456789

        res = req.urlopen('https://graph.qq.com/oauth2.0/me?' + access_token).read().decode()  # Open access openid Links

        openid = json.loads(function.parse_jsonp(res))['openid']  # Getting from the returned data openid  410225632333335556566

        userinfo = req.urlopen('https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s&%s' % (
            client_id, openid, access_token)).read().decode()  # Open a link to get user information
        # Print and view the obtained user information
        print(userinfo)
        userinfo = json.loads(userinfo)  # User information data to be returned( JSON Format) Read as a dictionary.
        user = Member.objects.filter(member_qq_id=openid)  # Query whether a user already exists
        if not user:  # If no user exists
            # Create new users
            member_obj = Member.objects.create(member_qq_id=openid,member_nickname=userinfo['nickname'],member_name=userinfo['nickname'],member_photo = userinfo['figureurl_qq_1'])
            # user = Member()  # Create new users
            # user.member_qq_id = openid  # Write user information
            # user.member_nickname = userinfo['nickname']  # Write user information
            # user.member_name = userinfo['nickname']  # Write user information
            # # user.gender = userinfo['gender']  # Write user information
            # user.member_photo = userinfo['figureurl_qq_1']  # Write user information
            # user.save()  # Save or update users
            request.session['member_id'] = member_obj.member_id  # Users who will be logged in openid Write in Session
            request.session['member_name'] = userinfo['nickname']
        #  Back to the homepage
        return redirect('/blog/index/')
    else:
        return HttpResponse('Authorization failed!')

This article is the qqq login function in the local test project, so the callback address in the qqq interconnected official network needs to be changed to the local address.

5. Start Project Testing Function

 

6. Look at the membership table of the database and the membership information has been written.

done.

Posted by Avendium on Fri, 04 Oct 2019 19:52:58 -0700