Esempio n. 1
0
    def __init__(self, *args, **kwargs):
        super(AdminForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_tag = False
        # 获取region
        init_region = RegionInfo.register_choices()[0][0]

        self.helper.layout = Layout(
            Div(Field('enter_alias',
                      css_class="form-control",
                      placeholder=u"企业名称"),
                Field('nick_name',
                      css_class="form-control",
                      placeholder=u"用户名(英文)"),
                Field('email', css_class="form-control", placeholder=u"管理员邮箱"),
                Hidden('machine_region', value=init_region),
                Field('password',
                      css_class="form-control",
                      placeholder=u"请输入至少8位数密码"),
                Field('password_repeat',
                      css_class="form-control",
                      placeholder=u"请再输入一次密码"),
                HTML(
                    """<div class="form-group" style="text-align:left;"><a href="http://doc.goodrain.com/cloudbang-agreement/201656" target="_blank">《云帮企业版用户服务协议》</a></div>"""
                ),
                FormActions(
                    Submit('register',
                           u'同意协议,创建账号',
                           css_class='btn btn-lg btn-success btn-block')),
                css_class="login-wrap"))
        self.helper.form_id = 'form-normal-reg'
        self.helper.form_class = 'form-horizontal'
Esempio n. 2
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()
Esempio n. 3
0
    def __init__(self, *args, **kwargs):
        init_phone = ""
        init_email = ""
        init_tenant = ""
        init_region = ""
        selected_region = ""
        next_url = None
        origin = None
        prefix_url = ""
        if len(kwargs) > 0:
            if kwargs.get("initial") is not None:
                initalObj = kwargs.get("initial")
                init_phone = initalObj["phone"]
                init_email = initalObj["email"]
                init_tenant = initalObj["tenant"]
                init_region = initalObj["region"]
            if kwargs.get("region_level") is not None:
                selected_region = kwargs["region_level"]["region"]
                kwargs.pop("region_level")
            if kwargs.get("next_url") is not None:
                next_url = kwargs["next_url"]
                prefix_url += "&next={0}".format(next_url)
                kwargs.pop("next_url")
            if kwargs.get("origin") is not None:
                origin = kwargs["origin"]
                prefix_url += "&origin={0}".format(origin)
                kwargs.pop("origin")
        if len(prefix_url) > 1:
            prefix_url = "?" + prefix_url[1:]
        if len(args) > 0:
            if type(args) is tuple:
                if args[0].get("initial") is not None:
                    initalObj = args[0]["initial"]
                    if type(initalObj) is list:
                        initalObj = initalObj(0)
                    init_phone = initalObj["phone"]
                    init_email = initalObj["email"]
                    init_tenant = initalObj["tenant"]
                    init_region = initalObj["region"]
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_tag = False

        text_phone = "手机号"
        text_email = "请输入邮箱地址"
        text_tenant = "团队域名"
        if init_phone is not None and init_phone != "":
            self.fields['phone'].widget.attrs['readonly'] = True
            text_phone = init_phone
        if init_email is not None and init_email != "":
            self.fields['email'].widget.attrs['readonly'] = True
            text_email = init_email
        if init_tenant is not None and init_tenant != "":
            self.fields['tenant'].widget.attrs['readonly'] = True
            text_tenant = init_tenant
        if init_region is not None and init_region != "":
            self.fields['machine_region'].initial = init_region
            self.fields['machine_region'].widget.attrs['readonly'] = True
        if selected_region is not None and selected_region != "":
            self.fields['machine_region'].initial = selected_region

        init_region = RegionInfo.register_choices()[0][0]
        # 对于社区版注册表单进行处理
        is_private = sn.instance.is_private()
        tenant_name = None
        if is_private:
            tenant_num = Tenants.objects.count()
            if tenant_num == 1:
                tenant_list = Tenants.objects.all()
                tenant = tenant_list[0]
                tenant_name = tenant.tenant_name

        # if settings.MODULES["Sms_Check"]:
        if settings.MODULES["WeChat_Module"]:
            self.helper.layout = Layout(
                Div(
                    Field('tenant',
                          "",
                          placeholder='请输入团队名(可使用小写英文字母、数字、下划线及中划线)',
                          css_class="form-control") if tenant_name is None else
                    Field('tenant',
                          "",
                          placeholder='请输入团队名(可使用小写英文字母、数字、下划线及中划线)',
                          css_class="form-control",
                          readonly="readonly",
                          value=tenant_name),
                    Field('nick_name',
                          css_class="form-control",
                          placeholder='请输入用户名(可使用小写英文字母、数字、下划线及中划线)'),
                    Field('email',
                          css_class="form-control",
                          placeholder='请输入邮箱(选填)'),
                    HTML("<hr/>"),
                    # 默认为ali-sh
                    Hidden('machine_region', value=init_region),
                    Hidden('next', value=next_url),
                    Hidden('origin', value=origin),
                    Field('password',
                          css_class="form-control",
                          placeholder='请设置密码,至少包含8位字符'),
                    Field('password_repeat',
                          css_class="form-control",
                          placeholder='请再输入一次密码'),
                    Field('phone',
                          css_class="form-control",
                          placeholder='请输入手机号'),
                    AppendedText(
                        'captcha_code',
                        '<img id="captcha_code" src="/captcha" /> <a href="javascript:void(0)" onclick="refresh();">看不清,换一张</a>  ',
                        css_class='input-xlarge',
                        placeholder='图片验证码'),
                    AppendedText(
                        'phone_code',
                        '<a href="javascript:void(0)" id="PhoneCodeBtn" onclick="getPhoneCode();">点击发送验证码</a>  ',
                        css_class='input-xlarge',
                        placeholder='手机验证码'),
                    HTML(
                        """<div class="linkfw text-center">点击注册表示你已阅读并同意《<a href="http://www.goodrain.com/goodrainlaws.html" target="_blank">云帮服务条款</a>》</div>"""
                    ),
                    FormActions(
                        Submit('register',
                               u'注册',
                               css_class='btn btn-lg btn-success btn-block')),
                    HTML("""<p class="text-center">或使用以下账号注册</p>"""),
                    HTML(
                        """<a href="/wechat/login{0}" class="weixin"><img src="static/www/images/weixin.png">微信</a>"""
                        .format(prefix_url)),
                    HTML(
                        """<div class="linkregister text-center">直接<a href="/login{0}">登录</a></div>"""
                        .format(prefix_url)),
                    # HTML("""<a href="http://www.goodrain.com/" class="linkgood text-center">goodrain.com</a>"""),
                    css_class="login-wrap"))
        else:
            self.helper.layout = Layout(
                Div(
                    Field('tenant',
                          "",
                          placeholder='请输入团队名(可使用小写英文字母、数字、下划线及中划线)',
                          css_class="form-control") if tenant_name is None else
                    Field('tenant',
                          "",
                          placeholder='请输入团队名(可使用小写英文字母、数字、下划线及中划线)',
                          css_class="form-control",
                          readonly="readonly",
                          value=tenant_name),
                    Field('nick_name',
                          css_class="form-control",
                          placeholder='请输入用户名(可使用小写英文字母、数字、下划线及中划线)'),
                    Field('email',
                          css_class="form-control",
                          placeholder='请输入邮箱(选填)'),
                    HTML("<hr/>"),
                    Hidden('machine_region', value=init_region),
                    Hidden('next', value=next_url),
                    Hidden('origin', value=origin),
                    Field('password',
                          css_class="form-control",
                          placeholder='请设置密码,至少包含8位字符'),
                    Field('password_repeat',
                          css_class="form-control",
                          placeholder='请再输入一次密码'),
                    Field('phone',
                          css_class="form-control",
                          placeholder='请输入手机号'),
                    AppendedText(
                        'captcha_code',
                        '<img id="captcha_code" src="/captcha" /> <a href="javascript:void(0)" onclick="refresh();">看不清,换一张</a>  ',
                        css_class='input-xlarge',
                        placeholder='验证码'),
                    AppendedText(
                        'phone_code',
                        '<a href="javascript:void(0)" id="PhoneCodeBtn" onclick="getPhoneCode();">点击发送验证码</a>  ',
                        css_class='input-xlarge',
                        placeholder='手机验证码'),
                    HTML(
                        """<div class="linkfw text-center">点击注册表示你已阅读并同意《<a href="http://www.goodrain.com/goodrainlaws.html" target="_blank">云帮服务条款</a>》</div>"""
                    ),
                    FormActions(
                        Submit('register',
                               u'注册',
                               css_class='btn btn-lg btn-success btn-block')),
                    HTML(
                        """<div class="linkregister text-center">直接<a href="/login{0}">登录</a></div>"""
                        .format(prefix_url)),
                    # HTML("""<a href="http://www.goodrain.com/" class="linkgood text-center">goodrain.com</a>"""),
                    css_class="login-wrap"))
        self.helper.form_id = 'form-normal-reg'
        self.helper.form_class = 'form-horizontal'
Esempio n. 4
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)
Esempio n. 5
0
class RegisterForm(forms.Form):
    '''
    邀请注册表单
    '''
    email = forms.EmailField(
        required=False,
        max_length=32,
        label="",
        # ajax_check=True,
        # widget=widgets.EmailInput(attrs={"data-remote-error": u"邮件地址已存在"})
    )
    tenant = forms.CharField(
        required=True,
        max_length=40,
        label="",
        validators=[is_standard_word_extend, is_sensitive],
        # min_length=3, ajax_check=True, pattern=standard_regex_string,
        # widget=widgets.TextInput(attrs={"data-remote-error": u"已存在"})
    )
    nick_name = forms.CharField(
        required=True,
        max_length=24,
        label="",
        validators=[is_standard_word, is_sensitive],
        # pattern=standard_regex_string, ajax_check=True,
        # widget=widgets.TextInput(attrs={"data-remote-error": u"昵称已存在"})
    )
    password = forms.CharField(required=True,
                               label='',
                               widget=forms.PasswordInput,
                               validators=[password_len])
    password_repeat = forms.CharField(required=True,
                                      label='',
                                      widget=forms.PasswordInput,
                                      validators=[password_len])
    phone = forms.CharField(required=True, label='', validators=[is_phone])

    if settings.MODULES["Sms_Check"]:
        phone_code = forms.CharField(
            required=False,
            label='',
        )

    captcha_code = forms.CharField(
        required=True,
        label='',
    )
    real_captcha_code = forms.CharField(
        required=True,
        label='',
    )

    invite_tag = forms.CharField(
        required=False,
        label='',
    )

    # ('aws-bj-1', 'Amazon北京'),
    # ('aws-bj-1', '亚马逊[北京]'),
    # ('0', {'label':'亚马逊[北京](正在建设)', 'disabled': True})
    machine_region = forms.ChoiceField(label="",
                                       choices=RegionInfo.register_choices(),
                                       initial="ali-sh",
                                       widget=SelectWithDisabled)

    error_messages = {
        'nick_name_used': u"该用户名已存在",
        'email_used': u"邮件地址已被注册",
        'tenant_used': u"团队名已存在",
        'password_repeat': u"两次输入的密码不一致",
        'phone_used': u"手机号已存在",
        'phone_empty': u"手机号为空",
        'phone_captch_error': u"手机验证码已失效",
        'phone_code_error': u"手机验证码错误",
        'captcha_code_error': u"验证码有误",
        'machine_region_error': u"请选择数据中心",
    }

    def __init__(self, *args, **kwargs):
        init_phone = ""
        init_email = ""
        init_tenant = ""
        init_region = ""
        selected_region = ""
        next_url = None
        origin = None
        prefix_url = ""
        if len(kwargs) > 0:
            if kwargs.get("initial") is not None:
                initalObj = kwargs.get("initial")
                init_phone = initalObj["phone"]
                init_email = initalObj["email"]
                init_tenant = initalObj["tenant"]
                init_region = initalObj["region"]
            if kwargs.get("region_level") is not None:
                selected_region = kwargs["region_level"]["region"]
                kwargs.pop("region_level")
            if kwargs.get("next_url") is not None:
                next_url = kwargs["next_url"]
                prefix_url += "&next={0}".format(next_url)
                kwargs.pop("next_url")
            if kwargs.get("origin") is not None:
                origin = kwargs["origin"]
                prefix_url += "&origin={0}".format(origin)
                kwargs.pop("origin")
        if len(prefix_url) > 1:
            prefix_url = "?" + prefix_url[1:]
        if len(args) > 0:
            if type(args) is tuple:
                if args[0].get("initial") is not None:
                    initalObj = args[0]["initial"]
                    if type(initalObj) is list:
                        initalObj = initalObj(0)
                    init_phone = initalObj["phone"]
                    init_email = initalObj["email"]
                    init_tenant = initalObj["tenant"]
                    init_region = initalObj["region"]
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_tag = False

        text_phone = "手机号"
        text_email = "请输入邮箱地址"
        text_tenant = "团队域名"
        if init_phone is not None and init_phone != "":
            self.fields['phone'].widget.attrs['readonly'] = True
            text_phone = init_phone
        if init_email is not None and init_email != "":
            self.fields['email'].widget.attrs['readonly'] = True
            text_email = init_email
        if init_tenant is not None and init_tenant != "":
            self.fields['tenant'].widget.attrs['readonly'] = True
            text_tenant = init_tenant
        if init_region is not None and init_region != "":
            self.fields['machine_region'].initial = init_region
            self.fields['machine_region'].widget.attrs['readonly'] = True
        if selected_region is not None and selected_region != "":
            self.fields['machine_region'].initial = selected_region

        init_region = RegionInfo.register_choices()[0][0]
        # 对于社区版注册表单进行处理
        is_private = sn.instance.is_private()
        tenant_name = None
        if is_private:
            tenant_num = Tenants.objects.count()
            if tenant_num == 1:
                tenant_list = Tenants.objects.all()
                tenant = tenant_list[0]
                tenant_name = tenant.tenant_name

        # if settings.MODULES["Sms_Check"]:
        if settings.MODULES["WeChat_Module"]:
            self.helper.layout = Layout(
                Div(
                    Field('tenant',
                          "",
                          placeholder='请输入团队名(可使用小写英文字母、数字、下划线及中划线)',
                          css_class="form-control") if tenant_name is None else
                    Field('tenant',
                          "",
                          placeholder='请输入团队名(可使用小写英文字母、数字、下划线及中划线)',
                          css_class="form-control",
                          readonly="readonly",
                          value=tenant_name),
                    Field('nick_name',
                          css_class="form-control",
                          placeholder='请输入用户名(可使用小写英文字母、数字、下划线及中划线)'),
                    Field('email',
                          css_class="form-control",
                          placeholder='请输入邮箱(选填)'),
                    HTML("<hr/>"),
                    # 默认为ali-sh
                    Hidden('machine_region', value=init_region),
                    Hidden('next', value=next_url),
                    Hidden('origin', value=origin),
                    Field('password',
                          css_class="form-control",
                          placeholder='请设置密码,至少包含8位字符'),
                    Field('password_repeat',
                          css_class="form-control",
                          placeholder='请再输入一次密码'),
                    Field('phone',
                          css_class="form-control",
                          placeholder='请输入手机号'),
                    AppendedText(
                        'captcha_code',
                        '<img id="captcha_code" src="/captcha" /> <a href="javascript:void(0)" onclick="refresh();">看不清,换一张</a>  ',
                        css_class='input-xlarge',
                        placeholder='图片验证码'),
                    AppendedText(
                        'phone_code',
                        '<a href="javascript:void(0)" id="PhoneCodeBtn" onclick="getPhoneCode();">点击发送验证码</a>  ',
                        css_class='input-xlarge',
                        placeholder='手机验证码'),
                    HTML(
                        """<div class="linkfw text-center">点击注册表示你已阅读并同意《<a href="http://www.goodrain.com/goodrainlaws.html" target="_blank">云帮服务条款</a>》</div>"""
                    ),
                    FormActions(
                        Submit('register',
                               u'注册',
                               css_class='btn btn-lg btn-success btn-block')),
                    HTML("""<p class="text-center">或使用以下账号注册</p>"""),
                    HTML(
                        """<a href="/wechat/login{0}" class="weixin"><img src="static/www/images/weixin.png">微信</a>"""
                        .format(prefix_url)),
                    HTML(
                        """<div class="linkregister text-center">直接<a href="/login{0}">登录</a></div>"""
                        .format(prefix_url)),
                    # HTML("""<a href="http://www.goodrain.com/" class="linkgood text-center">goodrain.com</a>"""),
                    css_class="login-wrap"))
        else:
            self.helper.layout = Layout(
                Div(
                    Field('tenant',
                          "",
                          placeholder='请输入团队名(可使用小写英文字母、数字、下划线及中划线)',
                          css_class="form-control") if tenant_name is None else
                    Field('tenant',
                          "",
                          placeholder='请输入团队名(可使用小写英文字母、数字、下划线及中划线)',
                          css_class="form-control",
                          readonly="readonly",
                          value=tenant_name),
                    Field('nick_name',
                          css_class="form-control",
                          placeholder='请输入用户名(可使用小写英文字母、数字、下划线及中划线)'),
                    Field('email',
                          css_class="form-control",
                          placeholder='请输入邮箱(选填)'),
                    HTML("<hr/>"),
                    Hidden('machine_region', value=init_region),
                    Hidden('next', value=next_url),
                    Hidden('origin', value=origin),
                    Field('password',
                          css_class="form-control",
                          placeholder='请设置密码,至少包含8位字符'),
                    Field('password_repeat',
                          css_class="form-control",
                          placeholder='请再输入一次密码'),
                    Field('phone',
                          css_class="form-control",
                          placeholder='请输入手机号'),
                    AppendedText(
                        'captcha_code',
                        '<img id="captcha_code" src="/captcha" /> <a href="javascript:void(0)" onclick="refresh();">看不清,换一张</a>  ',
                        css_class='input-xlarge',
                        placeholder='验证码'),
                    AppendedText(
                        'phone_code',
                        '<a href="javascript:void(0)" id="PhoneCodeBtn" onclick="getPhoneCode();">点击发送验证码</a>  ',
                        css_class='input-xlarge',
                        placeholder='手机验证码'),
                    HTML(
                        """<div class="linkfw text-center">点击注册表示你已阅读并同意《<a href="http://www.goodrain.com/goodrainlaws.html" target="_blank">云帮服务条款</a>》</div>"""
                    ),
                    FormActions(
                        Submit('register',
                               u'注册',
                               css_class='btn btn-lg btn-success btn-block')),
                    HTML(
                        """<div class="linkregister text-center">直接<a href="/login{0}">登录</a></div>"""
                        .format(prefix_url)),
                    # HTML("""<a href="http://www.goodrain.com/" class="linkgood text-center">goodrain.com</a>"""),
                    css_class="login-wrap"))
        self.helper.form_id = 'form-normal-reg'
        self.helper.form_class = 'form-horizontal'

    def clean(self):
        email = self.cleaned_data.get('email')
        tenant = self.cleaned_data.get('tenant')
        nick_name = self.cleaned_data.get('nick_name')
        password = self.cleaned_data.get('password')
        password_repeat = self.cleaned_data.get('password_repeat')
        phone = self.cleaned_data.get('phone')
        phone_code = self.cleaned_data.get('phone_code')
        captcha_code = self.cleaned_data.get('captcha_code')
        real_captcha_code = self.cleaned_data.get('real_captcha_code')
        invite_tag = self.cleaned_data.get('invite_tag')
        machine_region = self.cleaned_data.get('machine_region')

        # 校验邮箱,为空不做校验
        if email is not None and email != "":
            try:
                Users.objects.get(email=email)
                raise forms.ValidationError(self.error_messages['email_used'],
                                            code='email_used',
                                            params={'email': email})
            except Users.DoesNotExist:
                pass

        # 判断是否邀请注册,邀请注册不校验租户
        if invite_tag is None or invite_tag == "":
            try:
                Tenants.objects.get(tenant_name=tenant)
                if not sn.instance.is_private():
                    raise forms.ValidationError(
                        self.error_messages['tenant_used'],
                        code='tenant_used',
                        params={'tenant': tenant})
            except Tenants.DoesNotExist:
                pass

        # 数据中心不做校验,默认为ali-sh
        if machine_region is None or machine_region == "" or machine_region == "1":
            pass
            # machine_region = "ali-sh"
            # raise forms.ValidationError(
            #     self.error_messages['machine_region_error'],
            #     code='machine_region_error',
            # )

        try:
            Users.objects.get(nick_name=nick_name)
            raise forms.ValidationError(self.error_messages['nick_name_used'],
                                        code='nick_name_used')
        except Users.DoesNotExist:
            pass

        if password_repeat != password:
            raise forms.ValidationError(
                self.error_messages['password_repeat'],
                code='password_repeat',
            )

        # 手机号码为空不做校验,不为空校验是否已经存在
        if phone is not None and phone != "":
            phoneNumber = Users.objects.filter(phone=phone).count()
            logger.debug('form_valid.register', phoneNumber)
            if phoneNumber > 0:
                raise forms.ValidationError(self.error_messages['phone_used'],
                                            code='phone_used')
        else:
            pass
            # raise forms.ValidationError(
            #     self.error_messages['phone_empty'],
            #     code='phone_empty'
            # )

        if phone is not None and phone != "":
            if settings.MODULES["Sms_Check"]:
                phoneCodes = PhoneCode.objects.filter(
                    phone=phone).order_by('-ID')[:1]
                if len(phoneCodes) > 0:
                    phoneCode = phoneCodes[0]
                    last = int(phoneCode.create_time.strftime("%s"))
                    now = int(time.time())
                    if now - last > 300:
                        logger.info('form_valid.register',
                                    phone + "too long time")
                        raise forms.ValidationError(
                            self.error_messages['phone_captch_error'],
                            code='phone_captch_error')
                    if phoneCode.code != phone_code:
                        logger.info('form_valid.register',
                                    phone + " different")
                        raise forms.ValidationError(
                            self.error_messages['phone_code_error'],
                            code='phone_code_error')
                else:
                    raise forms.ValidationError(
                        self.error_messages['phone_code_error'],
                        code='phone_code_error')
        else:
            logger.info('form_valid.register', " phone is None")
            pass
            # raise forms.ValidationError(
            #     self.error_messages['phone_empty'],
            #     code='phone_empty'
            # )

        if real_captcha_code is None or captcha_code is None or real_captcha_code.lower(
        ) != captcha_code.lower():
            raise forms.ValidationError(
                self.error_messages['captcha_code_error'],
                code='captcha_code_error')

        return self.cleaned_data