SHARE
TWEET

Untitled

a guest May 7th, 2016 76 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. GITHUB_CLIENTID = 'my git client id'
  2. GITHUB_CLIENTSECRET = ' my git client secret'
  3. GITHUB_CALLBACK = 'http://example.com'
  4.  
  5.  
  6.  
  7. class GithubOauthView(RedirectView):
  8.     permanent = False
  9.     url = None
  10.  
  11.     def get_access_token(self):
  12.         '''
  13.         use code to get access token
  14.         '''
  15.         code = self.request.GET.get('code')
  16.         url = 'https://github.com/login/oauth/access_token'
  17.         data = {
  18.             'grant_type': 'authorization_code',
  19.             'client_id': GITHUB_CLIENTID,
  20.             'client_secret': GITHUB_CLIENTSECRET,
  21.             'code': code,
  22.             'redirect_uri': GITHUB_CALLBACK,
  23.         }
  24.         data = urllib.urlencode(data)
  25.         req = Request(url, data, headers={'Accept': 'application/json'})
  26.         response = urlopen(req)
  27.         result = response.read()
  28.         result = json.loads(result)
  29.         return result
  30.  
  31.     def get_user_info(self, access_token):
  32.         url = 'https://api.github.com/user?access_token=%s' % (access_token)
  33.         response = urlopen(url)
  34.         html = response.read()
  35.         data = json.loads(html)
  36.         username = data['login']
  37.         email = 'oauth@oauth.com'
  38.         password = '********'
  39.         try:
  40.             user = User.objects.get(username=username)
  41.         except:
  42.             user = User.objects.create_user(username, email, password)
  43.             user.save()
  44.         user = authenticate(username=username, password=password)
  45.         login(self.request, user)
  46.  
  47.     def get_redirect_url(self, *args, **kwargs):
  48.             self.url = GITHUB_CALLBACK
  49.         try:
  50.             access_token_info = self.get_access_token()
  51.             access_token = access_token_info['access_token']
  52.             self.get_user_info(access_token)
  53.         except:
  54.             pass
  55.         return super(GithubOauthView, self).get_redirect_url(*args, **kwargs)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top