Example #1
0
    def get(self, request):
        code = request.GET.get('code')
        state = request.GET.get('state', '/')
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
        )

        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'code': RETCODE.SERVERERR,
                'errmsg': '服务器发生错误'
            })

        try:
            oauth_model = OauthQQUser.objects.get(openid=openid)
        except OauthQQUser.DoesNotExist:
            # 没有查到openid, 说明是新用户,先把openid保存在前端的隐藏标签中
            openid = save_openid(openid)
            context = {"openid": openid}
            return render(request, 'oauth_callback.html', context)
        else:
            user = oauth_model.user
            login(request, user)
            response = redirect(state)
            response.set_cookie('username',
                                user.username,
                                max_age=settings.SESSION_COOKIE_AGE)
            return response
Example #2
0
    def get(self, request):
        code = request.GET.get('code')
        if not code:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少code参数'})
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '获取openid出错'})

        try:
            oauth_qq = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            # 采用session形式保存openid
            # 创建request.session['键'] = 值
            # 取值value = request.session.get('键',默认值)
            # 设置时长request.session.set_expiry(value)
            request.session['openid'] = openid
            request.session.set_expiry(600)
            return http.JsonResponse({'code': 300, 'errmsg': 'ok'})

        else:
            user = oauth_qq.user
            login(request, user)
            response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie('username',
                                user.username,
                                max_age=3600 * 24 * 14)
            return response
Example #3
0
    def get(self, request):
        code = request.GET.get('code')
        state = request.GET.get('state')
        # redirect_uri = request.GET.get('redirect_uri')
        if code == None:
            return HttpResponseBadRequest('code为空!')

        oauth = OAuthQQ(client_id=QQ_CLIENT_ID,
                        client_secret=QQ_CLIENT_SECRET,
                        redirect_uri=QQ_REDIRECT_URI,
                        state=next)
        token = oauth.get_access_token(code)

        openid = oauth.get_open_id(token)
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            return render(request,
                          'oauth_callback.html',
                          context={'openid': openid})
        else:
            login(request, qquser.user)
            response = redirect(reverse('user1:index'))
            # 设置cookie
            response.set_cookie('username',
                                qquser.user.username,
                                max_age=24 * 3600)
            return response
Example #4
0
    def get(self, request):

        #获取从前段发送来的code参数
        code = request.GET.get("code")

        #验证code获取token
        try:
            oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                               client_secret=settings.QQ_CLIENT_SECRET,
                               redirect_uri=settings.QQ_REDIRECT_URI)
            token = oauth_qq.get_access_token(code)

            #根据token获取openid
            openid = oauth_qq.get_open_id(access_token=token)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, 'errmsg': "qq登录失败!"})
        try:
            oauth_qq = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist as e:
            #用户没有绑定过qq,我们需要返回加密的openid
            access_token = generate_access_token(openid)
            return JsonResponse({'access_token': access_token})

        #用户已经绑定过qq-->登录成功
        user = oauth_qq.user
        #状态保持
        login(request, user)
        response = JsonResponse({'code': 0, 'errmsg': "ok"})
        response.set_cookie("username", user.username, max_age=3600 * 24 * 14)

        return response
Example #5
0
    def get(self, request):
        code = request.GET.get('code')
        if code is None:
            return http.HttpResponseForbidden('必传参数不能为空')

        # 根据code 获取access_token

        auth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
        )
        try:
            access_token = auth.get_access_token(code)
            # 根据access_token 获取openid
            openid = auth.get_open_id(access_token)
        except:
            return http.HttpResponseForbidden('获取openid失败')

        try:
            user = OAuthQQUser.objects.get(openId=openid)
        except BaseException as e:
            # 用户首次用QQ 登录
            access_token = MD5(openid).generate_access_token()
            context = {'access_token': access_token}
            return render(request, 'oauth_callback.html', context)
        else:
            # 用户非首次QQ登录
            # 1 状态保持
            login(request, user.user)
            response = redirect(reverse('contents:index'))
            response.set_cookie('username',
                                user.user.username,
                                max_age=3600 * 24 * 7)
            return response
