Exemplo n.º 1
0
 def post(self, request, *args, **kwargs):
     oauth_user_id = str(request.data.get("oauth_user_id"))
     service_id = request.data.get("service_id")
     try:
         oauth_service = oauth_repo.get_oauth_services_by_service_id(service_id=service_id)
     except Exception as e:
         logger.debug(e)
         rst = {"data": {"bean": None}, "status": 404,
                "msg_show": u"未找到oauth服务, 请检查该服务是否存在且属于开启状态"}
         return Response(rst, status=status.HTTP_200_OK)
     user_id = request.user.user_id
     oauth_user = oauth_user_repo.user_oauth_exists(service_id=service_id, oauth_user_id=oauth_user_id)
     link_user = oauth_user_repo.get_user_oauth_by_user_id(service_id=service_id, user_id=user_id)
     if link_user is not None and link_user.oauth_user_id != oauth_user_id:
         rst = {"data": {"bean": None}, "status": 400, "msg_show": u"绑定失败, 该用户已绑定其他账号"}
         return Response(rst, status=status.HTTP_200_OK)
     if oauth_user:
         oauth_user.user_id = user_id
         oauth_user.save()
         data = {
             "oauth_user_id": oauth_user.oauth_user_id,
             "oauth_user_name": oauth_user.oauth_user_name,
             "oauth_user_email": oauth_user.oauth_user_email,
             "is_authenticated": oauth_user.is_authenticated,
             "is_expired": oauth_user.is_expired,
             "is_link": True,
             "service_id": service_id,
             "oauth_type": oauth_service.oauth_type,
         }
         rst = {"data": {"bean": data}, "status": 200, "msg_show": u"绑定成功"}
         return Response(rst, status=status.HTTP_200_OK)
     else:
         rst = {"data": {"bean": None}, "status": 404, "msg_show": u"绑定失败,请重新认证"}
         return Response(rst, status=status.HTTP_200_OK)
Exemplo n.º 2
0
 def get(self, request, service_id, *args, **kwargs):
     user_id = request.user.user_id
     page = request.GET.get("page", 1)
     search = request.GET.get("search", '')
     oauth_service = oauth_repo.get_oauth_services_by_service_id(
         service_id=service_id)
     oauth_user = oauth_user_repo.get_user_oauth_by_user_id(
         service_id=service_id, user_id=user_id)
     if oauth_user is None:
         rst = {
             "data": {
                 "bean": None
             },
             "status": 400,
             "msg_show": u"未成功获取第三方用户信息"
         }
         return Response(rst, status=status.HTTP_200_OK)
     service = get_oauth_instance(oauth_service.oauth_type, oauth_service,
                                  oauth_user)
     if not service.is_git_oauth():
         rst = {
             "data": {
                 "bean": None
             },
             "status": 400,
             "msg_show": u"该OAuth服务不是代码仓库类型"
         }
         return Response(rst, status=status.HTTP_200_OK)
     try:
         if len(search) > 0 and search is not None:
             true_search = oauth_user.oauth_user_name + '/' + search.split(
                 "/")[-1]
             data = service.search_repos(true_search, page=page)
         else:
             data = service.get_repos(page=page)
         rst = {
             "data": {
                 "bean": {
                     "repositories": data,
                     "user_id": user_id,
                     "service_id": service_id,
                     "service_type": oauth_service.oauth_type,
                     "service_name": oauth_service.name,
                     "total": 10
                 }
             }
         }
         return Response(rst, status=status.HTTP_200_OK)
     except Exception as e:
         logger.debug(e)
         rst = {
             "data": {
                 "bean": None
             },
             "status": 400,
             "msg_show": u"Access Token 已过期"
         }
         return Response(rst, status=status.HTTP_200_OK)
