Пример #1
0
    def validate(self, attrs):
        password = attrs.get("password")

        user_obj = Users.objects.filter(
            Q(phone=attrs.get("nick_name")) | Q(email=attrs.get("nick_name"))
            | Q(nick_name=attrs.get("nick_name"))).first()

        if user_obj is not None:
            credentials = {
                'username': user_obj.nick_name,
                'password': password
            }
            if all(credentials.values()):
                user = authenticate(**credentials)
                if user:
                    if not user.is_active:
                        msg = _('用户帐户被禁用.')
                        raise serializers.ValidationError(msg)

                    payload = jwt_payload_handler(user)

                    return {'token': jwt_encode_handler(payload), 'user': user}
                else:
                    msg = _('无法使用提供的凭证登录.')
                    raise serializers.ValidationError(msg)

            else:
                msg = _('用户名或密码不能为空.')
                msg = msg.format(username_field=self.username_field)
                raise serializers.ValidationError(msg)

        else:
            msg = _('账户邮箱/用户名不存在')
            raise serializers.ValidationError(msg)
Пример #2
0
    def post(self, request, *args, **kwargs):
        AccessToken = request.POST.get('AccessToken', None)
        if AccessToken is None:
            return JsonResponse({
                "ok": False,
                "info": "need AccessToken field"
            },
                                status=400)

        remote_user = self.get_remote_user(AccessToken)
        if remote_user is None:
            return JsonResponse({"ok": False, "info": "用户验证失败"}, status=403)

        if isinstance(request.user, AnonymousUser):
            pass
        else:
            user = request.user
            if user.email == remote_user.UserEmail:
                if user.is_active:
                    return self.redirect_view()
                else:
                    return self.redirect_to(
                        '/partners/ucloud/update_userinfo/')
            else:
                logout(request)

        try:
            local_user = Users.objects.get(email=remote_user.UserEmail)
            if local_user.origion == 'ucloud':
                user = authenticate(username=local_user.email, source='ucloud')
                login(request, user)
                if local_user.is_active:
                    return self.redirect_view(request)
                else:
                    return self.redirect_to(
                        '/partners/ucloud/update_userinfo/')
            else:
                info = "user from ucloud confict by email %s" % remote_user.UserEmail
                logger.info("partners.auth_ucloud", info)
                return JsonResponse({"ok": False, "info": info}, status=409)
        except Users.DoesNotExist:
            default_nick_name = u'ucloud_{0}'.format(remote_user.UserId * 3 +
                                                     1152)

            try:
                new_user = Users.objects.create(nick_name=default_nick_name,
                                                email=remote_user.UserEmail,
                                                phone=remote_user.UserPhone,
                                                origion='ucloud',
                                                is_active=False,
                                                password='******')
                user = authenticate(username=new_user.email, source='ucloud')
                login(request, user)
                return self.redirect_to('/partners/ucloud/update_userinfo/')
            except Exception, e:
                logger.error("partners.auth_ucloud", e)
                return JsonResponse({
                    "ok": False,
                    "info": "server error"
                },
                                    status=500)
Пример #3
0
 def post(self, request):
     """
     用户登录接口
     ---
     parameters:
         - name: nick_name
           description: 用户名
           required: true
           type: string
           paramType: form
         - name: password
           description: 密码
           required: true
           type: string
           paramType: form
     """
     user_name = request.POST.get("nick_name", None)
     raw_passwd = request.POST.get("password", None)
     try:
         if not user_name or not raw_passwd:
             code = 405
             result = general_message(code, "username is missing", "请填写用户名")
             return Response(result, status=code)
         elif not raw_passwd:
             code = 405
             result = general_message(code, "password is missing", "请填写密码")
             return Response(result, status=code)
         user, msg, code = user_svc.is_exist(user_name, raw_passwd)
         if not user:
             code = 400
             result = general_message(code, "authorization fail ", msg)
             return Response(result, status=code)
         else:
             u = authenticate(username=user_name, password=raw_passwd)
             http_client = HttpClient()
             url = "http://" + request.get_host(
             ) + '/console/api-token-auth'
             default_headers = {
                 'Connection': 'keep-alive',
                 'Content-Type': 'application/json'
             }
             data = {"nick_name": user_name, "password": raw_passwd}
             res, body = http_client._post(url, default_headers,
                                           json.dumps(data))
             if res.get("status", 400) != 200:
                 code = 400
                 result = general_message(code, "login failed", "登录失败")
                 return Response(result, status=code)
             logger.debug("res {0} body {1}".format(res, body))
             token = body.get("token", "")
             data = {'token': token}
             login(request, u)
             code = 200
             result = general_message(code,
                                      "login success",
                                      "登录成功",
                                      bean=data)
     except Exception as e:
         logger.exception(e)
         code = 500
         result = error_message(e.message)
     return Response(result, status=code)