Example #6
0
    def get(self, request):
        code = request.GET.get("code")
        state = request.GET.get("state")
        if code is None:
            return HttpResponseBadRequest("meiyou1code")
        # 导入QQ互联包
        from QQLoginTool.QQtool import OAuthQQ
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=state)
        # 获取token
        token = oauth.get_access_token(code)
        # 获取openid
        openid = oauth.get_open_id(token)
        # 判断openid
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            return render(request,
                          "oauth_callback.html",
                          context={"openid": openid})
        else:
            login(request, qquser.user)

            response = redirect(reverse("concents:index"))
            response.set_cookie("username", qquser.user, max_age=3600 * 24)
            return response
Example #7
0
    def get(self, request):
        code = request.GET.get('code')
        if not code:
            return http.HttpResponseForbidden("缺少code")
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            aaaaaccess_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(aaaaaccess_token)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('OAuth2.0认证失败')
        try:
            oauth_user = OauthQQUser.objects.get(openid=openid)
        except OauthQQUser.DoesNotExist:
            # 没有帮顶qq
            access_token = generate_access_token(openid)
            context = {'access_token': access_token}
            return render(request, 'oauth_callback.html', context)

        else:
            qq_user = oauth_user.user
            login(request, qq_user)
            response = redirect(reverse('contents:index'))
            response.set_cookie('username',
                                qq_user.username,
                                max_age=3600 * 24 * 14)
            return response
Example #8
0
    def get(self, request):
        #1 获取参数
        code = request.GET.get('code')
        #2 校验参数
        if not code:
            return http.HttpResponseForbidden("code丢失")
        # 3 获取access_token
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state='/')

        access_token = oauth_qq.get_access_token(code=code)

        #  4 获取openid
        openid = oauth_qq.get_open_id(access_token=access_token)

        #5 判断是否绑定
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            print("没有该用户")
            #初次授权
            encrypt_openid = encode_openid(openid)
            context = {"token": encrypt_openid}
            return render(request, 'oauth_callback.html', context=context)
        else:
            # 非初次授权,获取梅朵用户
            user = qq_user.user
            login(request, user)
            response = redirect(reverse('contents:index'))
            response.set_cookie('username', user.username)
            response = merge_cart_cookie_to_redis(request, user, response)
            return response
Example #9
0
 def get(self, request):
     code = request.GET.get("code")
     oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI)
     try:
         access_token = oauth.get_access_token(code)
         openid = oauth.get_open_id(access_token)
     except:
         return JsonResponse({"code": 400, "message": "登陆失败"})
     try:
         qq_user = OAuthQQUser.objects.get(openid=openid)
     except:
         secret_openid = generate_secret_openid(openid)
         return JsonResponse({
             "code": 300,
             "message": "OK",
             "secret_openid": secret_openid
         })
     else:
         user = qq_user.user
         login(request, user)
         response = JsonResponse({"code": 0, "message": "OK"})
         response.set_cookie("username",
                             user.username,
                             max_age=14 * 24 * 3600)
         cart_helper = CartHelper(request, response)
         cart_helper.merge_cookie_cart_to_redis()
         return response
Example #10
0
    def get(self,request):
        # 1.获取code值和state
        code=request.GET.get("code")
        state=request.GET.get("state")
        print(code,state)
        state="/index/"
        if code is None or state is None:
            return JsonResponse({"error":"缺少参数"})

        #2.生成qq对象
        qq=OAuthQQ(client_id=settings.QQ_CLIENT_ID,client_secret=settings.QQ_CLIENT_SECRET,
                   redirect_uri=settings.QQ_REDIRECT_URI,state=state)
        try:
            # 3.调用方法获取access_token值
            access_token=qq.get_access_token(code)
            openid=qq.get_open_id(access_token)
        except:
            return JsonResponse({"error":"网络错误"})
        try:
            #判断qq有没有绑定美多账号
            qq_user=OAuthQQUser.objects.get(openid=openid)
        except:
            tjw = TJW(settings.SECRET_KEY, 300)
            openid = tjw.dumps({'openid': openid}).decode()
            return render(request, 'oauth_callback.html', {'token': openid})
        #绑定的用户
        login(request,qq_user.user)

        #将用户写入cookie方便在页面中展示
        response=redirect(state)
        response.set_cookie("username",qq_user.user.username,60 * 60 * 2)
        #合并购物车
        response = merge_cart_cookie_to_redis(request,qq_user.user,response)
        return response
