示例#1
0
def destroy_oauth(request,site):
    """
    删除一个绑定
    """
    unlogined_redirect(request)

    ts=TokenService(request.user)
    ts.deleteToken(site)
    return redirect("account:oauth_manage")
示例#2
0
 def get_or_create_user(self):
     """
     返回一个字典:
     user:保存用户实体对象
     password:只在用户被系统自动创建时返回,否则为空
     """
     retdic = {}
     #尝试获取oauth,以此来得到对应的用户
     try:
         oauth = Token.objects.get(
             site = self.site,
             access_token = self.access_token,
             refresh_token = self.refresh_token,
         )
     #没有匹配数据,那么新建一个用户,为该用户关联该数据
     #自动创建的账号名和密码等规则还需要进一步讨论才能确定,
     #目前暂时这么处理
     except ObjectDoesNotExist:
         #创建用户
         username = ""
         email = ""
         if self.name:
             username = self.name
             email = self.name + "@temp.com"
         else:
             username = self.openid
             email = self.openid + "@temp.com"
             #password = random.randint(100000,999999)
         password = "******"
         new_user = User.objects.create(username=username, email=email, nickname=self.nick)
         new_user.set_password(password)
         new_user.save()
         #绑定到社交网络
         tokenService = TokenService(new_user)
         tokenService.addToken(
             self.site,
             access_token=self.access_token,
             refresh_token=self.refresh_token,
             expires_in=self.expires_in,
             openid=self.openid,
             )
         user = new_user
         retdic["password"] = password
     #否则获取该数据的对应用户
     else:
         user = oauth.user
     #为user添加backend,用于将用户寄存在session中
     user.backend = 'django.contrib.auth.backends.ModelBackend'
     retdic["user"] = user
     return retdic
示例#3
0
def tw_oauth_confirm(request):
    """
    处理请求完code后的回调,同时申请腾讯微博accessToken
    """

    if 'state' in request.GET:
        state = request.GET['state']
        #防止跨站伪造请求攻击
        # if state == request.session["oauthstate"]:
        if True:
            code = request.GET['code']
            # openid = request.GET['openid']
            # openkey = request.GET['openkey']

            from accounts.platform.handlers.tencentWeiboHandler import client_id, client_secret

            access_token_url = "https://open.t.qq.com/cgi-bin/oauth2/access_token?"\
                               + "client_id=%s&client_secret=%s&redirect_uri=%s&gra"\
                               + "nt_type=authorization_code&code=%s&state=%s"
            redirect_uri = domain + reverse("account:tw_oauth_confirm")
            targetUrl = access_token_url % (client_id, client_secret, redirect_uri, code, state)

            response = str(urlopen(targetUrl).read(), encoding = "utf-8")
            params = unparse_params(response)
            if "access_token" in params:
                user = request.user
                if user.is_authenticated():
                    #如果是已登录的用户,则绑定一个openauth
                    tokenService = TokenService(user)
                    tokenService.addToken(site = 'tw', **params)
                #如果是通过第三方认证登录的用户,检查该token是否已经绑定到某个账号,如果是的话,返回该用户
                #否则系统自动创建一个账户,并绑定这个token
                else:
                    oauthService = OpenAuthService(site = 'tw', **params)
                    ret = oauthService.get_or_create_user()
                    user = ret["user"]
                    if user.is_active:
                        login(request, user)
                    else:
                        return redirect("index")

                return redirect("home:content")
            else:
                pass
    else:
        pass

    return redirect("index")
示例#4
0
def oauth_manage_view(request):
    """
    用户的第三方平台账号管理页面
    """

    unlogined_redirect(request)

    from accounts.platform.config import site_config
    import copy

    sitelist = copy.deepcopy(site_config)

    ts = TokenService(request.user)
    for site in sitelist:
        for token in ts.getTokens():
            if token.site == site['site']:
                site['token'] = token

    return render(request,'accounts/oauth_manage.html',{'sitelist':sitelist})
示例#5
0
def sw_oauth_confirm(request):
    """
    处理请求完code后的回调,同时申请腾讯微博accessToken
    """
    #if request.GET["state"] != request.session['sw_oauth_state']:
    #    print(request.GET["state"])
    a = {}
    a['client_id'] = '2749469053'
    a['client_secret'] = '22a991ef6b614ebc2bcb75555b5a1aec'
    a['grant_type'] = 'authorization_code'
    a['redirect_uri'] = domain + reverse("account:sw_oauth_confirm")
    a['code'] = request.GET["code"]
    import urllib.request
    import urllib.parse
    import json

    querystring = urllib.parse.urlencode(a)
    by = urllib.request.urlopen('https://api.weibo.com/oauth2/access_token',
                                data=bytes(querystring.encode('utf8'))).read()
    j = json.loads(str(by, encoding='utf8'))
    for item in j:
        print("item:" + item)

    if "access_token" in j:
        user = request.user
        if user.is_authenticated():
            tokenService = TokenService(user)
            tokenService.addToken(site=u"sina", access_token=j["access_token"], refresh_token="",
                                  expires_in=j['expires_in'], remind_in=j['remind_in'], openid=j['uid'])
        else:
            oauthService = OpenAuthService(site=u"sina", access_token=j["access_token"], refresh_token="",
                                           expires_in=j['expires_in'], remind_in=j['remind_in'], openid=j['uid'])
            ret = oauthService.get_or_create_user()
            user = ret["user"]
            if user.is_active:
                login(request, user)
            else:
                return redirect("index")
        return redirect("home:statuses")
    else:
        pass
    return redirect("index")