Exemplo n.º 3
0
 def get(self, request, *args, **kwargs):
     code = request.GET.get("code")
     service_id = request.GET.get("service_id")
     service = oauth_repo.get_oauth_services_by_service_id(service_id)
     route_mode = os.getenv("ROUTE_MODE", "hash")
     path = "/#/oauth/callback?service_id={}&code={}"
     if route_mode == "history":
         path = "/oauth/callback?service_id={}&code={}"
     return HttpResponseRedirect(path.format(service.ID, code))
Exemplo n.º 4
0
 def get(self, request, service_id, *args, **kwargs):
     user_id = request.user.user_id
     type = request.GET.get("type")
     full_name = request.GET.get("full_name")
     oauth_service = oauth_repo.get_oauth_services_by_service_id(service_id)
     oauth_user = oauth_user_repo.get_user_oauth_by_user_id(
         service_id=service_id, user_id=user_id)
     if oauth_user is None:
         rst = {
             "data": {
                 "bean": None
             },
             "status": 400,
             "msg_show": u"未成功获取第三方用户信息"
         }
         return Response(rst, status=status.HTTP_200_OK)
     try:
         service = get_oauth_instance(oauth_service.oauth_type,
                                      oauth_service, oauth_user)
     except Exception as e:
         logger.debug(e)
         rst = {
             "data": {
                 "bean": None
             },
             "status": 400,
             "msg_show": u"未找到OAuth服务"
         }
         return Response(rst, status=status.HTTP_200_OK)
     if not service.is_git_oauth():
         rst = {
             "data": {
                 "bean": None
             },
             "status": 400,
             "msg_show": u"该OAuth服务不是代码仓库类型"
         }
         return Response(rst, status=status.HTTP_200_OK)
     try:
         data = service.get_branches_or_tags(type, full_name)
         rst = {"data": {"bean": {type: data, "total": len(data)}}}
         return Response(rst, status=status.HTTP_200_OK)
     except Exception as e:
         logger.debug(e)
         rst = {
             "data": {
                 "bean": None
             },
             "status": 400,
             "msg_show": u"Access Token 已过期"
         }
         return Response(rst, status=status.HTTP_200_OK)
Exemplo n.º 5
0
    def get(self, request, service_id, path, name, *args, **kwargs):
        full_name = '/'.join([path, name])
        user_id = request.user.user_id
        try:
            oauth_service = oauth_repo.get_oauth_services_by_service_id(service_id=service_id)
            oauth_user = oauth_user_repo.get_user_oauth_by_user_id(service_id=service_id, user_id=user_id)
        except Exception as e:
            logger.debug(e)
            rst = {"data": {"bean": None}, "status": 404,
                   "msg_show": u"未找到oauth服务, 请检查该服务是否存在且属于开启状态"}
            return Response(rst, status=status.HTTP_200_OK)
        if oauth_user is None:
            rst = {"data": {"bean": None},
                   "status": 400,
                   "msg_show": u"未成功获取第三方用户信息"
                   }
            return Response(rst, status=status.HTTP_200_OK)
        try:
            service = get_oauth_instance(oauth_service.oauth_type, oauth_service, oauth_user)
        except Exception as e:
            logger.debug(e)
            rst = {"data": {"bean": None},
                   "status": 400,
                   "msg_show": u"未找到OAuth服务"
                   }
            return Response(rst, status=status.HTTP_200_OK)
        if not service.is_git_oauth():
            rst = {"data": {"bean": None},
                   "status": 400,
                   "msg_show": u"该OAuth服务不是代码仓库类型"
                   }
            return Response(rst, status=status.HTTP_200_OK)

        repo_list = []

        try:
            for data in service.get_repo_detail(full_name):
                repo_list.append(data)
            rst = {"data": {"bean": {
                "repositories": repo_list, "user_id": user_id,
                "service_id": service_id, "service_type": oauth_service.oauth_type,
                "service_name": oauth_service.name, "total": 10}}}
            return Response(rst, status=status.HTTP_200_OK)
        except Exception as e:
            logger.debug(e)
            rst = {"data": {"bean": None},
                   "status": 400,
                   "msg_show": u"Access Token 已过期"}
            return Response(rst, status=status.HTTP_200_OK)