Example #11
0
 def get(self, request):
     code = request.query_params.get('code')
     if code is None:
         return Response(status=status.HTTP_400_BAD_REQUEST)
     oauth = OAuthQQ(
         client_id=settings.QQ_CLIENT_ID,
         client_secret=settings.QQ_CLIENT_SECRET,
         redirect_uri=settings.QQ_REDIRECT_URL,
     )
     access_token = oauth.get_access_token(code)
     #通过token获取openid
     openid = oauth.get_open_id(access_token)
     # 获取到openid后,我们要查询一下数据库  是否有openid  显示不同页面
     try:
         qquser = OAuthQQUser.objects.get(openid=openid)
     except OAuthQQUser.DoesNotExist:
         # 如果没有 则说明用户没绑定过
         # openid是一个比较敏感的信息,需要加密,最好在设置一个有效期
         access_token = generic_access_token(openid)
         return Response({'access_token': access_token})
     else:
         jwt_payload_handler = api_settings.JWTPAYLOAD_HANDLER
         jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
         payload = jwt_payload_handler(qquser.user)
         token = jwt_encode_handler(payload)
         return Response({
             'token': token,
             'username': qquser.user.username,
             'user_id': qquser.user.id
         })
Example #12
0
    def get(self, request):
        code = request.GET.get('code')
        state = request.GET.get('state')

        if code is None:
            return HttpResponseBadRequest('code已过期')
        oauthqq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                          client_secret=settings.QQ_CLIENT_SECRET,
                          redirect_uri=settings.QQ_REDIRECT_URI,
                          state=state)
        token = oauthqq.get_access_token(code)

        openid = oauthqq.get_open_id(token)

        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            new_openid = serect_openid(openid)
            return render(request,
                          'oauth_callback.html',
                          context={'openid': new_openid})
        else:
            login(request, qquser.user)
            response = redirect(reverse('contents:index'))
            response.set_cookie('username', qquser.user.username, max_age=3600)
            return response
Example #13
0
 def get(self,request):
     code=request.GET.get('code')
     next=request.GET.get('state') or '/'
     if not code:
         return HttpResponse(request,'登录失败')
     oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=next)
     try:
         # 使用code向QQ服务器请求access_token
         access_token = oauth.get_access_token(code)
         # 使用access_token向QQ服务器请求openid
         openid = oauth.get_open_id(access_token)
     except Exception as e:
         logger.error(e)
         return HttpResponseServerError('OAuth2.0认证失败')
     try:
         user=OAuthQQUser.objects.get(openid=openid)
     except OAuthQQUser.DoesNotExist:
         openid=generate_openid_signature(openid)
         context = {'openid': openid}
         return render(request, 'oauth_callback.html', context)
     else:
         login(request,user.user)
         response=redirect(next)
         response.set_cookie('username',user.user,max_age=3600 * 24 * 15)
         return response
Example #14
0
    def get(self, request):
        code = request.GET.get('code')
        if not code:
            return JsonResponse({'code': 400, 'errmsg': '必传参数为空'})
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
        )
        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.info(e)
            return JsonResponse({'code': 400, 'errmsg': '获取openid失败'})

        try:
            auth_qq = OAuthQQUser.objects.get(openid=openid)
        except:
            access_token = generate_access_token_by_openid(openid)
            return JsonResponse({
                'code': 300,
                'errmsg': 'ok',
                'access_token': access_token
            })
        else:
            user = auth_qq.user
            login(request, user)
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie('username',
                                user.username,
                                max_age=3600 * 24 * 14)
            return response
