def signUp(): if request.method == 'POST': if vaptcha.validate: account = request.form.get("account") vcode = request.form.get("vcode") password = request.form.get("password") repassword = request.form.get("repassword") auth = Authentication(g.mysql, g.redis) try: res = auth.signUp(account=account, vcode=vcode, password=password, repassword=repassword, register_ip=g.ip) except Exception, e: logger.error(e, exc_info=True) flash(u"系统异常,请稍后再试") else: res = dfr(res) if res["success"]: # 写登陆日志 return redirect(url_for('.signIn')) else: flash(res["msg"]) else: flash(u"人机验证失败") return redirect(url_for('.signUp'))
def ssoCreateTicket(self, sid=None, agent=None, ip=None): """创建授权令牌写入redis 说明: 授权令牌:临时鉴别使用,有效期3min,写入令牌集合中。 参数: sid str: 当None时表明未登录,此时ticket是首次产生;当真时,说明已登录,此时ticket非首次产生,其值需要设置为有效的sid """ ticket = gen_requestId() init = dict(last=get_current_timestamp()) if sid else dict( ctime=get_current_timestamp(), agent=agent, ip=ip) sid = sid or md5(ticket) tkey = "passport:sso:ticket:{}".format(ticket) skey = "passport:sso:sid:{}".format(sid) try: pipe = self.redis.pipeline() pipe.set(tkey, sid) #tkey过期,ticket授权令牌过期,应当给个尽可能小的时间,并且ticket使用过后要删除(一次性有效) pipe.expire(tkey, 180) #skey初始化数据 pipe.hmset(skey, init) #skey过期,即cookie过期,设置为jwt过期秒数,每次创建ticket都要更新过期时间 pipe.expire(skey, SYSTEM["SESSION_EXPIRE"]) pipe.execute() except Exception, e: logger.error(e, exc_info=True)
def ssoCreateSid(self, ticket, uid, source_app_name): """创建sid并写入redis 说明: sid:可以理解为user-agent,sso server cookie(jwt payload)中携带 参数: ticket str: 授权令牌 uid str: 用户唯一id source_app_name str: sso应用名,本次sid对应的首个应用 """ if ticket and isinstance(ticket, basestring) and uid and source_app_name: tkey = "passport:sso:ticket:{}".format(ticket) sid = self.redis.get(tkey) if sid: skey = "passport:sso:sid:{}".format(sid) try: pipe = self.redis.pipeline() pipe.hmset(skey, dict(uid=uid, sid=sid, source=source_app_name)) pipe.expire(skey, SYSTEM["SESSION_EXPIRE"]) pipe.execute() except Exception, e: logger.error(e, exc_info=True) else: return True
def listUserApp(self): """ 查询userapp应用列表 """ res = dict(msg=None, code=1) key = "passport:user:apps" try: if self.cache_enable is False: raise data = json.loads(self.redis.get(key)) if data: logger.info("Hit listUserApps Cache") else: raise except: sql = "SELECT id,name,description,app_id,app_secret,app_redirect_url,ctime,mtime FROM sso_apps" try: data = self.mysql.query(sql) except Exception, e: logger.error(e, exc_info=True) res.update(msg="System is abnormal") else: res.update(data=data, code=0) pipe = self.redis.pipeline() pipe.set(key, json.dumps(data)) pipe.expire(key, 600) pipe.execute()
def count_message(self, uid, msgStatus=2): """统计消息 @param uid str: 用户id @param msgStatus int: 消息状态 1-未读 0-已读, 默认2代表统计所有状态消息 """ res = dict(msg=None, code=1) if uid: try: msgStatus = int(msgStatus) except (TypeError, ValueError): res.update(msg="There are invalid parameters", code=2) else: try: if msgStatus in (0, 1): msgIds = self.redis.zrange(self.gen_usermsgKey(uid), 0, -1) if msgIds: pipe = self.redis.pipeline() for msgId in msgIds: pipe.hget(self.gen_usermsgIdKey(msgId), "msgStatus") data = pipe.execute() count = sum( map( lambda _status: 1 if int(_status) == msgStatus else 0, data)) else: count = 0 else: count = self.redis.zcard(self.gen_usermsgKey(uid)) except Exception, e: logger.error(e, exc_info=True) res.update(msg="System is abnormal", code=3) else: res.update(code=0, count=count)
def push_message(self, uid, msgContent, msgType="system"): """ 推送一条站内消息 @param msgContent str: 消息内容,允许部分html标签,参见`ALLOWED_TAGS` @param msgType str: 消息类型 """ res = dict(code=1, msg=None) if uid and msgContent and msgType and isinstance( msgContent, (unicode, str)) and msgType in self.ALLOWED_MSGTYPE: msgId = gen_token().lower() msgTime = get_current_timestamp() msgContent = bleach.clean(msgContent, tags=self.ALLOWED_TAGS, attributes=self.ALLOWED_ATTRIBUTES, styles=self.ALLOWED_STYLES) try: pipe = self.redis.pipeline() pipe.zadd(self.gen_usermsgKey(uid), msgId, msgTime) pipe.hmset( self.gen_usermsgIdKey(msgId), dict(msgId=msgId, msgContent=msgContent, msgTime=msgTime, msgType=msgType, msgStatus=1)) pipe.execute() except Exception, e: logger.error(e, exc_info=True) res.update(msg="System is abnormal", code=2) else: res.update(code=0)
def useruploadpub(): # 通过表单形式上传图片 res = dict(code=1, msg=None) logger.debug(request.files) f = request.files.get('file') callableAction = request.args.get("callableAction") if f and allowed_file(f.filename): filename = gen_rnd_filename() + "." + secure_filename( f.filename).split('.')[-1] # 随机命名 # 判断是否上传到又拍云还是保存到本地 if Upyun['enable'] in ('true', 'True', True): basedir = Upyun['basedir'] if Upyun['basedir'].startswith( '/') else "/" + Upyun['basedir'] imgUrl = os.path.join(basedir, filename) try: # 又拍云存储封装接口 UploadImage2Upyun(imgUrl, f.stream.read()) except Exception, e: logger.error(e, exc_info=True) res.update(code=2, msg="System is abnormal") else: imgUrl = Upyun['dn'].strip("/") + imgUrl res.update(data=dict(src=imgUrl), code=0) else: if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) f.save(os.path.join(UPLOAD_FOLDER, filename)) imgUrl = request.url_root + IMAGE_FOLDER + filename res.update(data=dict(src=imgUrl), code=0)
def Get(self, dbId): """通过dbId获取MySQL实例数据""" sql = "select host,port,user,passwd from incetops_db where id=%s" try: data = self.mysql.get(sql, dbId) except Exception, e: logger.error(e, exc_info=True)
def userupload(): # 通过base64形式上传图片 res = dict(code=1, msg=None) picStr = request.form.get('picStr') if picStr: # 判断是否上传到又拍云还是保存到本地 if Upyun['enable'] in ('true', 'True', True): basedir = Upyun['basedir'] if Upyun['basedir'].startswith('/') else "/" + Upyun['basedir'] imgUrl = os.path.join(basedir, gen_rnd_filename() + ".png") try: # 又拍云存储封装接口 UploadImage2Upyun(imgUrl, base64.b64decode(picStr)) except Exception, e: logger.error(e, exc_info=True) res.update(code=2, msg="System is abnormal") else: imgUrl = Upyun['dn'].strip("/") + imgUrl res.update(imgUrl=imgUrl, code=0) else: filename = gen_rnd_filename() + ".png" if not os.path.exists(UPLOAD_FOLDER): os.makedirs(UPLOAD_FOLDER) with open(os.path.join(UPLOAD_FOLDER, filename), "wb") as f: f.write(base64.b64decode(picStr)) imgUrl = request.url_root + IMAGE_FOLDER + filename res.update(imgUrl=imgUrl, code=0) # "回调"动作 if res.get("imgUrl"): imgUrl = res.get("imgUrl") callableAction = request.args.get("callableAction") if callableAction == "UpdateAvatar": resp = g.api.userprofile.updateUserAvatar(uid=g.uid, avatarUrl=imgUrl) res.update(resp) if resp["code"] == 0: # 同步头像 g.api.usersso.clientsConSync(g.api.userapp.getUserApp, g.uid, dict(CallbackType="user_avatar", CallbackData=imgUrl))
def POST(self, swarmName, swarmIp): """ add a swarm cluster into current, check, pickle. """ res = {"msg": None, "code": 0} swarmIp = swarmIp.strip() swarmName = swarmName.strip() logger.debug( "post a swarm cluster, name is %s, ip is %s, check ip is %s" % (swarmName, swarmIp, ip_check(swarmIp))) if not swarmName or not swarmIp or not ip_check(swarmIp): res.update(msg="POST: data params error", code=-1020) elif self.isMember(swarmName): res.update(msg="POST: swarm cluster already exists", code=-1021) else: #access node ip's info, and get all remote managers url = Splice(netloc=swarmIp, port=self.port, path='/info').geturl swarm = dict(name=swarmName) logger.info( "init a swarm cluter named %s, will get swarm ip info, that url is %s" % (swarmName, url)) try: nodeinfo = requests.get(url, timeout=self.timeout, verify=self.verify).json() logger.debug("get swarm ip info, response is %s" % nodeinfo) swarm["manager"] = [ nodes["Addr"].split(":")[0] for nodes in nodeinfo["Swarm"]["RemoteManagers"] ] except Exception, e: logger.error(e, exc_info=True) res.update(msg="POST: access the node ip has exception", code=-1022) else:
def QQ_Login_Page_State(code, QQ_APP_ID, QQ_APP_KEY, QQ_REDIRECT_URI, timeout=5, verify=False): ''' Authorization Code cannot repeat ''' QQ_Access_Token_Url = Splice(scheme="https", domain="graph.qq.com", path="/oauth2.0/token", query={ "grant_type": "authorization_code", "client_id": QQ_APP_ID, "client_secret": QQ_APP_KEY, "code": code, "state": "P.passport", "redirect_uri": QQ_REDIRECT_URI }).geturl access_token_data = requests.get(QQ_Access_Token_Url, timeout=timeout, verify=verify).text try: data = Parse_Access_Token(access_token_data) except Exception, e: logger.error(e, exc_info=True) data = Callback_Returned_To_Dict(access_token_data)
def Add(self, host, port, user, passwd, sd, ris=''): """添加一个服务 @param host,port,user,passwd,分别对应db的地址:端口:用户:密码 @param sd str: 这个db的描述 @param ris str: 即推荐的inception的地址:端口,例如127.0.0.1:6669,端口默认6669 """ res = dict(msg=None, code=1) if ris: ihost, iport = ris.split(":") if ":" in ris else (ris, 6669) if not ip_check(ihost) or not number_check(iport): res.update(msg="Invaild ris") return res if sd and host and port and user and passwd: if " " in passwd or "%" in passwd: res.update(msg="Password has spaces or %") return res if number_check(port): sql = "INSERT INTO incetops_db (sd,host,port,user,passwd,ris,ctime) VALUES(%s,%s,%s,%s,%s,%s,%s)" try: self.mysql.insert(sql, sd, host, port, user, self.Encrypt(passwd), ris, get_current_timestamp()) except IntegrityError: res.update(msg="DB connection already exists") except Exception, e: logger.error(e, exc_info=True) res.update(msg="System exception") else: res.update(code=0) else: res.update(msg="Invaild db port")
def GitHub_Login_Page_State(code, GITHUB_APP_ID, GITHUB_APP_KEY, GITHUB_REDIRECT_URI, timeout=5, verify=False): ''' Authorization Code cannot repeat ''' Access_Token_Url = Splice(scheme="https", domain="github.com", path="/login/oauth/access_token", query={ "client_id": GITHUB_APP_ID, "client_secret": GITHUB_APP_KEY, "code": code, "redirect_uri": GITHUB_REDIRECT_URI }).geturl data = requests.post(Access_Token_Url, timeout=timeout, verify=verify).text data = Parse_Access_Token(data) if "access_token" in data: access_token = data.get("access_token") User_Info_Url = Splice(scheme="https", domain="api.github.com", path="/user", query={ "access_token": access_token }).geturl data = requests.get(User_Info_Url, timeout=timeout, verify=verify).json() username = "******" + data.get("login") user_id = data.get("id") user_github = data.get("html_url") user_cname = data.get("name") user_avater = data.get("avatar_url") user_email = data.get("email") user_extra = "blog:%s, company:%s, location:%s" % ( data.get("blog"), data.get("company"), data.get("location")) try: UserSQL = "INSERT INTO User (username, cname, email, avatar, time, github, extra) VALUES (%s, %s, %s, %s, %s, %s, %s)" mysql.insert(UserSQL, username, user_cname, user_email, user_avater, How_Much_Time(), user_github, user_extra) OAuthSQL = "INSERT INTO OAuth (oauth_username, oauth_type, oauth_openid, oauth_access_token, oauth_expires) VALUES (%s, %s, %s, %s, %s)" mysql.insert(OAuthSQL, username, "GitHub", user_id, access_token, How_Much_Time()) except IntegrityError, e: logger.debug(e, exc_info=True) #Check if it has been registered CheckSQL = "SELECT oauth_username FROM OAuth WHERE oauth_username=%s" if mysql.get(CheckSQL, username): UpdateSQL = "UPDATE OAuth SET oauth_access_token=%s, oauth_expires=%s, oauth_openid=%s WHERE oauth_username=%s" mysql.update(UpdateSQL, access_token, How_Much_Time(), user_id, username) #update user profile UpdateUserSQL = "UPDATE User SET cname=%s, avatar=%s, extra=%s WHERE username=%s" mysql.update(UpdateUserSQL, user_cname, user_avater, user_extra, username) return {"username": username, "uid": user_id} except Exception, e: logger.error(e, exc_info=True) return False
def listUserLoginHistory(self, uid, page=1, limit=5, sort="desc"): """ 查询用户登录历史 @param uid str: 用户唯一id 分页参数: @param page int: 请求页数,从1开始 @param limit int: 每页数据量 @param sort str: 排序,可选值asc正序、desc倒序 """ res = dict(code=1, msg=None) # 检查参数 try: page = int(page) limit = int(limit) sort = sort.upper() if not uid or page < 1 or limit < 1 or not sort in ("ASC", "DESC"): raise except: res.update(code=2, msg="There are invalid parameters") else: # mysql处分页 # select * from xxx where xxx order by xx sort limit offset(page不为0时=(page-1)*limit),rows(limit); sql1 = "SELECT id,uid,login_type,login_ip,login_area,login_time,user_agent,browser_type,browser_device,browser_os,browser_family FROM user_loginlog WHERE uid=%s ORDER BY id {} LIMIT {},{}".format( sort, (page - 1) * limit, limit) sql2 = "SELECT count(id) FROM user_loginlog WHERE uid=%s" try: data1 = self.mysql.query(sql1, uid) data2 = self.mysql.get(sql2, uid) except Exception, e: logger.error(e, exc_info=True) res.update(msg="System is abnormal", code=3) else:
def getUserProfile(self, uid, getBind=False): """ 查询用户资料 @param uid str: 用户id """ res = dict(msg=None, code=1) key = "passport:user:profile:{}".format(uid) try: if self.cache_enable is False: raise data = json.loads(self.redis.get(key)) if data: logger.info("Hit getUserProfile Cache") else: raise except: sql = "SELECT register_source,register_ip,nick_name,domain_name,gender,birthday,signature,avatar,location,ctime,mtime,is_realname,is_admin,lock_nick_name,lock_domain_name FROM user_profile WHERE uid=%s" if uid and isinstance(uid, (str, unicode)) and len(uid) == 22: try: data = self.mysql.get(sql, uid) except Exception, e: logger.error(e, exc_info=True) res.update(msg="System is abnormal") else: res.update(data=data, code=0) pipe = self.redis.pipeline() pipe.set(key, json.dumps(data)) pipe.expire(key, 3600) pipe.execute() else: res.update(msg="There are invalid parameters", code=2)
def listUserBind(self, uid): """ 查询用户绑定的社交账号 @param uid str: 用户唯一id """ bind = [] if uid: #sql = "SELECT id,identity_type,ctime,mtime,etime FROM user_auth WHERE identity_type in (1, 2, 3, 4, 5, 6, 7, 8, 9) AND status=1 AND uid=%s" sql = "SELECT id,identity_type,identifier,ctime,mtime,etime FROM user_auth WHERE status=1 AND uid=%s" try: data = self.mysql.query(sql, uid) except Exception, e: logger.error(e, exc_info=True) else: # 定义map解析函数 def parse(i): if i["identity_type"] == 1: # identifier = "{}****{}".format(i["identifier"][0:3], i["identifier"][7:]) identifier = i["identifier"] elif i["identity_type"] == 2: # identifier = "{}****{}@{}".format(i["identifier"].split('@')[0][0:3], i["identifier"].split('@')[0][7:], i["identifier"].split('@')[-1]) identifier = i["identifier"] else: identifier = "" return { "identity_type": oauth2_type2name(i["identity_type"]), "ctime": i["ctime"], "mtime": i["mtime"], "auth_type": "lauth" if i["identity_type"] in (1, 2) else "oauth", "identifier": identifier } bind = map(parse, data)
def updateUserPassword(self, uid, nowpass, newpass, repass): """修改密码 @param uid str: 用户id @param nowpass str: 当前密码 @param newpass str: 新密码 @param repass str: 确认新密码 """ res = dict(msg=None, code=1) if uid and nowpass and 6 <= len( nowpass) <= 30 and newpass and newpass == repass and 6 <= len( newpass) <= 30: if nowpass == newpass: res.update( msg= "The new password request is inconsistent with the current password", code=5) else: if self.__check_modifyPass(uid): if self.__checkUserPassword(uid, nowpass): try: sql = "UPDATE user_auth SET certificate=%s WHERE identity_type IN (1,2) AND uid = %s" self.mysql.update(sql, generate_password_hash(newpass), uid) except Exception, e: logger.error(e, exc_info=True) res.update(msg="System is abnormal", code=2) else: res.update(code=0) else: res.update(msg="The current password is wrong", code=3) else: res.update(msg="Please bind the email or phone first", code=6)
def userupload(): # 通过base64形式上传图片 res = dict(code=1, msg=None) picStr = request.form.get('picStr') callableAction = request.args.get("callableAction") if picStr: basedir = Upyun['basedir'] if Upyun['basedir'].startswith( '/') else "/" + Upyun['basedir'] imgUrl = os.path.join(basedir, gen_rnd_filename() + ".png") try: # 又拍云存储封装接口 upyunapi = CloudStorage(timeout=15) upyunapi.put(imgUrl, base64.b64decode(picStr)) except Exception, e: logger.error(e, exc_info=True) res.update(code=2, msg="System is abnormal") else: imgUrl = Upyun['dn'].strip("/") + imgUrl res.update(imgUrl=imgUrl, code=0) if callableAction == "UpdateAvatar": resp = g.api.userprofile.updateUserAvatar(uid=g.uid, avatarUrl=imgUrl) res.update(resp) if resp["code"] == 0: # 同步头像 g.api.usersso.clientsConSync( g.api.userapp.getUserApp, g.uid, dict(CallbackType="user_avatar", CallbackData=imgUrl))
def __scan_third(self): if self.__third_hooks and isinstance(self.__third_hooks, list): for hn in self.__third_hooks: #: hn: the name of the hook module that can be imported if hn in modules: hm = modules[hn] if getattr(hm, '__mtime__', 0) < getmtime( self.__get_fileorparent(hm)): del modules[hn] try: ho = __import__(hn) except ImportError as e: logger.error(e, exc_info=True) continue if hasattr(ho, "__version__") and hasattr(ho, "__author__"): #: 语义化版本号 if not is_valid_verion(ho.__version__): warnings.warn("%s: irregular version number" % hn) continue #: 匹配扩展要求的应用版本 appversion = getattr(ho, "__appversion__", None) if not is_match_appversion(appversion): warnings.warn( "%s: app version number does not match for %s" % (hn, appversion)) continue ho.__mtime__ = getmtime(self.__get_fileorparent(ho)) ho.__family__ = "third" self.__hooks[hn] = self.__get_meta(ho)
def getSwarm(self, checkState=False, UpdateManager=False): """ 查询存储中所有Swarm集群信息(并检查健康状态) """ logger.info( "get all swarm and check state(%s) for all swarm cluster with UpdateManager(%s), start" % (checkState, UpdateManager)) swarms = [] for swarm in self._swarms: if checkState == True: swarm.update(state=self._checkSwarmHealth( self._checkSwarmLeader(swarm))) elif "state" in swarm: swarm.pop("state") if UpdateManager == True: logger.info("Update manager in getSwarm, start") try: manager = self._checkSwarmManager( self._checkSwarmLeader(swarm)) except Exception, e: logger.error(e, exc_info=True) logger.info("Update manager in getSwarm, end, fail") else: if manager: swarm.update(manager=manager) logger.info( "Update manager in getSwarm, end, successfully, manager is %s" % manager) swarms.append(swarm)
def upload_view(): res = dict(code=-1, msg=None) logger.debug(request.files) f = request.files.get('file') if f and allowed_file(f.filename): filename = secure_filename(gen_rnd_filename() + "." + f.filename.split('.')[-1]) #随机命名 basedir = Upyun['basedir'] if Upyun['basedir'].startswith( '/') else "/" + Upyun['basedir'] imgUrl = os.path.join(basedir, filename) try: upres = api.put(imgUrl, f.stream.read()) except Exception, e: logger.error(e, exc_info=True) res.update(code=2, msg="Storage failure") else: imgId = md5(filename) imgUrl = Upyun['dn'].strip("/") + imgUrl upres.update(ctime=get_current_timestamp(), imgUrl=imgUrl, imgId=imgId) try: pipe = g.redis.pipeline() pipe.sadd(picKey, imgId) pipe.hmset("{}:{}".format(GLOBAL['ProcessName'], imgId), upres) pipe.execute() except Exception, e: logger.error(e, exc_info=True) res.update( code=0, msg= "It has been uploaded, but the server has encountered an unknown error" ) else:
def __oauth2_getUid(self, openid): """根据openid获取uid""" sql = "SELECT uid FROM user_auth WHERE identifier=%s" try: data = self.db.get(sql, openid) except Exception, e: logger.error(e, exc_info=True)
def GetList(self, page=1, limit=10, sort="desc"): """ 获取任务列表 分页参数: @param page int: 请求页数,从1开始 @param limit int: 每页数据量 @param sort str: 排序,可选值asc正序、desc倒序 """ res = dict(code=1, msg=None) # 检查参数 try: page = int(page) limit = int(limit) sort = sort.upper() if page < 1 or limit < 1 or not sort in ("ASC", "DESC"): raise except: res.update(code=2, msg="There are invalid parameters") else: # mysql处分页 # select * from xxx where xxx order by xx sort limit offset(page不为0时=(page-1)*limit),rows(limit); sql1 = "SELECT taskId,dbId,t.sd taskSd,inception,applicant,t.ctime,status,statusMsg,timer,timer_id,sqlContent,autoviewResult,autoviewSQLSHA1,enableIgnoreWarnings,enableRemoteBackup,executeResult,ftime,d.sd dbSd,host,port,user FROM incetops_task t LEFT JOIN incetops_db d ON t.dbId = d.id ORDER BY taskId {} LIMIT {},{}".format( sort, (page - 1) * limit, limit) sql2 = "SELECT count(*) as count FROM incetops_task" try: data1 = self.mysql.query(sql1) data2 = self.mysql.get(sql2) except Exception, e: logger.error(e, exc_info=True) res.update(msg="System is abnormal", code=3) else:
def signIn(self, account, password): """登录接口,面向前端 参数: @param account str: 注册时的账号,邮箱/手机号 @param password str: 密码 流程: 1. 判断账号类型,仅支持邮箱、手机号两种本地账号。 2. 校验账号(是否合法、启用状态等)。 3. 校验密码(是否合格、正确)。 """ res = dict(msg=None, success=False) # NO.1 检查账号类型 if email_check(account): # 账号类型:邮箱 identity_type = 2 # NO.2 检查账号 if password and 6 <= len(password) < 30: sql = "SELECT uid,certificate FROM user_auth WHERE identity_type={} AND identifier=%s AND status=1".format(identity_type) try: data = self.db.get(sql, account) except Exception, e: logger.error(e, exc_info=True) res.update(msg="System is abnormal") else: if data and isinstance(data, dict): uid = data["uid"] certificate = data["certificate"] if check_password_hash(certificate, password): res.update(success=True, uid=uid, identity_type=identity_type) else: res.update(msg="Wrong password") else: res.update(msg="Invalid account: does not exist or has been disabled") else: res.update(msg="Invalid password: length unqualified")
def misc_sendVcode(): """发送验证码:邮箱、手机""" res = dict(msg=None, success=False) account = request.form.get("account") scene = request.form.get("scene") or request.args.get("scene") or "signUp" scenemap = dict(signUp=u"注册", bindLauth=u"绑定本地化账号", forgot=u"忘记密码") if email_check(account): # 生成验证码,校验的话,libs.auth.Authentication类中`__check_sendVcode`方法 email = account key = "passport:vcode:{}:{}".format(scene, email) try: hasKey = g.redis.exists(key) except Exception, e: logger.error(e, exc_info=True) res.update(msg="System is abnormal") else: if hasKey: res.update(msg="Have sent the verification code, please check the mailbox") else: # 初始化邮箱发送服务 sendmail = SendMail() vcode = generate_verification_code() result = sendmail.SendMessage(to_addr=email, subject=u"SaintIC Passport %s 验证码" %scenemap[scene], formatType="html", message=email_tpl % (email, scenemap[scene], vcode)) if result["success"]: try: g.redis.set(key, vcode) g.redis.expire(key, 300) except Exception, e: logger.error(e, exc_info=True) res.update(msg="System is abnormal") else: res.update(msg="Sent verification code, valid for 300 seconds", success=True) else:
def signUp(): if request.method == 'POST': sceneid = request.args.get("sceneid") or "02" token = request.form.get("token") challenge = request.form.get("challenge") if token and challenge and vaptcha.validate(challenge, token, sceneid): account = request.form.get("account") vcode = request.form.get("vcode") password = request.form.get("password") repassword = request.form.get("repassword") register_ip = request.headers.get('X-Real-Ip', request.remote_addr) auth = Authentication(g.mysql, g.redis) try: res = auth.signUp(account=account, vcode=vcode, password=password, repassword=repassword, register_ip=register_ip) except Exception, e: logger.error(e, exc_info=True) flash(u"系统异常,请稍后再试") else: res = dfr(res) if res["success"]: # 写登陆日志 return redirect(url_for('.signIn')) else: flash(res["msg"]) else: flash(u"人机验证失败") return redirect(url_for('.signUp'))
def DELETE(self, serviceFlag): #delete a service res = {"msg": None, "code": 0} logger.info(serviceFlag) if not self.leader: res.update(msg="No active swarm", code=-1000) logger.info(res) return res if not serviceFlag: res.update(msg="no service id or name<%s>" % serviceFlag, code=50100) logger.info(res) return res logger.info("delete service, check parameters pass") try: SwarmEngineServiceDeleteUrl = Splice(netloc=self.leader, port=self.port, path="/services/%s" % serviceFlag).geturl SwarmEngineServiceDeleteRes = requests.delete( SwarmEngineServiceDeleteUrl, timeout=self.timeout, verify=self.verify) SwarmEngineServiceDeleteCode = SwarmEngineServiceDeleteRes.status_code except Exception, e: logger.error(e, exc_info=True) res.update(success=False, code=50200, msg="delete service<%s> fail" % serviceFlag)
def GET(self, node=None): """ 查询所有可用的节点群,并组织返回节点信息 """ res = {"code": 0, "msg": None, "data": []} if self.leader: #format (host, id, role, status, availability, reachability, containers, cpu, mem, label, UpdatedAt, DockerVersion). req_data = self._checkSwarmNode(self.leader, node) req_data = req_data if isinstance(req_data, (list, tuple)) else (req_data, ) node_data = [] for i in req_data: try: node_id = i['ID'] node_role = 'Leader' if i.get( 'ManagerStatus', {}).get('Leader') else i['Spec'].get('Role') node_host = i['Spec'].get('Labels', {}).get( 'ipaddr', i['Description']['Hostname']) or i.get( 'ManagerStatus', {}).get('Addr', '').split(':')[0] node_status = i['Status']['State'] node_availability = i['Spec'].get('Availability') node_reachability = i.get('ManagerStatus', {}).get('Reachability') node_containers = self._checkSwarmNodeinfo(node_host).get( "ContainersRunning" ) if ip_check( node_host ) and node_status == "ready" and node_availability == "active" else 'Unknown' node_cpu = int(i['Description']['Resources']['NanoCPUs'] / 1e9) node_mem = int( i['Description']['Resources']['MemoryBytes'] / 1e6 / 1024) #bytes to G node_label = i['Spec'].get('Labels') if isinstance(node_label, dict): _node_label = '' for k, v in node_label.iteritems(): _node_label += '%s=%s, ' % (k, v) node_label = _node_label.strip(' ,') node_CreatedAt = timeChange(i['CreatedAt']) node_UpdatedAt = timeChange(i['UpdatedAt']) node_dockerVersion = i['Description']['Engine'][ 'EngineVersion'] node_indexVersion = i.get("Version", {}).get("Index") except Exception, e: logger.error(e, exc_info=True) logger.debug(i) node_host = i['Spec'].get('Labels', {}).get( 'ipaddr', i['Description']['Hostname']) or i.get( 'ManagerStatus', {}).get('Addr', '').split(':')[0] node_data.append((node_host, i.get("ID"))) else: node_data.append( (node_host, node_id, node_role, node_status, node_availability, node_reachability, node_containers, node_cpu, node_mem, node_label, node_CreatedAt, node_UpdatedAt, node_dockerVersion)) res.update(data=node_data)
def config(): try: set_site_config(request.form.to_dict()) except Exception as e: logger.error(e, exc_info=True) return dict(code=1, msg="An unknown error occurred in the program") else: return dict(code=0)
def _checkSwarmNetwork(self, leader, networkId=None): """ 查询集群网络 """ try: path = "/networks/" + networkId if networkId else "/networks" NetUrl = Splice(netloc=leader, port=self.port, path=path).geturl NetData = requests.get(NetUrl, timeout=self.timeout, verify=self.verify).json() except Exception,e: logger.error(e, exc_info=True)