Exemplo n.º 6
0
    def put(self, request, *args, **kwargs):
        """
        修改构建源
        ---
        """
        s_id = transaction.savepoint()
        try:
            image = request.data.get("image", None)
            cmd = request.data.get("cmd", None)
            service_source = request.data.get("service_source")
            git_url = request.data.get("git_url", None)
            code_version = request.data.get("code_version", None)
            user_name = request.data.get("user_name", None)
            password = request.data.get("password", None)
            is_oauth = request.data.get("is_oauth", False)
            user_id = request.user.user_id
            oauth_service_id = request.data.get("service_id")
            git_full_name = request.data.get("full_name")

            if not service_source:
                return Response(general_message(400, "param error", "参数错误"),
                                status=400)

            service_source_user = service_source_repo.get_service_source(
                team_id=self.service.tenant_id,
                service_id=self.service.service_id)

            if not service_source_user:
                service_source_info = {
                    "service_id": self.service.service_id,
                    "team_id": self.service.tenant_id,
                    "user_name": user_name,
                    "password": password,
                    "create_time":
                    datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                }
                service_source_repo.create_service_source(
                    **service_source_info)
            else:
                service_source_user.user_name = user_name
                service_source_user.password = password
                service_source_user.save()
            if service_source == "source_code":
                if code_version:
                    self.service.code_version = code_version
                else:
                    self.service.code_version = "master"
                if git_url:
                    if is_oauth:
                        oauth_service = oauth_repo.get_oauth_services_by_service_id(
                            service_id=oauth_service_id)
                        oauth_user = oauth_user_repo.get_user_oauth_by_user_id(
                            service_id=oauth_service_id, user_id=user_id)
                        try:
                            instance = get_oauth_instance(
                                oauth_service.oauth_type, oauth_service,
                                oauth_user)
                        except Exception as e:
                            logger.debug(e)
                            rst = {
                                "data": {
                                    "bean": None
                                },
                                "status": 400,
                                "msg_show": u"未找到OAuth服务"
                            }
                            return Response(rst, status=200)
                        if not instance.is_git_oauth():
                            rst = {
                                "data": {
                                    "bean": None
                                },
                                "status": 400,
                                "msg_show": u"该OAuth服务不是代码仓库类型"
                            }
                            return Response(rst, status=200)
                        service_code_from = "oauth_" + oauth_service.oauth_type
                        self.service.code_from = service_code_from
                        self.service.git_url = git_url
                        self.service.git_full_name = git_full_name
                        self.service.oauth_service_id = oauth_service_id
                    else:
                        self.service.git_url = git_url
                self.service.save()
                transaction.savepoint_commit(s_id)
            elif service_source == "docker_run":
                if image:
                    version = image.split(':')[-1]
                    if not version:
                        version = "latest"
                        image = image + ":" + version
                    self.service.image = image
                    self.service.version = version
                self.service.cmd = cmd
                self.service.save()
                transaction.savepoint_commit(s_id)
            result = general_message(200, "success", "修改成功")
        except Exception as e:
            logger.exception(e)
            result = error_message(e.message)
            transaction.savepoint_rollback(s_id)
        return Response(result, status=result["code"])
