Implementing QQ login in django

The process of qq login on the server side:
1. Place the QQ login button, and point the connection to https://graph.qqq.com/oauth2.0/authorize? Response_type=code &client_id=[YOUR_APPID]&redirect_uri=[YOUR_REDIRECT_URI]&scope=[The_SCOPE], or point to your own website first, then redirect to the past, so as to avoid exposing the APPID;
2. Get the code in the redirect_uri processing function connected above.
3. Use this code to request access_ken from https://graph.qqq.com/oauth2.0/token?Grant_type=authorization_code&client_id=[YOUR_APP_ID]& client_secret=[YOUR_APP_Key]&code=[The_AUTHORIZATION_CODE]& state=[The_CLIENT_STATE]&redirect_uri=[YR_OURECT_URI]
4. After getting the access_token returned, request openid from https://graph.qqq.com/oauth2.0/me?Access_token=YOUR_ACCESS_TOKEN.
5. Finally, other API s provided by Tencent can be invoked with access_token and openid.
So how should the web server corresponding to django operate? The steps are as follows:
1. Redirect the request address of the QQ button to the QQ side;
2. Processing the corresponding redirect_uri to get the value of the variable code;

#url to generate request code
    def get_code_url(self, crsf_token):
        auth_url = '%s?%s'%(self.code_url, urllib.urlencode({
                                        'response_type': 'code',
                                        'client_id': self.appid,
                                        'redirect_uri': self.redirect_url,
                                        'scope': self.scope,
                                        'state': crsf_token,
                                        }))
        
        return auth_url
    #Parsing to get code
    def get_code(self, request):
        return request.REQUEST.get('code')

3. Request access_token from qq q with urllib2 library to get access_token returned.

def get_token_url(self, code):
        token_url = '%s?%s'%(self.token_url, urllib.urlencode({
                                        'grant_type': 'authorization_code',
                                        'client_id': self.appid,
                                        'client_secret': self.appkey,
                                        'code': code,
                                        'redirect_uri': self.redirect_url,
                                    }))
        return token_url

    def get_token(self, code):
        token_url = self.get_token_url(code)
        req = urllib2.Request(token_url)
        resp = urllib2.urlopen(req)
        content = resp.read()
        access_token = urllib2.urlparse.parse_qs(content).get('access_token', [''])[0]
        return access_token

4. Then using urllib2 library, access_token constructs the request to obtain openid.

def get_openid_url(self, token):
        openid_url = '%s?%s'%(self.openid_url, urllib.urlencode({
                                        'access_token': token,
                                    }))
        return openid_url

    def get_openid(self, token):
        openid_url = self.get_openid_url(token)
        req = urllib2.Request(openid_url)
        resp = urllib2.urlopen(req)
        content = resp.read()
        content = content[content.find('(')+1:content.rfind(')')]
        data = simplejson.loads(content)
        return data.get('openid')

5. According to the website's own account rules, prompt users to register their username, mailbox number, etc. (password can not be used), then add this account in the database (if you feel troubled, you can program to generate an account randomly, without user filling in information), and record openid in another table, foreign key points to the account just now, at the same time, use rname, openid, access_toke. N, token_timestamp is entered into session.

The model of the new table is as follows:

class Company(models.Model):
    company = models.CharField('company', max_length=20)
    def __unicode__(self):
        return self.company.decode('utf8')

class OpenId(models.Model):
    user = models.ForeignKey(User, verbose_name='user')
    company = models.ForeignKey(Company, verbose_name='company')
    
    openid = models.CharField('openid', max_length=100)
    
    def __unicode__(self):
        return u'%s, %s'%(self.user.username, self.company)

6. Create users and associate them with qq q accounts

def save(self, request):
        username = self.cleaned_data.get("username")
        email = self.cleaned_data["email"].strip().lower()
        openid = request.session.get('openid')
        company = request.session.get('company')
        company = Company.objects.get(company__iexact=company)
        if not (openid and company):
            return None
        new_user = self.create_user(username) 
        #EmailAddress.objects.add_email(new_user, email)
        EmailAddress(user=new_user, email=email, verified=True, primary=True).save()
        #OpenId.objects.add_openid(new_user, openid, company)
        OpenId(user=new_user, openid=openid, company=company).save()
        return new_user

7. At this point, you can call other API s provided by qq.

8. If the user has not logged out, the next login, directly according to cookie session username, openid,access_token,token_timestamp and other data, according to token_timestamp to determine whether expired, if expired, repeat steps 1-3, and update access_token,token_timestamp in the session; if not expired, then the normal user has logged in to process directly. Call the API provided by qq

9. If the user logs out and logs in next time, repeat 1-4 directly, check out username and so on according to openid, and save it in session.

 

Finally, debugging, because the key and id of qq need to be applied by domain name, and the redirect_url passed by must be the domain name, so when debugging, you can modify the host file of your PC, the general path is C: Windows System32 drivers etc host, probably as follows.

127.0.0.1 www.mydomain.com

  

 

  

  

Reproduced in: https://my.oschina.net/weisenz/blog/200630

Keywords: Session Python Web Server Django

Added by vtroubled on Thu, 13 Jun 2019 21:30:58 +0300