Example #15
0
    def get(self, request):
        code = request.GET.get('code')
        logger.info(code)
        if not code:
            return http.HttpResponseForbidden('缺少参数')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            access_token = oauth.get_access_token(code)
            open_id = oauth.get_open_id(access_token)
        except Exception as e:
            return http.HttpResponseServerError('OAuth2.0认证失败')

        try:
            oauthqq = OAuthQQUser.objects.get(openid=open_id)

        except:
            ct_access_token = generate_access_token(open_id)
            context = {'access_token': ct_access_token}
            return render(request, 'oauth_callback.html', context)
        else:
            state = request.GET.get('state')
            qq_username = oauthqq.user.username
            qq_user = oauthqq.user
            login(request, qq_user)
            response = redirect(state)
            response.set_cookie('username',
                                qq_username,
                                max_age=3600 * 24 * 15)
            return response
Example #16
0
    def get(self, request):
        """
        Oauth2.0认证
        :param request:
        :return:
        """
        # 提取code请求参数
        code = request.GET.get('code')
        if not code:
            return http.HttpResponseForbidden('缺少参数')

        # 创建工具对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        # 使用code向QQ服务器请求access_token
        access_token = oauth.get_access_token(code)

        # 使用access_token向QQ服务器请求openid
        openid = oauth.get_open_id(access_token)

        # 4. 判断是否绑定openid
        response = is_bind_openid(openid, request)

        return response
Example #17
0
    def get(self, request):

        code = request.GET.get('code')

        token_code = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                             client_secret=settings.QQ_CLIENT_SECRET,
                             redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            acess_token = token_code.get_access_token(code)
            openid = token_code.get_open_id(acess_token)
            print(openid)
        except Exception as ret:
            return ret
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # openid 需要加密
            token = get_acess_token(openid)
            # 将加密的唯一表示openid 响应给前端
            return render(request, 'oauth_callback.html', {'openid': token})
        else:
            user = oauth_user.user
            login(request, user)
            next = request.GET.get('state')
            response = redirect(next or '/')
            response.set_cookie('username',
                                user.username,
                                max_age=settings.SESSION_COOKIE_AGE)

            # 合并购物车
            merge_carts_cookie_2_redis(request, response)
            return response
Example #18
0
    def get(self, request):
        code = request.GET.get('code')
        state = request.GET.get('state', '/')

        oauthqq = OAuthQQ(settings.QQ_CLIENT_ID, settings.QQ_CLIENT_SECRET,
                          settings.QQ_REDIRECT_URI, state)

        # 1.根据code获取token
        token = oauthqq.get_access_token(code)

        # 2.根据token获取openid
        openid = oauthqq.get_open_id(token)

        # 判断是否初次授权
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except:
            # 未查到数据,则为初次授权,显示绑定页面
            # 将openi加密
            json_str = meiduo_signature.dumps({"openid": openid},
                                              constants.OPENID_EXPIRES)
            # 显示绑定页面
            context = {'token': json_str}
            return render(request, 'oauth_callback.html', context)
        else:
            # 查询到授权对象,则状态保持,转到相关页面
            user = qquser.user
            login(request, user)

            response = redirect(state)
            response.set_cookie('username', user.username)
            return response
Example #19
0
    def get(self, request):
        # 获取前端发送过来的 code 参数
        code = request.GET.get('code')

        try:  # 创建工具对象
            oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                               client_secret=settings.QQ_CLIENT_SECRET,
                               redirect_uri=settings.QQ_REDIRECT_URI)
            # 携带 code 向 QQ服务器 请求 access_token
            token = oauth_qq.get_access_token(code)
            # 携带 access_token 向 QQ服务器 请求 openid
            openid = oauth_qq.get_open_id(access_token=token)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': 'qq登陆失败!'})

        try:  #查看用户请求的openid是否与已绑定openid相同,是则调用登录
            oauth_qq = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist as e:
            # 4、用户没有绑定过qq:我们需要返回加密的openid
            access_token = generate_access_token(openid)
            return JsonResponse({'access_token': access_token})

        # 5、用户已经绑定过qq——登陆成功!!
        user = oauth_qq.user
        login(request, user)  # 状态保持
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        response = merge_cart_cookie_to_redis(request, user, response)
        return response
