def post(self, request, *args, **kwargs): self.form = AppendInfoForm(request.POST) if not self.form.is_valid(): return self.get_response() post_data = request.POST.dict() try: user = request.user if isinstance(user, AnonymousUser): return JsonResponse({"info": "anonymoususer"}, status=403) nick_name = post_data.get('nick_name') tenant_name = post_data.get('tenant') git_pass = post_data.get('password') user.nick_name = nick_name user.is_active = True user.save(update_fields=['nick_name', 'is_active']) monitorhook.registerMonitor(user, 'register from ucloud') # init tenant region_names = ['ucloud-bj-1'] enterprise_svc.create_and_init_tenant(user.pk, tenant_name, region_names, user.enterprise_id) # create gitlab user if user.email is not None and user.email != "": codeRepositoriesService.createUser(user.email, git_pass, nick_name, nick_name) return self.redirect_view() except Exception, e: logger.exception(e) return JsonResponse({"info": "server error"}, status=500)
def post(self, request, *args, **kwargs): """ 管理后台初始化云帮账户 --- parameters: - name: body description: json内容 required: true type: string paramType: body """ result = {} try: user_info = request.data.get("user_info") enterprise_info = request.data.get("enterprise_info") username = user_info["username"] password = user_info["password"] email = user_info["email"] phone = user_info["phone"] eid = enterprise_info["eid"] name = enterprise_info["name"] is_active = enterprise_info["is_active"] logger.debug("user info {0} enterprise info {1}".format( user_info, enterprise_info)) is_user_exist = user_service.is_user_exist(username) if is_user_exist: result = generate_result("1002", "user exist", "用户已存在") return Response(result) if_ent_exist = enterprise_service.is_enterprise_exist(name) if if_ent_exist: result = generate_result("1004", "exterprise exist", "企业已存在") return Response(result) logger.debug("create tenant enterprise") # 创建企业 enterprise = enterprise_service.create_enterprise( eid, name, name, "", is_active) # 创建用户 logger.debug("create tenant user") user = user_service.create_user(username, password, email or '', phone or '', enterprise.enterprise_id, "backend") logger.debug("create tenant and init tenant") enterprise_svc.create_and_init_tenant( user_id=user.user_id, enterprise_id=user.enterprise_id) user.is_active = True user.save() result = generate_result("0000", "success", "初始化成功") except Exception as e: logger.exception(e) result = generate_error_result() return Response(result)
def create_tenant(self, tenant_name, region, user_id, nick_name, enterprise_id): """创建租户""" regions = [region] if region else [] tenant = enterprise_svc.create_and_init_tenant(user_id, tenant_name, regions) return tenant
def get(self, request, *args, **kwargs): user_id = request.GET.get('uid') tenant_name = request.GET.get('tenant_name') region_names = request.GET.get('region') enterprise_id = request.GET.get('eid') action = request.GET.get('action') if action == 'del': user_svc.delete_tenant(user_id) return JsonResponse(data={'message': 'ok'}) else: regions = region_names.split(',') if region_names else [] try: tenant = enterprise_svc.create_and_init_tenant( user_id, tenant_name, regions, enterprise_id) return JsonResponse(data={ 'message': 'ok', 'data': tenant.to_dict() }) except Exception as e: logger.exception(e) return JsonResponse(data={'message': e.message})
def active_market_enterprise(self, sso_user, enterprise_id, market_client_id, market_client_token): """ 将sso_user 绑定到指定的enterprise上,并绑定访问云市的认证信息 :param sso_user: :param enterprise_id: :param market_client_id: :param market_client_token: :return: """ enterprise = enterprise_svc.get_enterprise_by_id(enterprise_id) # 如果要绑定的企业在本地云帮不存在, 且eid与云市eid一致,则创建一个与公有云一致的企业信息 if not enterprise and enterprise_id == sso_user.eid: # 注册一个用户信息 user = user_svc.register_user_from_sso(sso_user) # 创建一个企业信息 enterprise = enterprise_svc.create_enterprise( enterprise_id=sso_user.eid, enterprise_alias=sso_user.company) logger.info('create enterprise[{0}] with name {1}[{2}]'.format( enterprise.enterprise_id, enterprise.enterprise_alias, enterprise.enterprise_name)) # 绑定用户与企业关系 user.enterprise_id = enterprise.enterprise_id user.save() 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)) # 初始化用户工作环境 tenant = enterprise_svc.create_and_init_tenant( user_id=user.user_id, enterprise_id=user.enterprise_id) domain = os.getenv('GOODRAIN_APP_API', settings.APP_SERVICE_API["url"]) return client_auth_service.save_market_access_token( enterprise_id, domain, market_client_id, market_client_token)
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))
def create_and_init_tenant(self, user): tenant = enterprise_svc.create_and_init_tenant( user_id=user.user_id, enterprise_id=user.enterprise_id) user.is_active = True return tenant
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()
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)