Exemplo n.º 7
0
    def post(self, request, *args, **kwargs):
        """
        源码创建组件
        ---
        parameters:
            - name: tenantName
              description: 租户名
              required: true
              type: string
              paramType: path
            - name: group_id
              description: 组id
              required: true
              type: string
              paramType: form
            - name: code_from
              description: 组件代码来源
              required: true
              type: string
              paramType: form
            - name: service_cname
              description: 组件名称
              required: true
              type: string
              paramType: form
            - name: git_url
              description: git地址
              required: false
              type: string
              paramType: form
            - name: git_project_id
              description: 代码ID
              required: false
              type: string
              paramType: form
            - name: code_version
              description: 代码版本
              required: false
              type: string
              paramType: form
            - name: username
              description: 私有云用户名称
              required: false
              type: string
              paramType: form
            - name: password
              description: 私有云账户密码
              required: false
              type: string
              paramType: form
            - name: server_type
              description: 仓库类型git或svn
              required: false
              type: string
              paramType: form

        """

        group_id = request.data.get("group_id", -1)
        service_code_from = request.data.get("code_from", None)
        service_cname = request.data.get("service_cname", None)
        service_code_clone_url = request.data.get("git_url", None)
        git_password = request.data.get("password", None)
        git_user_name = request.data.get("username", None)
        service_code_id = request.data.get("git_project_id", None)
        service_code_version = request.data.get("code_version", "master")
        is_oauth = request.data.get("is_oauth", False)
        check_uuid = request.data.get("check_uuid")
        event_id = request.data.get("event_id")
        server_type = request.data.get("server_type", "git")
        user_id = request.user.user_id
        oauth_service_id = request.data.get("service_id")
        git_full_name = request.data.get("full_name")
        git_service = None
        open_webhook = False
        host = os.environ.get('DEFAULT_DOMAIN', "http://" + request.get_host())

        result = {}
        if is_oauth:
            open_webhook = request.data.get("open_webhook", False)
            try:
                oauth_service = oauth_repo.get_oauth_services_by_service_id(service_id=oauth_service_id)
                oauth_user = oauth_user_repo.get_user_oauth_by_user_id(service_id=oauth_service_id, user_id=user_id)
            except Exception as e:
                logger.debug(e)
                rst = {"data": {"bean": None}, "status": 400, "msg_show": "未找到OAuth服务, 请检查该服务是否存在且属于开启状态"}
                return Response(rst, status=200)
            try:
                git_service = get_oauth_instance(oauth_service.oauth_type, oauth_service, oauth_user)
            except Exception as e:
                logger.debug(e)
                rst = {"data": {"bean": None}, "status": 400, "msg_show": "未找到OAuth服务"}
                return Response(rst, status=200)
            if not git_service.is_git_oauth():
                rst = {"data": {"bean": None}, "status": 400, "msg_show": "该OAuth服务不是代码仓库类型"}
                return Response(rst, status=200)

            service_code_from = "oauth_" + oauth_service.oauth_type
        try:
            if not service_code_clone_url:
                return Response(general_message(400, "code url is null", "仓库地址未指明"), status=400)
            if not service_code_from:
                return Response(general_message(400, "params error", "参数service_code_from未指明"), status=400)
            if not server_type:
                return Response(general_message(400, "params error", "仓库类型未指明"), status=400)
            # 创建源码组件
            if service_code_clone_url:
                service_code_clone_url = service_code_clone_url.strip()
            code, msg_show, new_service = app_service.create_source_code_app(
                self.response_region, self.tenant, self.user, service_code_from, service_cname, service_code_clone_url,
                service_code_id, service_code_version, server_type, check_uuid, event_id, oauth_service_id, git_full_name)
            if code != 200:
                return Response(general_message(code, "service create fail", msg_show), status=code)
            # 添加username,password信息
            if git_password or git_user_name:
                app_service.create_service_source_info(self.tenant, new_service, git_user_name, git_password)

            # 自动添加hook
            if open_webhook and is_oauth and not new_service.open_webhooks:
                service_webhook = service_webhooks_repo.create_service_webhooks(new_service.service_id, "code_webhooks")
                service_webhook.state = True
                service_webhook.deploy_keyword = "deploy"
                service_webhook.save()
                try:
                    git_service.create_hook(host, git_full_name, endpoint='console/webhooks/' + new_service.service_id)
                    new_service.open_webhooks = True
                except Exception as e:
                    logger.exception(e)
                    new_service.open_webhooks = False
                new_service.save()
            # 添加组件所在组

            code, msg_show = group_service.add_service_to_group(self.tenant, self.response_region, group_id,
                                                                new_service.service_id)

            if code != 200:
                logger.debug("service.create", msg_show)
            bean = new_service.to_dict()
            result = general_message(200, "success", "创建成功", bean=bean)
        except ResourceNotEnoughException as re:
            raise re
        except AccountOverdueException as re:
            logger.exception(re)
            return Response(general_message(10410, "resource is not enough", re.message), status=412)
        return Response(result, status=result["code"])