Example #20
0
    def get(self, request):
        """Oauth2.0认证"""
        #接收Authorization Code

        code = request.GET.get('code')
        if not code:
            return http.HttpResponseForbidden('缺少code')

        #创建工具对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            #携带code 向QQ服务器请求access_token
            access_token = oauth.get_access_token(code)

            #携带access_token 向QQ服务器请求openid
            openid = oauth.get_open_id(access_token)

        except Exception as e:
            #如果上面获取的openid出错,验证失败
            logger.error(e)

            #返回结果
            return http.HttpResponseServerError('OAuth2.0认证失败')

        #判断openid是否绑定用户
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            #如果openid没有绑定用户
            #调用封装好的方法
            access_token = generate_access_token(openid)

            # #拿到access_token 字符串,拼接字典
            context = {'access_token': access_token}

            # #返回响应,重新渲染
            return render(request, 'oauth_callback.html', context)
            pass

        else:
            #如果已绑定用户
            qq_user = oauth_user.user

            #实现状态保持
            login(request, qq_user)

            #创建重定向到主页的对象
            response = redirect(reverse('contents:index'))

            #将用户信息写到cookie中,有效期15天
            response.set_cookie('username',
                                qq_user.username,
                                max_age=3600 * 24 * 15)

            #返回响应
            return response
Example #21
0
    def get(self, request):
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.info(e)
            return Response({'message': 'QQ服务器内部错误'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        try:
            oauthuser_model = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            openid_access_token = generate_save_user_token(openid)
            return Response({'access_token': openid_access_token})
        else:
            # 必须在注册或者登录之后,响应注册或者登录结果之前,生成jwt_token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            user = oauthuser_model.user
            # 生成载荷:包含了user_id,username,email
            payload = jwt_payload_handler(user)
            # jwt_token
            token = jwt_encode_handler(payload)
            # 将token添加到user : python是面向对象的高级动态编程语言
            # 合并购物车
            response = Response({
                'user_id': user.id,
                'username': user.username,
                'token': token
            })
            response = merge_cart_cookie_to_redis(request, response, user)
            return response
Example #22
0
    def get(self, request):
        # 1. 获取code
        code = request.GET.get('code')
        if code is None:
            return JsonResponse({'code': 400, 'errmsg': '没有code参数'})

        QQ_CLIENT_ID = '101474184'
        QQ_CLIENT_SECRET = 'c6ce949e04e12ecc909ae6a8b09b637c'
        QQ_REDIRECT_URI = 'http://www.meiduo.site:8080/oauth_callback.html'

        qq = OAuthQQ(client_id=QQ_CLIENT_ID,
                     client_secret=QQ_CLIENT_SECRET,
                     redirect_uri=QQ_REDIRECT_URI)

        # 2. 通过 coke 换取 token
        access_token = qq.get_access_token(code)

        # 3. 通过 token 获取 openid
        openid = qq.get_open_id(access_token)

        # 4. 根据 openid 进行数据查询
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            return JsonResponse({'code': 300, 'access_token': openid})
        else:
            login(request, qquser.user)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', qquser.user.username, 14 * 24 * 3600)

        return response
Example #23
0
    def get(self, request):
        code = request.GET.get("code")
        if not code:
            return http.HttpResponseForbidden('缺少code')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=None)
        try:
            accss_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(accss_token)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('OAuth2.0认证失败')
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            #
            context = {"openid": openid}
            return render(request, 'oauth_callback.html', context)
        else:
            qq_user = oauth_user.user
            login(request, qq_user)

            # 重定向到主页
            response = redirect(reverse('users:index'))

            # 登录时用户名写入到cookie,有效期15天
            response.set_cookie('username',
                                qq_user.username,
                                max_age=3600 * 24 * 15)

            return response
Example #24
0
    def get(self, request):
        code = request.GET.get('code')
        next = request.GET.get('state')
        if not code:
            return http.HttpResponseServerError('缺少code')
        try:
            oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                            client_secret=settings.QQ_CLIENT_SECRET,
                            redirect_uri=settings.QQ_REDIRECT_URI,
                            state=next)
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('OAuth2.0认证失败')

        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist as e:
            logger.error(e)
            access_token_openid = generate_access_token(openid)
            context = {'access_token_openid': access_token_openid}
            return render(request, 'oauth_callback.html', context)
        else:
            login(request, oauth_user.user)

        next = request.GET.get('state')
        response = redirect(next)
        response.set_cookie('username',
                            oauth_user.user.username,
                            max_age=3600 * 24 * 15)
        return response
