def wxWebLogin(request): if request.method == 'POST': json_para = JsonRequest(request.body) try: puserTempId = json_para.get('userTempId','') puserTempToken = json_para.get('userTempToken','') pToken = get_token(request) debug('wxWebLogin',puserTempId,puserTempToken) lUser = User.objects.get(UserTempId=puserTempId) if lUser.verifyUserTempToken(puserTempToken): """ resultSave,infoSave = lUser.save() if not resultSave: return JsonResponse(GlobalVar.RspFail,infoSave)""" result,infor = LoginStatus(luser=lUser,ltoken=pToken) if result: return JsonResponse(GlobalVar.RspSuccess,'微信用户登录成功') else: return JsonResponse(GlobalVar.RspFail,infor) else: return JsonResponse(GlobalVar.RspFail,'微信用户登录失败') except User.DoesNotExist: return JsonResponse(GlobalVar.RspFail,'微信用户链接可能已经过期') except: return JsonResponse(GlobalVar.RspFail,'微信用户登录异常,请重新登录') else: return JsonResponse(GlobalVar.RspFail,'HTTP方法不支持')
def getToken(refresh=False): global expires_in,access_token,application,url #判断当前是否已经超时 if (datetime.now() - token_time).seconds < expires_in \ and not refresh and not access_token == '': return True,access_token backdata = '' try: #获取token的json字段 postStr = '{"grant_type":"client_credentials",'\ + '"client_id": "YXA6oSm0kJ2OEeW4bge9YoDNxQ","client_secret": "YXA6tGnIfyPAskipCkcUxWTbERT8xDU"}' conn = httplib.HTTPSConnection(host) conn.request('POST', url + '/token' , postStr, headers) """ response示例 { "access_token":"YWMtWY779DgJEeS2h9OR7fw4QgAAAUmO4Qukwd9cfJSpkWHiOa7MCSk0MrkVIco", "expires_in":5184000, #有效时间,秒为单位, 默认是七天,在有效期内是不需要重复获取的 "application":"c03b3e30-046a-11e4-8ed1-5701cdaaa0e4" } """ response = conn.getresponse() backdata = response.read(5000) if response.status >= 400: return False,backdata except: debug('func_im.py->getToken->except:',backdata) return False,'更新环信Token异常' if 'access_token' in backdata and 'expires_in' in backdata: _dict = JsonRequest(backdata) access_token = _dict.get("access_token","") expires_in = int(_dict.get('expires_in','5184000')) application = _dict.get("application","") if access_token != "": #更新headers headers['Authorization'] = 'Bearer ' + access_token return True,access_token else: return False,backdata else: return False,backdata
def uploadFileTemp(request): if request.method == 'POST': postStr = JsonRequest(request.body) pUpload = postStr.get('Upload','') pIsPublic = postStr.get('IsPublic','') pType = postStr.get('Type','') if pUpload == 'True' or pUpload == 'true': #文件上传只针对登录用户 #判断用户是否登录,登录用户才具备查询权限,并返回当前登录用户 result,lUser = LoginStatus(ltoken=get_token(request)) if not result: #print 'not login',get_token(request),loginUser infor = lUser return JsonResponse(GlobalVar.RspOffLine,infor) lFileTemp = fileTemp( idUser = lUser, IsPublic = pIsPublic ) result,token = lFileTemp.getUlToken(pType) if result: return JsonResponse(token) else: return JsonResponse(GlobalVar.RspFail,token) else: return JsonResponse(GlobalVar.RspFail,'缺少Upload参数') elif request.method == 'GET': #返回下载链接 filename = request.GET.get('FileName','') debug('views_common.py -> uploadFileTemp-> GET filename:',filename) if filename == '': return JsonResponse(GlobalVar.RspFail,'') try: lFileTemp = fileTemp.objects.filter(_FILE_Temp__startswith=filename) if lFileTemp.count() <= 0: return JsonResponse(GlobalVar.RspFail,'文件不存在') info = lFileTemp[0].getFileUrl(colName='_FILE_Temp') if info != '': return JsonResponse({"url":info}) else: return JsonResponse(GlobalVar.RspFail,'获取下载凭证失败') except Exception,ex: return JsonResponse(GlobalVar.RspFail,ex)
def sendSysMsg(target_type=globalvar.target_type.users,target='["test"]',typePara="system",action="test",fromPara="admin",ext=""): #Token刷新,如果获取失败,则返回 result,info = getToken() if not result: return False,info backdata = '' try: if ext is None or ext == '': ext = '{"reservs":"保留"}' # 添加朋友的json字段 #users 给用户发消息, chatgroups 给群发消息, chatrooms 给聊天室发消息 #一个用户u1或者群组, 也要用数组形式 ['u1'], 给用户发送时数组元素是用户名,给群组发送时数组元素是groupid #表示消息发送者, 无此字段Server会默认设置为"from":"admin",有from字段但值为空串("")时请求失败 #扩展属性, 由app自己定义.可以没有这个字段,但是如果有,值不能是“ext:null“这种形式,否则出错 postStr = '{' +\ '"target_type":"' + target_type + '", '+\ '"target":"'+ target +'",'+ \ '"msg":{"type":"' + typePara + '", "action":"' + action +'"},'+\ '"from":"' + fromPara + '",' +\ '"ext":' + ext + '}' conn = httplib.HTTPSConnection(host) debug('func_im.py->sendSysMsg->postStr:', postStr) conn.request('POST', url + '/messages/', postStr, headers) """ { "action" : "post", "application" : "4d7e4ba0-dc4a-11e3-90d5-e1ffbaacdaf5", "uri" : "https://a1.easemob.com/easemob-demo/chatdemoui", "entities" : [ ], "data" : { "testb" : "success", "testc" : "success" }, "timestamp" : 1415167842297, "duration" : 4, "organization" : "easemob-demo", "applicationName" : "chatdemoui" } """ response = conn.getresponse() backdata = response.read(5000) if response.status >= 400: debug('func_im.py->getBlocks->error:',response.status) return False,backdata else: _dict = JsonRequest(backdata) data = _dict.get('data',[]) return True,data except: print('func_im.py->getBlocks->except:', backdata) return False, '获取黑名单异常'
def getHxUser(username): #Token刷新,如果获取失败,则返回 result,info = getToken() if not result: return False,info backdata = '' try: # 添加朋友的json字段 postStr = '{}' conn = httplib.HTTPSConnection(host) debug('func_im.py->getUser->postStr:', postStr) conn.request('GET', url + '/users/' + username , postStr, headers) """ { "action" : "get", "application" : "4d7e4ba0-dc4a-11e3-90d5-e1ffbaacdaf5", "params" : { }, "path" : "/users", "uri" : "https://a1.easemob.com/easemob-demo/chatdemoui/users/ywuxvxuir6", "entities" : [ { "uuid" : "628a88ba-dfce-11e3-8cac-51d3cb69b303", "type" : "user", "created" : 1400556326075, "modified" : 1400556326075, "username" : "ywuxvxuir6", "activated" : true } ], "timestamp" : 1409574716897, "duration" : 57, "organization" : "easemob-demo", "applicationName" : "chatdemoui" } """ response = conn.getresponse() backdata = response.read(5000) if response.status >= 400: debug('func_im.py->getUser->error:',response.status) return False,backdata else: _dict = JsonRequest(backdata) data = _dict.get('entities',[]) if len(data) == 1: uuid = data[0].get('uuid','') if uuid == '': return False,'获取到的uuid为空' else: return True,uuid else: debug('func_im.py->getFriends->get Uuid fail:', backdata) return False,'获取Uuid失败' except Exception,ex: debug('func_im.py->getFriends->error:', ex) return False, '获取用户信息异常'
def wxticket(request): if request.method == 'GET': #不支持GeT方法 return JsonResponse(GlobalVar.RspFail) elif request.method == 'POST': data = JsonRequest(request.body); url = data.get('url','') debug('wxticket',url) ret = get_js_wx_config(url) return JsonResponse(ret) else: return JsonResponse(GlobalVar.RspFail)
def wxLogin(request): #【1】如果方法是Post,提交验证码和电话号码 if request.method == 'POST': wxLogin = JsonRequest(request.body) #pCode = wxLogin.get('code','') pToken = get_token(request) pMsg = wxLogin.get('code','') #【1】用户存在,绑定微信相关id到用户上,并更新用户信息 try: #【1.1】根据电话号码,验证码进行验证,同时会判断该用户是不是已经绑定微信用户 #如果已经绑定,暂时不先解绑,直接覆盖绑定 result1,info1,lUser = loginBest(GlobalVar.LoginWeiXinBond,wxLogin,pToken) #身份校验,验证码比对不通过 if not result1: return JsonResponse(GlobalVar.RspFail,info1) debug('wxLogin','Verify Code is OK') #【1.2】拉取微信用户信息 #如果该用户已经绑定到某个用户的电话号码,需要先解绑,根据openid等查找用户是不是已经绑定 resultBond,inforToken,infoUser = get_weixin_user_first(pMsg) if not resultBond: debug('wxLogin','get weixin user info error',inforToken) return JsonResponse(GlobalVar.RspFail,inforToken) #【1.3】 #【1.4】根据微信用户的信息和数据库中的用户信息进行合并绑定 #lUser=User.objects.get(PhoneNumber=pPhoneNumber) rusult2,infor2 = lUser.wxBond(inforToken,infoUser) if rusult2: #绑定成功,需要上线微信用户 result,infor = LoginStatus(luser=lUser,ltoken=get_token(request)) #不判断登录状态,没有登录成功也不需要重复绑定 """ if result: return JsonResponse(GlobalVar.RspSuccess,infor2) else: return JsonResponse(GlobalVar.RspFail,infor) """ return JsonResponse(GlobalVar.RspSuccess,infor2) else: return JsonResponse(GlobalVar.RspFail,infor2) #【2】用户不存在,直接新注册用户 except Exception,ex: debug('views_weixin->wxLogin->error:',ex) return JsonResponse(GlobalVar.RspFail,'绑定过程发生异常')
def GetCode(request): #【1】如果方法是Post,则为获取验证码的步骤 if request.method == 'POST': try: lPhone = JsonRequest(request.body) pPhoneNumber = lPhone.get('PhoneNumber','') #生成验证码并下发到手机,响应客户端 result,info = getVerifyCode(pPhoneNumber) if result: return JsonResponse(GlobalVar.RspSuccess,info) else: return JsonResponse(GlobalVar.RspFail,info) except Exception,ex: debug('views_login.py->GetCode->error',ex) return JsonResponse(GlobalVar.RspFail,'获取验证码异常')
def TaskFlowHandle(request): #登录用户才能操作 #判断用户是否登录,登录用户才具备查询权限,并返回当前登录用户 result,lUser = LoginStatus(ltoken=get_token(request)) if not result: #print 'not login',get_token(request),loginUser infor = lUser return JsonResponse(GlobalVar.RspOffLine,infor) #【1】如果方法是Post,分三种场景:非管理员申请加入班级;管理员拉人进入班级;管理员处理加入班级请求 if request.method == 'POST': params = JsonRequest(request.body) pType = params.get('Type','NoType') return taskTable.get(pType)(params,lUser) elif request.method == 'GET': pGetType = request.GET.get('GetType','ToDO') page = int(request.GET.get('page',1)) onePageCount = int(request.GET.get('onePageCount',20)) #待处理的任务 if pGetType == 'ToDO': pTaskFlows = TaskFlow.objects.filter(idOwner=lUser).filter(done=False) #我发起的任务 elif pGetType == 'myCreate': pTaskFlows = TaskFlow.objects.filter(idCreateUser=lUser) #我参与的任务 elif pGetType == 'myOwner': pTaskFlows = TaskFlow.objects.filter(idOwner=lUser) else: pTaskFlows = None if pTaskFlows is None or pTaskFlows.count() <= 0: return JsonResponse(GlobalVar.RspFail,'查询结果为空') else: start,end = getPageDataStart(pTaskFlows.count(),page,onePageCount) return JsonResponse(pTaskFlows[start:end].values(*GlobalVar.TableFields.TaskFields)) else: return JsonResponse(GlobalVar.RspFail,'仅支持POST和GET方法')
def getFriends(username): #Token刷新,如果获取失败,则返回 result,info = getToken() if not result: return False,info backdata = '' try: # 添加朋友的json字段 postStr = '{}' conn = httplib.HTTPSConnection(host) debug('func_im.py->getFriends->postStr:', postStr) conn.request('GET', url + '/users/' + username + '/contacts/users', postStr, headers) """ { "action" : "get", "application" : "4d7e4ba0-dc4a-11e3-90d5-e1ffbaacdaf5", "params" : { }, "uri" : "https://a1.easemob.com/easemob-demo/chatdemoui/users/v3y0kf9arx/contacts/users", "entities" : [ ], "data" : [ "88888" ], "timestamp" : 1409737366071, "duration" : 45, "organization" : "easemob-demo", "applicationName" : "chatdemoui" } """ response = conn.getresponse() backdata = response.read(5000) if response.status >= 400: debug('func_im.py->getFriends->error:',response.status) return False,backdata else: _dict = JsonRequest(backdata) data = _dict.get('data',[]) return True,data except: print('func_im.py->getFriends->except:', backdata) return False, '获取好友列表异常'
def getUserInfoFromHx(request): #判断用户是否登录,登录用户才具备查询权限,并返回当前登录用户 result,loginUser = LoginStatus(ltoken=get_token(request)) if not result: #print 'not login',get_token(request),loginUser infor = loginUser return JsonResponse(GlobalVar.RspOffLine,infor) if request.method == 'GET': phxUserName = request.GET.get('hxUserName','') if phxUserName == '': return JsonResponse(GlobalVar.RspFail,'环信用户名不能为空') try: #temp1 = User.objects.filter(PhoneNumber=pKey) #temp2 = User.objects.filter(UserName__contains=pKey) fields = ['id','PhoneNumber','UserName','_FILE_HeaderFigure','IsDelete','Nick','hxUserName'] lUser = User.objects.values(*GlobalVar.TableFields.Userfields).get(hxUserName=phxUserName) #lUser = lUser lUser = GetCommonDlList([lUser]) #lUser = lUser.values(*fields) return JsonResponse(lUser) except User.DoesNotExist: return JsonResponse(GlobalVar.RspFail,'未查找到该环信用户的信息') except: return JsonResponse(GlobalVar.RspFail,'出现异常') elif request.method == "POST": _strReq = JsonRequest(request.body) pHxUserNameList = _strReq.get('hxUserNameList',[]) debug('views_person->getUserInfoFromHx->_strReq:',_strReq) debug('views_person->getUserInfoFromHx->pHxUserNameList:',pHxUserNameList) try: lUser = User.objects.values(*GlobalVar.TableFields.Userfields).filter(hxUserName__in=pHxUserNameList) if len(lUser) == 0: return JsonResponse(GlobalVar.RspSuccess, '查询结果为空') lUser = GetCommonDlList(lUser) return JsonResponse(lUser) except: return JsonResponse(GlobalVar.RspFail,'出现异常') return JsonResponse(GlobalVar.RspFail,'方法不支持')
def wxRelease(request): #【1】如果方法是Post,提交验证码和电话号码 if request.method == 'POST': wxLogin = JsonRequest(request.body) try: #【1】使用验证码登录 result1,info1,lUser = loginBest(GlobalVar.LoginWeiXinRelease,wxLogin) #身份校验,验证码比对不通过直接返回,包括用户不存在场景 if not result1: return JsonResponse(GlobalVar.RspFail,info1) #【2】验证登录通过之后,根据返回的用户释放微信绑定 #lUser=User.objects.get(PhoneNumber=pPhoneNumber) rusult2,infor2 = lUser.wxRelease() debug('wxRelease',rusult2,infor2) #依据电话号码来查找对应的csrfToken pPhonNumber = wxLogin.get('PhoneNumber','') lUserToken = UserToken.objects.filter(idUser__PhoneNumber=pPhonNumber) #解除绑定之后,还需要将csrfToken清除下线 if lUserToken.count() > 0: lUserToken.delete() if rusult2: return JsonResponse(GlobalVar.RspSuccess,infor2) else: return JsonResponse(GlobalVar.RspFail,infor2) #【2】其他异常 except: return JsonResponse(GlobalVar.RspFail,'解绑异常') #微信采用GET方法跳转 elif request.method == 'GET': return JsonResponse(GlobalVar.RspFail,'不支持操作') else: return JsonResponse(GlobalVar.RspFail,'不支持操作')
def response_handle(response=''): try: _dict = JsonRequest(response) if 'errcode' in response: errcode = str(_dict.get('errcode','')) #0 - 成功 if errcode == '0' or errcode == '': return '0',_dict #40014 - 不合法的access_token elif errcode == '40014' or errcode == '41001'\ or errcode == '42001': #print 'response_handle:get token',errcode get_access_token(True) else: #print 'response_handle:do nothing',errcode pass return errcode,_dict else: return '0',_dict except: return '-999',{}
def getBlocks(username): #Token刷新,如果获取失败,则返回 result,info = getToken() if not result: return False,info backdata = '' try: # 添加朋友的json字段 postStr = '{}' conn = httplib.HTTPSConnection(host) debug('func_im.py->getBlocks->postStr:', postStr) conn.request('GET', url + '/users/' + username + '/blocks/users', postStr, headers) """ { "action" : "get", "uri" : "https://a1.easemob.com/easemob-demo/chatdemoui/users/v3y0kf9arx/blocks/users", "entities" : [ ], "data" : [ "stliu2" ], "timestamp" : 1412824409803, "duration" : 36 } """ response = conn.getresponse() backdata = response.read(5000) if response.status >= 400: debug('func_im.py->getBlocks->error:',response.status) return False,backdata else: _dict = JsonRequest(backdata) data = _dict.get('data',[]) return True,data except: print('func_im.py->getBlocks->except:', backdata) return False, '获取黑名单异常'
def register(username,password): #Token刷新,如果获取失败,则返回 result,info = getToken() if not result: return False,info backdata = '' try: # 获取token的json字段 postStr = '{"username":"******",' \ + '"password": "******"}' conn = httplib.HTTPSConnection(host) conn.request('POST', url + '/users', postStr, headers) """ response示例 { "action" : "post", "application" : "a2e433a0-ab1a-11e2-a134-85fca932f094", "params" : { }, "path" : "/users", "uri" : "https://a1.easemob.com/easemob-demo/chatdemoui/users", "entities" : [ { "uuid" : "7f90f7ca-bb24-11e2-b2d0-6d8e359945e4", "type" : "user", "created" : 1368377620796, "modified" : 1368377620796, "username" : "jliu", "activated" : true } } ], "timestamp" : 1368377620793, "duration" : 125, "organization" : "easemob-demo", "applicationName" : "chatdemo" } """ response = conn.getresponse() backdata = response.read(5000) if response.status >= 400: debug('func_im.py->register->backdata:',backdata) return False,backdata except: print('func_im.py->register->except:', backdata) return False, '更新环信Token异常' if 'uuid' in backdata and 'activated' in backdata: _dict = JsonRequest(backdata) tempapplication = _dict.get("application", "") if tempapplication != application: return False,'非法应用' entities = _dict.get("entities",None) if entities is None or len(entities) <= 0: return False,'数据为空' uuid = entities[0].get("uuid","") if uuid == "": return False,"uuid生成失败" else: return True,uuid else: print('func_im.py->register->backdata:', backdata) return False, backdata
""" return JsonResponse(GlobalVar.RspSuccess,infor2) else: return JsonResponse(GlobalVar.RspFail,infor2) #【2】用户不存在,直接新注册用户 except Exception,ex: debug('views_weixin->wxLogin->error:',ex) return JsonResponse(GlobalVar.RspFail,'绑定过程发生异常') #微信采用GET方法跳转 elif request.method == 'GET': wxLogin = JsonRequest(request.body) #pPhoneNumber = wxLogin.get('PhoneNumber','') code = wxLogin.get('code','') state = wxLogin.get('state','') else: pass """ #微信 直接 解除绑定,不用微信直接解绑,可以通过电话号码解绑 def wxLogout(request): if request.method == 'GET': code = request.GET.get('code','') #获取openId
def UserDetail(request): #判断用户是否登录,登录用户才具备查询权限,并返回当前登录用户 result,loginUser = LoginStatus(ltoken=get_token(request)) if not result: #print 'not login',get_token(request),loginUser infor = loginUser return JsonResponse(GlobalVar.RspOffLine,infor) if request.method == 'POST': _strReq = JsonRequest(request.body) #print 'Post Request:', _strReq; lPhoneNumber = _strReq.get('PhoneNumber','') lid = _strReq.get('id','') try: if lPhoneNumber.strip() is '' and lid.strip() is '': lUser = loginUser #优先用id去获取用户 elif lid.strip() is not '': lUser = User.objects.get(id=lid) else: lUser = User.objects.get(PhoneNumber=lPhoneNumber) #普通登录用户只能修改自身的信息 if not lUser.id == loginUser.id: #print 'LoginUser:'******' UserModify:',lUser.id #指定Super账号可以修改角色字段,定义管理员 return JsonResponse(GlobalVar.RspFail,'没有权限修改相关信息') result,infor = lUser.UserUpdate(_strReq) debug("UserDetail:",result,infor) #可能携带头像上传的UlTokenl if result: return JsonResponse(infor,DateTime2Str(lUser.ModifyTime)) else: return JsonResponse(GlobalVar.RspFail,'保存失败') except User.DoesNotExist: return JsonResponse(GlobalVar.RspFail,'该用户不存在') except: return JsonResponse(GlobalVar.RspFail,'保存过程出现异常,请重新提交') elif request.method == 'GET': try: lid = request.GET.get('id','') lPhoneNumber = request.GET.get('PhoneNumber','') lModiryTime = request.GET.get('ModifyTime',''); debug( 'lPhoneNumber:',lPhoneNumber.strip(),',lid:',lid.strip(),'.') #id和电话号码均为空,无法检索用户 """if lid.strip() is '' and lPhoneNumber.strip() is '': #print 'setup1' return JsonResponse(GlobalVar.RspFail,'没有选择有效的用户')""" #返回查询结果,优先使用id查询 lUser = None if lid.isdigit(): lUser = User.objects.get(id=lid)#.values(*GlobalVar.TableFields.Userfields) elif lPhoneNumber.isdigit(): #print 'enter the user query according the phone number' lUser = User.objects.get(PhoneNumber=lPhoneNumber)#.values(*GlobalVar.TableFields.Userfields) else: lUser = loginUser #判断是否是最新结果 if lUser.isNew(lModiryTime): return JsonResponse(GlobalVar.RspNew,'已经是最新的拷贝') #pManager = User.objects.filter(id=pClass.Owner.id).values(*GlobalVar.TableFields.Userfields) #头像下载特殊处理 """ if not isSrc(lUser._FILE_HeaderFigure): name = lUser._FILE_HeaderFigure.split(GlobalVar.InterStr)[0] result,infor = GetCommonDlItem(name) #如果发生异常,infor将为空,用户不需要下载头像""" lUser._FILE_HeaderFigure = lUser.getFileUrl() return JsonResponse(lUser) #用户不存在 except User.DoesNotExist: #print 'setup2' return JsonResponse(GlobalVar.RspFail,'该用户不存在') except Exception,ex: # pass return JsonResponse(GlobalVar.RspFail,ex)