Exemplo n.º 8
0
    def check_service(self, tenant, service, is_again, user=None):
        body = dict()
        body["tenant_id"] = tenant.tenant_id
        body["source_type"] = self.__get_service_region_type(
            service.service_source)
        source_body = ""
        service_source = service_source_repo.get_service_source(
            tenant.tenant_id, service.service_id)
        user_name = ""
        password = ""
        service.service_source = self.__get_service_source(service)
        if service_source:
            user_name = service_source.user_name
            password = service_source.password
        if service.service_source == AppConstants.SOURCE_CODE:
            if service.oauth_service_id:
                try:
                    oauth_service = oauth_repo.get_oauth_services_by_service_id(
                        service.oauth_service_id)
                    oauth_user = oauth_user_repo.get_user_oauth_by_user_id(
                        service_id=service.oauth_service_id,
                        user_id=user.user_id)
                except Exception as e:
                    logger.debug(e)
                    return 400, "未找到oauth服务, 请检查该服务是否存在且属于开启状态", None
                if oauth_user is None:
                    return 400, "未成功获取第三方用户信息", None

                try:
                    instance = get_oauth_instance(oauth_service.oauth_type,
                                                  oauth_service, oauth_user)
                except Exception as e:
                    logger.debug(e)
                    return 400, "未找到OAuth服务", None
                if not instance.is_git_oauth():
                    return 400, "该OAuth服务不是代码仓库类型", None
                tenant = Tenants.objects.get(tenant_name=tenant.tenant_name)
                try:
                    service_code_clone_url = instance.get_clone_url(
                        service.git_url)
                except Exception as e:
                    logger.debug(e)
                    return 400, "Access Token 已过期", None
            else:
                service_code_clone_url = service.git_url

            sb = {
                "server_type": service.server_type,
                "repository_url": service_code_clone_url,
                "branch": service.code_version,
                "user": user_name,
                "password": password,
                "tenant_id": tenant.tenant_id
            }
            source_body = json.dumps(sb)
        elif service.service_source == AppConstants.DOCKER_RUN or service.service_source == AppConstants.DOCKER_IMAGE:
            source_body = service.docker_cmd
        elif service.service_source == AppConstants.THIRD_PARTY:
            # endpoints信息
            service_endpoints = service_endpoints_repo.get_service_endpoints_by_service_id(
                service.service_id).first()
            if service_endpoints and service_endpoints.endpoints_type == "discovery":
                source_body = service_endpoints.endpoints_info

        body["username"] = user_name
        body["password"] = password
        body["source_body"] = source_body
        res, body = region_api.service_source_check(service.service_region,
                                                    tenant.tenant_name, body)
        bean = body["bean"]
        service.check_uuid = bean["check_uuid"]
        service.check_event_id = bean["event_id"]
        # 更新创建状态
        if not is_again:
            service.create_status = "checking"
        service.save()
        bean = dict()
        bean.update(service.to_dict())
        bean.update({"user_name": user_name, "password": password})
        bean.update(self.__wrap_check_service(service))
        return 200, "success", bean