Example #25
0
 def get(self, request):
     code = request.GET.get('code')
     if code is None:
         return JsonResponse({'code': 400, 'errmsg': "没有code参数"})
     # QQ登录参数
     # 我们申请的 客户端id
     QQ_CLIENT_ID = '101474184'
     # 我们申请的 客户端秘钥
     QQ_CLIENT_SECRET = 'c6ce949e04e12ecc909ae6a8b09b637c'
     # 我们申请时添加的: 登录成功后回调的路径
     QQ_REDIRECT_URI = 'http://www.meiduo.site:8080/oauth_callback.html'
     qq = OAuthQQ(client_id=QQ_CLIENT_ID,
                  client_secret=QQ_CLIENT_SECRET,
                  redirect_uri=QQ_REDIRECT_URI)
     # 使用code换取token
     access_token = qq.get_access_token(code)
     # 使用token换取openid
     openid = qq.get_open_id(access_token)
     from apps.oauth.models import OAuthQQUser
     # 根据openid进行判断
     try:
         qquser = OAuthQQUser.objects.get(openid=openid)
     except:
         from apps.oauth.utils import generate_access_token
         token = generate_access_token(openid)
         return JsonResponse({'code': 300, 'access_token': token})
     else:
         from django.contrib.auth import login
         login(request, qquser.user)
         response = JsonResponse({'code': 0, 'errmsg': "OK"})
         response.set_cookie('username',
                             qquser.user.username,
                             max_age=14 * 24 * 3600)
         return response
Example #26
0
    def get(self, request):

        code = request.GET.get("code")

        if not code:
            return http.HttpResponseForbidden('EREER:501')
        oauthqq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                          client_secret=settings.QQ_CLIENT_SECRET,
                          redirect_uri=settings.QQ_REDIRECT_URI,
                          state="next")
        try:
            access_token = oauthqq.get_access_token(code)
            open_id = oauthqq.get_open_id(access_token)
        except Exception as e:
            logging.error(e)
            return http.HttpResponseForbidden('django_qq_exain:flase')
        try:
            oauthqq_user = OAuthQQUser.objects.get(openid=open_id)
        except OAuthQQUser.DoesNotExist:
            s = Serializer()
            context = {
                "access_token_openid": s.dupmsl(open_id).decode('utf-8')
            }
            return render(request, 'oauth_callback.html', context=context)
        else:
            login(request, oauthqq_user.users)
            response = render(reverse('Contents:index'))
            response.set_cookie('username',
                                oauthqq_user.user.username,
                                max_age=3000 * 24 * 30)
            return response