Пример #4
0
    def get(self, request, *args, **kwargs):
        # 获取sso的user_id
        sso_user_id = request.COOKIES.get('uid')
        sso_user_token = request.COOKIES.get('token')

        logger.debug('cookies.sso_user_id:{}'.format(sso_user_id))
        logger.debug('cookies.sso_user_token:{}'.format(sso_user_token))

        if not sso_user_id or not sso_user_token:
            logger.error('cookies uid or token not specified!')
            return self.redirect_to("/login")

        if sso_user_id == 'null' or sso_user_token == 'null':
            logger.error('bad uid or token, value is null!')
            return self.redirect_to("/login")

        api = GoodRainSSOApi(sso_user_id, sso_user_token)
        if not api.auth_sso_user_token():
            logger.error('Illegal user token!')
            return self.redirect_to("/login")

        # 同步sso_id所代表的企业信息,没有则创建
        try:
            user = Users.objects.get(sso_user_id=sso_user_id)
            if user.sso_user_token != sso_user_token:
                user.sso_user_token = sso_user_token
                user.save()
        except Users.DoesNotExist:
            logger.debug('query user with sso_user_id does not existed, created!')
            sso_user = api.get_sso_user_info()
            logger.debug(sso_user)
            try:
                enterprise = TenantEnterprise.objects.get(enterprise_id=sso_user.eid)
            except TenantEnterprise.DoesNotExist:
                enterprise = TenantEnterprise()
                enterprise.enterprise_id = sso_user.eid
                enterprise.enterprise_name = sso_user.company
                enterprise.enterprise_alias = sso_user.company
                enterprise.is_active = 1
                enterprise.save()
                logger.info(
                    'create enterprise[{0}] with name {1}'.format(enterprise.enterprise_id,
                                                                  enterprise.enterprise_name))

            user = Users.objects.create(nick_name=sso_user.name,
                                        email=sso_user.email or '',
                                        phone=sso_user.mobile or '',
                                        password=sso_user.pwd or '',
                                        sso_user_id=sso_user.uid,
                                        enterprise_id=sso_user.eid,
                                        sso_user_token=sso_user_token,
                                        is_active=False,
                                        rf='sso')
            logger.info(
                'create user[{0}] with name [{1}] from [{2}] use sso_id [{3}]'.format(user.user_id, user.nick_name,
                                                                                      user.rf,
                                                                                      user.sso_user_id))
            monitor_hook.registerMonitor(user, 'register')

        if not user.is_active:
            tenant = enterprise_svc.create_and_init_tenant(user.user_id, enterprise_id=user.enterprise_id)
        else:
            tenant = user_svc.get_default_tenant_by_user(user.user_id)
        logger.info(tenant.to_dict())

        # create gitlab user
        if user.email is not None and user.email != "":
            codeRepositoriesService.createUser(user, user.email, user.password, user.nick_name, user.nick_name)

        # SSO用户登录
        user = authenticate(user_id=user.user_id, sso_user_id=user.sso_user_id)
        jwtlogin(request, user)
        self.user = request.user

        next_url = request.GET.get('next')
        if next_url:
            return self.redirect_to(next_url)
        return self.redirect_to('/apps/{0}/'.format(tenant.tenant_name))