Exemplo n.º 9
0
    def post(self, request, service_id, *args, **kwargs):
        region = request.data.get("region_name")
        tenant_name = request.data.get("tenant_name", None)
        git_url = request.data.get("project_url")
        version = request.data.get("version")
        user_id = request.user.user_id
        try:
            oauth_service = oauth_repo.get_oauth_services_by_service_id(
                service_id)
            oauth_user = oauth_user_repo.get_user_oauth_by_user_id(
                service_id=service_id, user_id=user_id)
        except Exception as e:
            logger.exception(e)
            rst = {
                "data": {
                    "bean": None
                },
                "status": 404,
                "msg_show": "未找到oauth服务, 请检查该服务是否存在且属于开启状态"
            }
            return Response(rst, status=status.HTTP_200_OK)
        if oauth_user is None:
            rst = {
                "data": {
                    "bean": None
                },
                "status": 400,
                "msg_show": "未成功获取第三方用户信息"
            }
            return Response(rst, status=status.HTTP_200_OK)

        try:
            service = get_oauth_instance(oauth_service.oauth_type,
                                         oauth_service, oauth_user)
        except Exception as e:
            logger.debug(e)
            rst = {
                "data": {
                    "bean": None
                },
                "status": 400,
                "msg_show": "未找到OAuth服务"
            }
            return Response(rst, status=status.HTTP_200_OK)
        if not service.is_git_oauth():
            rst = {
                "data": {
                    "bean": None
                },
                "status": 400,
                "msg_show": "该OAuth服务不是代码仓库类型"
            }
            return Response(rst, status=status.HTTP_200_OK)
        tenant = Tenants.objects.get(tenant_name=tenant_name)
        service_code_version = version
        try:
            service_code_clone_url = service.get_clone_url(git_url)
        except Exception as e:
            logger.debug(e)
            rst = {
                "data": {
                    "bean": None
                },
                "status": 400,
                "msg_show": "Access Token 已过期"
            }
            return Response(rst, status=status.HTTP_200_OK)
        sb = {
            "server_type": 'git',
            "repository_url": service_code_clone_url,
            "branch": service_code_version,
            "tenant_id": tenant.tenant_id
        }

        source_body = json.dumps(sb)
        body = dict()
        body["tenant_id"] = tenant.tenant_id
        body["source_type"] = "sourcecode"
        body["username"] = None
        body["password"] = None
        body["source_body"] = source_body
        try:
            res, body = region_api.service_source_check(
                region, tenant.tenant_name, body)
            return Response({"data": {
                "data": body
            }},
                            status=status.HTTP_200_OK)
        except (region_api.CallApiError, ServiceHandleException) as e:
            logger.debug(e)
            raise ServiceHandleException(msg="region error",
                                         msg_show="访问数据中心失败")
Exemplo n.º 10
0
    def post(self, request, *args, **kwargs):
        login_user = request.user
        code = request.data.get("code")
        service_id = request.data.get("service_id")
        try:
            oauth_service = oauth_repo.get_oauth_services_by_service_id(
                service_id)
        except Exception as e:
            logger.debug(e)
            rst = {
                "data": {
                    "bean": None
                },
                "status": 404,
                "msg_show": "未找到oauth服务, 请检查该服务是否存在且属于开启状态"
            }
            return Response(rst, status=status.HTTP_200_OK)
        try:
            api = get_oauth_instance(oauth_service.oauth_type, oauth_service,
                                     None)
        except NoSupportOAuthType as e:
            logger.debug(e)
            rst = {
                "data": {
                    "bean": None
                },
                "status": 404,
                "msg_show": "未找到oauth服务"
            }
            return Response(rst, status=status.HTTP_200_OK)
        try:
            user, access_token, refresh_token = api.get_user_info(code=code)
        except Exception as e:
            logger.exception(e)
            rst = {
                "data": {
                    "bean": None
                },
                "status": 404,
                "msg_show": e.message
            }
            return Response(rst, status=status.HTTP_200_OK)

        user_name = user.name
        user_id = str(user.id)
        user_email = user.email
        authenticated_user = oauth_user_repo.user_oauth_exists(
            service_id=service_id, oauth_user_id=user_id)
        link_user = oauth_user_repo.get_user_oauth_by_user_id(
            service_id=service_id, user_id=login_user.user_id)
        if link_user is not None and link_user.oauth_user_id != user_id:
            rst = {
                "data": {
                    "bean": None
                },
                "status": 400,
                "msg_show": "该用户已绑定其他账号"
            }
            return Response(rst, status=status.HTTP_200_OK)

        if authenticated_user is not None and authenticated_user.user_id is None:
            authenticated_user.oauth_user_id = user_id
            authenticated_user.oauth_user_name = user_name
            authenticated_user.oauth_user_email = user_email
            authenticated_user.access_token = access_token
            authenticated_user.refresh_token = refresh_token
            authenticated_user.code = code
            authenticated_user.is_authenticated = True
            authenticated_user.is_expired = True
            authenticated_user.user_id = login_user.user_id
            authenticated_user.save()
            return Response(None, status=status.HTTP_200_OK)
        else:
            oauth_user_repo.save_oauth(
                oauth_user_id=user_id,
                oauth_user_name=user_name,
                oauth_user_email=user_email,
                user_id=login_user.user_id,
                code=code,
                service_id=service_id,
                access_token=access_token,
                refresh_token=refresh_token,
                is_authenticated=True,
                is_expired=False,
            )
            rst = {"data": {"bean": None}, "status": 200, "msg_show": "绑定成功"}
            return Response(rst, status=status.HTTP_200_OK)