Example #27
0
    def get(self, request):

        # 1、提取查询字符串参数code
        code = request.GET.get('code')
        # 2、验证code获取token
        try:
            oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                               client_secret=settings.QQ_CLIENT_SECRET,
                               redirect_uri=settings.QQ_REDIRECT_URI)
            token = oauth_qq.get_access_token(code)
            # 3、根据token获取openid
            openid = oauth_qq.get_open_id(access_token=token)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': 'qq登陆失败!'})

        try:
            oauth_qq = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist as e:
            # 4、用户没有绑定过qq:我们需要返回加密的openid
            access_token = generate_access_token(openid)
            return JsonResponse({'access_token': access_token})

        # 5、用户已经绑定过qq——登陆成功!!
        user = oauth_qq.user
        login(request, user)  # 状态保持
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        return response
Example #28
0
File: views.py Project: sunsyw/web
    def get(self, request):
        # 接收code
        code = request.query_params.get('code')
        if code is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # 用code换取token
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            token = oauth.get_access_token(code)
            # 通过token换取openid
            openid = oauth.get_open_id(token)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 通过openid查询判断
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果没有查询出来,则创建用户
            openid_itsdangerous = generate_openid_token(openid)
            return Response({'access_token': openid_itsdangerous})
        else:
            # 没有异常则登录
            # 登录状态token
            token = jwt_login(qquser)
            return Response({
                'token': token,
                'username': qquser.user.username,
                'user_id': qquser.user.id
            })
Example #29
0
    def get(self, request):
        code = request.GET.get('code')
        if code is None:
            return JsonResponse()
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state='/'

        )
        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            print(e)
            return JsonResponse({})
        # TODO:判断用户是否绑定账号
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            # 未绑定 —— 加密openid返回给前端(前端跳转到绑定页面)
            access_token = SecrectOauth().dump({'openid': openid})
            return JsonResponse({'code': 400, 'errmsg': 'ok', 'access_token': access_token})
        else:
            # 已经绑定 —— 直接正常响应 —— 登陆成功

            user = oauth_user.user
            login(request, user)
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})

            response.set_cookie('username', user.username, max_age=14 * 3600 * 24)
            return response
Example #30
0
    def get(self, request):
        code = request.GET.get('code')
        if code is None:
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state='xxxxx')
        token = qq.get_access_token(code)
        openid = qq.get_open_id(token)

        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            from apps.oauth.utils import generic_openid
            access_token = generic_openid(openid)

            response = JsonResponse({
                'code': 400,
                'access_token': access_token
            })
            return response

        else:
            login(request, qquser.user)
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})

            response.set_cookie('username', qquser.user.username)
            return response
Example #31
0
    def get(self, request):
        """Oauth2.0认证"""
        # 接收Authorization Code
        code = request.GET.get('code')
        if not code:
            return http.HttpResponseForbidden('缺少code')

        # 创建工具对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            # 携带 code 向 QQ服务器 请求 access_token
            access_token = oauth.get_access_token(code)

            # 携带 access_token 向 QQ服务器 请求 openid
            openid = oauth.get_open_id(access_token)

        except Exception as e:
            # 如果上面获取 openid 出错, 则验证失败
            logger.error(e)
            # 返回结果
            return http.HttpResponseServerError('OAuth2.0认证失败')

        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)

        except OAuthQQUser.DoesNotExist:
            # 如果 openid 没绑定美多商城用户,进入这里:
            # 调用我们封装好的方法, 对 openid 进行加密, 生成 access_token 字符串
            access_token = generate_access_token(openid)
            # 拿到 access_token 字符串后, 拼接字典
            context = {'access_token': access_token}
            # 返回响应, 重新渲染
            return render(request,'oauth_callback.html', context)

        else:
            # 如果 openid 已绑定美多商城用户
            # 根据 user 外键, 获取对应的 QQ用户
            qq_user = oauth_user.user
            # 实现状态保持
            login(request, qq_user)

            # 创建重定向到主页的对象
            response = redirect(reverse('contents:index'))

            # 将用户信息写入到 cookie 中,有效期15天
            response.set_cookie('username',qq_user.username,max_age=3600 * 24 * 15)

            # 合并购物车
            response = merge_cart_cookie_to_redis(request=request, user=qq_user, response=response)

            # 返回响应
            return response