Пример #5
0
    def get(self, request, *args, **kwargs):
        import datetime
        # 获取cookie中的csrf
        csrftoken = request.COOKIES.get('csrftoken')
        if csrftoken is None:
            csrftoken = "csrf"
        # 获取statue
        state = request.GET.get("state")
        # 解码toke, type
        logger.debug("account.wechat", state)
        logger.debug("account.wechat",
                     "is_weixin:{0}".format(str(is_weixin(request))))
        # 查询数据库
        err_url = settings.WECHAT_CALLBACK.get("index")
        try:
            wechat_state = WeChatState.objects.get(pk=state)
        except Exception as e:
            logger.exception("account.wechat", e)
            logger.error("account.wechat",
                         "wechatstate is missing,id={0}".format(state))
            return self.redirect_to(err_url)
        cry_state = wechat_state.state

        state_array = AuthCode.decode(str(cry_state),
                                      'we_chat_login').split(',')
        oldcsrftoken = state_array[0]
        origin = state_array[1]
        next_url = state_array[2]
        config = state_array[3]
        origin_url = None
        if len(state_array) == 5:
            origin_url = state_array[4]
        logger.debug("account.wechat", oldcsrftoken)
        logger.debug("account.wechat", origin)
        logger.debug("account.wechat", next_url)
        logger.debug("account.wechat", config)
        logger.debug("account.wechat", origin_url)

        if csrftoken != oldcsrftoken:
            return self.redirect_to(err_url)
        # 获取的code
        code = request.GET.get("code")
        logger.info(code)
        if code is None:
            return self.redirect_to(err_url)
        # 根据code获取access_token
        wechat_config = WeChatConfig.objects.get(config=config)
        access_token, open_id = OpenWeChatAPI.access_token_oauth2_static(
            wechat_config.app_id, wechat_config.app_secret, code)
        logger.info(access_token)
        if access_token is None:
            # 登录失败,跳转到失败页面
            return self.redirect_to(err_url)
        # 检查用户的open_id是否已经存在
        need_new = False
        wechat_user = None
        try:
            wechat_user = WeChatUser.objects.get(open_id=open_id)
        except WeChatUser.DoesNotExist:
            logger.warning(
                "account.wechat",
                "open_id is first to access console. now regist...")
            need_new = True

        # 添加wechatuser
        if need_new:
            jsondata = OpenWeChatAPI.query_userinfo_static(
                open_id, access_token)
            nick_name = jsondata.get("nickname")
            if nick_name:
                nick_name = nick_name.encode("utf-8")
            wechat_user = WeChatUser(open_id=jsondata.get("openid"),
                                     nick_name=nick_name,
                                     union_id=jsondata.get("unionid"),
                                     sex=jsondata.get("sex"),
                                     city=jsondata.get("city"),
                                     province=jsondata.get("province"),
                                     country=jsondata.get("country"),
                                     headimgurl=jsondata.get("headimgurl"),
                                     config=config)
            wechat_user.save()

        # 根据微信的union_id判断用户是否已经注册
        need_new = False
        user = None
        try:
            user = Users.objects.get(union_id=wechat_user.union_id)
        except Users.DoesNotExist:
            logger.warning(
                "account.wechat",
                "union id is first to access console. now create user...")
            need_new = True
        # 用户表中不存在对应用户,判断是否已经解绑
        if need_new:
            try:
                binding = WeChatUnBind.objects.get(
                    union_id=wechat_user.union_id, status=0)
                user = Users.objects.get(pk=binding.user_id)
                user.union_id = wechat_user.union_id
                user.save()
                need_new = False
            except WeChatUnBind.DoesNotExist:
                pass

        # 创建租户
        if need_new:
            union_id = wechat_user.union_id
            tmp_union_id = md5fun(union_id)
            begin_index = len(tmp_union_id) - 8
            tenant_name = tmp_union_id[begin_index:]
            tenant_name = tenant_name.replace("_", "-").lower()
            email = tenant_name + "@wechat.com"
            logger.debug(
                "account.wechat",
                "new wx regist user.email:{0} tenant_name:{1}".format(
                    email, tenant_name))
            # 创建用户,邮箱为openid后8位@wechat.comemail=email,
            # 统计当前wx数量
            count = Users.objects.filter(rf="open_wx").count()
            count += 1989
            nick_name = "wxgd0" + str(count)
            user = Users(nick_name=nick_name,
                         phone="",
                         client_ip=get_client_ip(request),
                         rf="open_wx",
                         status=2,
                         union_id=union_id)
            user.set_password("wechatpwd")
            user.save()
            monitorhook.registerMonitor(user, 'register')
            # 创建租户,默认为alish
            region = RegionInfo.register_choices()[0][0]

            # add by tanm
            regions = [region]
            enterprise_svc.create_and_init_tenant(user.user_id, tenant_name,
                                                  regions, user.enterprise_id)

            # create gitlab user
            if user.email is not None and user.email != "":
                codeRepositoriesService.createUser(user, email, password,
                                                   nick_name, nick_name)
        logger.info(user)
        if user is None:
            logger.error("account.wechat", "微信用户登录失败!")
            return self.redirect_to(err_url)
        # 微信用户登录
        user = authenticate(union_id=user.union_id)
        login(request, user)
        self.user = request.user

        # 回跳到云市
        if next_url is not None \
                and next_url != "" \
                and next_url != "none" \
                and next_url != "None":
            if origin == "app":
                logger.debug("account.wechat",
                             "now return to cloud market login..")
                if origin_url is None or origin_url == "redirect_url" or origin_url == "":
                    origin_url = settings.APP_SERVICE_API.get("url")
                if not origin_url.startswith("http://"):
                    origin_url = "http://" + origin_url
                # 返回参数
                payload = {
                    "nick_name": user.nick_name,
                    "user_id": str(user.user_id),
                    "next_url": next_url,
                    "action": "register" if need_new else "login"
                }
                if wechat_user is not None:
                    payload["wechat_name"] = wechat_user.nick_name
                ticket = AuthCode.encode(json.dumps(payload), "goodrain")
                next_url = "{0}/login/{1}/success?ticket={2}".format(
                    origin_url, sn.instance.cloud_assistant, ticket)
                # next_url = settings.APP_SERVICE_API.get("url") + '/login/goodrain/success?ticket=' + ticket
                logger.debug("account.wechat", next_url)
            return redirect(next_url)

        return self.redirect_view()