Exemplo n.º 11
0
 def get(self, request, *args, **kwargs):
     code = request.GET.get("code")
     service_id = request.GET.get("service_id")
     domain = request.GET.get("domain")
     home_split_url = None
     try:
         oauth_service = oauth_repo.get_oauth_services_by_service_id(
             service_id)
         if oauth_service.oauth_type == "enterprisecenter" and domain:
             home_split_url = urlsplit(oauth_service.home_url)
             oauth_service.proxy_home_url = home_split_url.scheme + "://" + domain + home_split_url.path
     except Exception as e:
         logger.debug(e)
         rst = {
             "data": {
                 "bean": None
             },
             "status": 404,
             "msg_show": "未找到oauth服务, 请检查该服务是否存在且属于开启状态"
         }
         return Response(rst, status=status.HTTP_200_OK)
     try:
         api = get_oauth_instance(oauth_service.oauth_type, oauth_service,
                                  None)
     except NoSupportOAuthType as e:
         logger.debug(e)
         rst = {
             "data": {
                 "bean": None
             },
             "status": 404,
             "msg_show": "未找到oauth服务"
         }
         return Response(rst, status=status.HTTP_200_OK)
     try:
         oauth_user, access_token, refresh_token = api.get_user_info(
             code=code)
     except Exception as e:
         logger.exception(e)
         rst = {
             "data": {
                 "bean": None
             },
             "status": 404,
             "msg_show": e.message
         }
         return Response(rst, status=status.HTTP_200_OK)
     if api.is_communication_oauth():
         logger.debug(oauth_user.enterprise_domain)
         logger.debug(domain.split(".")[0])
         logger.debug(home_split_url.netloc.split("."))
         if oauth_user.enterprise_domain != domain.split(".")[0] and \
                 domain.split(".")[0] != home_split_url.netloc.split(".")[0]:
             raise ServiceHandleException(msg="Domain Inconsistent",
                                          msg_show="登录失败",
                                          status_code=401,
                                          error_code=10405)
         client_ip = request.META.get("REMOTE_ADDR", None)
         oauth_user.client_ip = client_ip
         oauth_sev_user_service.get_or_create_user_and_enterprise(
             oauth_user)
     return oauth_sev_user_service.set_oauth_user_relation(
         api, oauth_service, oauth_user, access_token, refresh_token, code)