Пример #6
0
    def post(self, request, *args, **kwargs):
        """注册管理员"""
        admin_form = AdminForm(request.POST)
        import datetime
        if admin_form.is_valid():
            email = request.POST.get('email')
            nick_name = request.POST.get('nick_name')
            password = request.POST.get('password')
            password_repeat = request.POST.get('password_repeat')
            region = request.POST.get('machine_region')
            if region is None or region == "" or region == "1":
                region = RegionInfo.register_choices()[0][0]

            # 企业名称
            enter_alias = request.POST.get('enter_alias', '')

            # 租户信息
            tenant_name = nick_name
            # 清理之前所有的租户
            tenant_count = Tenants.objects.all().count()
            if tenant_count > 0:
                logger.error("account.register", "租户已存在,请先清理租户!")
                context = self.get_context()
                admin_form.add_error("", "租户已存在,请先清理租户!")
                context["form"] = admin_form
                return TemplateResponse(request, 'www/wizard/admin.html',
                                        context)
                # Tenants.objects.all().delete()

            regions = regionConfig.regions()
            if region not in [r['name'] for r in regions]:
                logger.error("account.register", "配置文件中未找到待初始化的数据中心配置信息!")
                context = self.get_context()
                admin_form.add_error("", "配置文件中未找到待初始化的数据中心配置信息!")
                context["form"] = admin_form
                return TemplateResponse(request, 'www/wizard/admin.html',
                                        context)

            # 添加本地企业信息
            enterprise = enterprise_svc.create_enterprise(
                enterprise_alias=enter_alias)

            # 添加用户
            user = Users(email=email,
                         nick_name=nick_name,
                         client_ip=get_client_ip(request),
                         rf='admin',
                         is_active=False,
                         enterprise_id=enterprise.enterprise_id)
            user.set_password(password)
            user.save()
            monitorhook.registerMonitor(user, 'register')
            # 添加django用户
            tmpname = nick_name + "_token"
            oauth_user = OAuthUser.objects.create(username=tmpname)
            oauth_user.set_password(password)
            oauth_user.is_staff = True
            oauth_user.save()

            # 初始化企业与团队信息
            region_names = [region]
            enterprise_svc.create_and_init_tenant(user.user_id, tenant_name,
                                                  region_names,
                                                  enterprise.enterprise_id)

            # 第一个用户默认作为云帮管理员
            superadmin = SuperAdminUser()
            superadmin.email = email
            superadmin.save()

            # create gitlab user
            if user.email is not None and user.email != "":
                codeRepositoriesService.createUser(user, email, password,
                                                   nick_name, nick_name)

            # 登录系统
            user = authenticate(username=nick_name, password=password)
            login(request, user)
            self.user = request.user

            # 发送数据到app进行注册
            data = {
                "username": nick_name,
                "email": email,
                "password": password,
            }
            json_data = json.dumps(data)

            try:
                # for num in range(0, 3):
                appClient.timeout = 5
                res, body = appClient.post_admin_info(json_data)
                if res is None:
                    logger.error("account.register", "register app failed!")
                else:
                    logger.debug("account.register", res)
                    logger.debug("account.register", body)
                    if res.status == 200:
                        logger.debug("account.register",
                                     "register app success!")
                    else:
                        logger.error("account.register",
                                     "register app failed!")
            except Exception as e:
                logger.exception("account.register", e)

            url = '/apps/{0}'.format(tenant_name)
            if settings.MODULES["Package_Show"]:
                selected_pay_level = ""
                pl = request.GET.get("pl", "")
                region_levels = pl.split(":")
                if len(region_levels) == 2:
                    selected_pay_level = region_levels[1]
                url = '/payed/{0}/select?selected={1}'.format(
                    tenant_name, selected_pay_level)
            logger.debug(url)
            return self.redirect_to(url)
        else:
            context = self.get_context()
            context["form"] = admin_form
            return TemplateResponse(request, 'www/wizard/admin.html', context)