Exemplo n.º 12
0
    def get(self, request, *args, **kwargs):
        code = request.GET.get("code")
        service_id = request.GET.get("service_id")
        try:
            oauth_service = oauth_repo.get_oauth_services_by_service_id(
                service_id)
        except Exception as e:
            logger.debug(e)
            rst = {
                "data": {
                    "bean": None
                },
                "status": 404,
                "msg_show": u"未找到oauth服务, 请检查该服务是否存在且属于开启状态"
            }
            return Response(rst, status=status.HTTP_200_OK)
        try:
            api = get_oauth_instance(oauth_service.oauth_type, oauth_service,
                                     None)
        except NoSupportOAuthType as e:
            logger.debug(e)
            rst = {
                "data": {
                    "bean": None
                },
                "status": 404,
                "msg_show": u"未找到oauth服务"
            }
            return Response(rst, status=status.HTTP_200_OK)
        try:
            user, access_token, refresh_token = api.get_user_info(code=code)
        except Exception as e:
            logger.debug(e.message)
            rst = {
                "data": {
                    "bean": None
                },
                "status": 404,
                "msg_show": e.message
            }
            return Response(rst, status=status.HTTP_200_OK)
        user_name = user.name
        user_id = str(user.id)
        user_email = user.email
        authenticated_user = oauth_user_repo.user_oauth_exists(
            service_id=service_id, oauth_user_id=user_id)

        if authenticated_user is not None:
            authenticated_user.oauth_user_id = user_id
            authenticated_user.oauth_user_name = user_name
            authenticated_user.oauth_user_email = user_email
            authenticated_user.access_token = access_token
            authenticated_user.refresh_token = refresh_token
            authenticated_user.code = code
            authenticated_user.save()
            if authenticated_user.user_id is not None:
                login_user = user_repo.get_by_user_id(
                    authenticated_user.user_id)
                payload = jwt_payload_handler(login_user)
                token = jwt_encode_handler(payload)
                response = Response({"data": {
                    "bean": {
                        "token": token
                    }
                }},
                                    status=status.HTTP_200_OK)
                if api_settings.JWT_AUTH_COOKIE:
                    expiration = (datetime.datetime.now() +
                                  api_settings.JWT_EXPIRATION_DELTA)
                    response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                        token,
                                        expires=expiration,
                                        httponly=True)
                return response

            else:
                rst = {
                    "oauth_user_name": user_name,
                    "oauth_user_id": user_id,
                    "oauth_user_email": user_email,
                    "service_id": authenticated_user.service_id,
                    "oauth_type": oauth_service.oauth_type,
                    "is_authenticated": authenticated_user.is_authenticated,
                    "code": code,
                }
                msg = "user is not authenticated"
                return Response(
                    {"data": {
                        "bean": {
                            "result": rst,
                            "msg": msg
                        }
                    }},
                    status=status.HTTP_200_OK)
        else:
            usr = oauth_user_repo.save_oauth(
                oauth_user_id=user_id,
                oauth_user_name=user_name,
                oauth_user_email=user_email,
                code=code,
                service_id=service_id,
                access_token=access_token,
                refresh_token=refresh_token,
                is_authenticated=True,
                is_expired=False,
            )
            rst = {
                "oauth_user_name": usr.oauth_user_name,
                "oauth_user_id": usr.oauth_user_id,
                "oauth_user_email": usr.oauth_user_email,
                "service_id": usr.service_id,
                "oauth_type": oauth_service.oauth_type,
                "is_authenticated": usr.is_authenticated,
                "code": code,
            }
            msg = "user is not authenticated"
            return Response({"data": {
                "bean": {
                    "result": rst,
                    "msg": msg
                }
            }},
                            status=status.HTTP_200_OK)
Exemplo n.º 13
0
 def get(self, request, *args, **kwargs):
     code = request.GET.get("code")
     service_id = request.GET.get("service_id")
     service = oauth_repo.get_oauth_services_by_service_id(service_id)
     path = "/#/oauth/callback?service_id={}&code={}"
     return HttpResponseRedirect(path.format(service.ID, code))