def authenticate(email, password): """ 用户登录,登录成功返回token,写将登录时间写入数据库;登录失败返回失败原因 :param password: :return: json """ userInfo = Users().getOne( {Users.email == email}, 'id desc', ('email', 'password', 'id', 'nick_name', 'head_img')) if (userInfo is None): return Utils.formatError(Code.BAD_REQUEST, '找不到用户') else: if (Users.check_password(userInfo['password'], password)): updated_at = int(time.time()) Users().edit({'updated_at': updated_at}, {Users.email == email}) token = UsersAuthJWT.encode_auth_token(userInfo['id'], updated_at) userInfo.pop('password') #删除密码 return Utils.formatBody( { 'token': token.decode(), 'user': userInfo }, '登陆成功') else: return Utils.formatError(Code.BAD_REQUEST, '密码不正确')
def add(params,user_info): ''' 添加通讯录 ''' if params['focused_user_id'] == user_info['data']['id']: return Utils.formatError(Code.BAD_REQUEST,msg='无法添加自己为新朋友') filters = { AddressBook.focused_user_id == params['focused_user_id'], AddressBook.be_focused_user_id == user_info['data']['id'] } addressBookData = AddressBook().getOne(filters) if(addressBookData == None): # 加入房间号 room_uuid = Utils.unique_id() # 建立通讯录关系 status = AddressBook.addRoomAndAddressBook( room_uuid, params['focused_user_id'], user_info['data']['id']) if status == False: return Utils.formatError(Code.BAD_REQUEST,msg='添加失败') #回复被添加用户 socketio.emit('beg', Utils.formatBody({ 'action':'beg_add_success', 'focused_user_id' : user_info['data']['id'] }), namespace='/room', room='@broadcast.'+str(params['focused_user_id'])) #添加后同步房间 addressBookData = AddressBook.get(room_uuid) for item in addressBookData: roomList = AddressBook.getRoomList(item.be_focused_user_id)['data'] socketio.emit('room',Utils.formatBody(roomList), namespace="/room",room='@broadcast.'+str(item.be_focused_user_id)) return Utils.formatBody({},msg='添加成功') return Utils.formatError(Code.BAD_REQUEST,msg='已添加')
def add(self, data=[]): #添加 if 'update_time' in data.keys(): data['update_time'] = int(time.time()) #判断用户名 if 'name' in data.keys(): filters = {Admin.delete_time == 0, Admin.name == data['name']} adminData = Admin().getOne(filters, 'add_time desc') if adminData != None: return Utils.formatError(CONST['CODE']['ERROR']['value'], '用户名已经存在') #判断手机号码 if 'mobile' in data.keys(): filters = {Admin.delete_time == 0, Admin.mobile == data['mobile']} admin = Admin().getOne(filters, 'add_time desc') if admin: return Utils.formatError(CONST['CODE']['ERROR']['value'], '手机号码已经存在') #判断邮箱 if 'email' in data.keys(): filters = {Admin.delete_time == 0, Admin.email == data['email']} admin = Admin().getOne(filters, Admin.add_time.desc()) if admin: return Utils.formatError(CONST['CODE']['ERROR']['value'], '邮箱已经存在') #生成一个md5对象 m1 = hashlib.md5() #使用md5对象里的update方法md5转换 m1.update(data['pwd'].encode("utf-8")) data['pwd'] = m1.hexdigest() res = Admin().add(data) if res: return Utils.formatBody(msg='添加成功') return Utils.formatError(CONST['CODE']['ERROR']['value'], '添加失败')
def adminChat(message: dict) -> dict: admin_user_info = UsersAuthJWT().adminIdentify( message['Authorization']) if isinstance(admin_user_info, str): return Utils.formatError(CONST['CODE']['ERROR_AUTH_CHECK_TOKEN_FAIL']['value'], admin_user_info) # 整合数据信息 filters = { Admin.id == admin_user_info['data']['id'], } admin_user_info = Admin().getOne(filters) default_img_data = Config().getOne( {Config.type == 'img', Config.code == 'default.img', Config.status == 1}) if default_img_data == None: default_img = 'static/img/about/python.jpg' else: default_img = default_img_data['config'] admin_user_info['nick_name'] = '系统管理-'+admin_user_info['nick_name'] admin_user_info['head_img'] = default_img # 这里后期改成配置的 # 使用0作为系统id msg = message['data']['msg'] room_uuid = message['data']['room_uuid'] Type = message['data']['type'] room_data = Room.get(room_uuid) if room_data == None: return Utils.formatError(CONST['CODE']['ROOM_NO_EXIST']['value'], "房间不存在") room_type = room_data.type created_at = int(time.time()) save_action = message['data']['save_action'] return ChatService.sendChatMessage(msg, room_uuid, Type, room_data, room_type, created_at, save_action, admin_user_info, 1)
def register(self, params): userData = Users().getOne({Users.email == params['email']}) if (userData == None): #昵称首字母 isChinese = re.compile(u"[\u4e00-\u9fa5]+") isEnglish = re.compile('[a-zA-Z]') nickNameFirstWord = params['nickName'][0] if isChinese.search(nickNameFirstWord): first_word = Pinyin().get_initial(nickNameFirstWord) elif isEnglish.search(nickNameFirstWord): first_word = nickNameFirstWord.upper() else: first_word = '#' data = { 'email': params['email'], 'password': Users.set_password(params['password']), 'nick_name': params['nickName'], 'head_img': params['headImg'], 'first_word': first_word, 'created_at': time.time(), 'updated_at': time.time() } user = Users().add(data) if user == False: return Utils.formatError(Code.BAD_REQUEST, '注册失败') else: result = UsersAuthJWT.authenticate(params['email'], params['password']) return result return Utils.formatError(Code.BAD_REQUEST, '注册失败') return Utils.formatError(Code.BAD_REQUEST, '账号已注册')
def beg(params, user_info): if user_info['data']['id'] == params['be_focused_user_id']: return Utils.formatError(CONST['CODE']['BAD_REQUEST']['value'], '无法添加自己为新朋友') addressBookdata = AddressBook.getAdddressBookByFocusedUserId( user_info['data']['id'], params['be_focused_user_id']) if addressBookdata != None: return Utils.formatError(CONST['CODE']['BAD_REQUEST']['value'], '已添加') msg_uuid = Utils.unique_id() userData = Users().getOne({Users.id == user_info['data']['id']}) data = { 'data': userData, 'action': 'beg_add', 'msg_uuid': msg_uuid, 'be_focused_user_id': params['be_focused_user_id'], 'focused_user_id': user_info['data']['id'] } socketio.emit('beg', Utils.formatBody(data), namespace='/api', room='@broadcast.' + str(params['be_focused_user_id'])) #,callback=success) #只缓存最新的一条 cache.set('@broadcast.beg' + str(params['be_focused_user_id']), data) return Utils.formatBody({}, msg='发送成功')
def inner_wrappar(*args, **kwargs): if 'Authorization' in args[0].keys(): result = UsersAuthJWT().adminIdentify(args[0]['Authorization']) else: return Utils.formatError(CONST['CODE']['ERROR_AUTH_CHECK_TOKEN_FAIL']['value'], '令牌失效') kwargs['user_info'] = result if isinstance(result, str): # socketio.emit(name,Utils.formatError(CONST['CODE']['ERROR']['value']_AUTH_CHECK_TOKEN_FAIL, '令牌失效'), room='@api.'+str(request.sid)) return Utils.formatError(CONST['CODE']['ERROR_AUTH_CHECK_TOKEN_FAIL']['value'], '令牌失效') res = func(*args, **kwargs) return res
def edit(self, data, filters = {}): if 'update_time' in data.keys(): data['update_time'] = time.time() adminData = Admin().getOne(filters, 'add_time desc') if adminData == None: return Utils.formatError(Code.ERROR, '用户不存在') #判断用户名 if 'name' in data.keys(): filters = { Admin.delete_time == 0, Admin.name == data['name'], Admin.id != adminData['id'] } admin = Admin().getOne(filters, 'add_time desc') if admin != None: return Utils.formatError(Code.ERROR, '用户名已经存在') #判断手机号码 if 'mobile' in data.keys(): filters = { Admin.delete_time == 0, Admin.mobile == data['mobile'], Admin.id != adminData['id'] } admin = Admin().getOne(filters, 'add_time desc') if admin != None: return Utils.formatError(Code.ERROR, '手机号码已经存在') #判断邮箱 if 'email' in data.keys(): filters = { Admin.delete_time == 0, Admin.email == data['email'], Admin.id != adminData['id'] } admin = Admin().getOne(filters, Admin.add_time.desc()) if admin != None: return Utils.formatError(Code.ERROR, '邮箱已经存在') if 'pwd' in data.keys(): #生成一个md5对象 m1 = hashlib.md5() #使用md5对象里的update方法md5转换 m1.update(data['pwd'].encode("utf-8")) data['pwd'] = m1.hexdigest() res = Admin().edit(data, filters) if res==True: return Utils.formatBody(msg='编辑成功') return Utils.formatError(Code.ERROR, '编辑失败', 0)
def login(self, data): name = data['name'] #生成一个md5对象 m1 = hashlib.md5() #使用md5对象里的update方法md5转换 m1.update(data['pwd'].encode("utf-8")) pwd = m1.hexdigest() #用户名/邮箱/手机登录 filters = { Admin.name == name, Admin.pwd == pwd, Admin.delete_time == 0 } admin = Admin().getOne(filters, 'add_time desc') if admin == None: filters = { Admin.email == name, Admin.pwd == pwd, Admin.delete_time == 0 } admin = Admin().getOne(filters, 'add_time desc') if admin == None: filters = { Admin.mobile == name, Admin.pwd == pwd, Admin.delete_time == 0 } admin = Admin().getOne(filters, 'add_time desc') if admin != None: #更新登录时间 filters = {Admin.id == admin['id']} update_time = int(time.time()) Admin().edit({Admin.update_time: update_time}, filters) token = UsersAuthJWT.encode_auth_token(admin['id'], update_time) return Utils.formatBody({'token': token, 'user': admin}) return Utils.formatError(CONST['CODE']['ERROR']['value'])
def inner_wrappar(*args, **kwargs): result = UsersAuthJWT().adminIdentify(request.headers.get('Authorization')) kwargs['user_info'] = result if isinstance(result, str): return make_response(jsonify(Utils.formatError(CONST['CODE']['ERROR_AUTH_CHECK_TOKEN_FAIL']['value'], result))) res = func(*args, **kwargs) return res
def inner_wrappar(*args, **kwargs): result = UsersAuthJWT().identify(args[0]['Authorization']) kwargs['user_info'] = result if isinstance(result, str): return Utils.formatError( Code.ERROR_AUTH_CHECK_TOKEN_FAIL, '令牌失效' ) #socketio.emit(name,Utils.formatError(Code.ERROR_AUTH_CHECK_TOKEN_FAIL, '令牌失效'), room='@api.'+str(request.sid)) res = func(*args, **kwargs) return res
def create(params, user_info): # 加入房间号 data = ChatService().groupChatCreate(params, user_info) if data: #添加后同步房间 user_room_relation_data = Utils.db_l_to_d(UserRoomRelation.get(data['room_uuid'])) for item in user_room_relation_data: roomList = UserRoomRelation.getRoomList(item['user_id']) socketio.emit('groupRoom', Utils.formatBody(roomList), namespace='/api', room='@broadcast.'+str(item['user_id'])) return Utils.formatBody(data, msg='创建成功') return Utils.formatError(CONST['CODE']['BAD_REQUEST']['value'],msg='创建失败')
def create(user_info, params): # 加入房间号 data = ChatService().groupChatCreate(user_info, params) if data: #添加后同步房间 user_room_relation_data = Utils.db_l_to_d(UserRoomRelation.get(data['room_uuid'])) for item in user_room_relation_data: roomList = UserRoomRelation.getRoomList(item['user_id'])['data'] socketio.emit('groupRoom', Utils.formatBody(roomList), namespace='/room', room='@broadcast.'+str(item['user_id'])) return Utils.formatBody(data, msg='创建成功') return Utils.formatError(Code.BAD_REQUEST,msg='创建失败')
def register(params): userData = Users().getOne({Users.email == params['email']}) if (userData == None): #昵称首字母 isChinese = re.compile(u"[\u4e00-\u9fa5]+") isEnglish = re.compile('[a-zA-Z]') nickNameFirstWord = params['nickName'][0] nowTime = time.time() if isChinese.search(nickNameFirstWord): first_word = Pinyin().get_initial(nickNameFirstWord) elif isEnglish.search(nickNameFirstWord): first_word = nickNameFirstWord.upper() else: first_word = '#' data = { 'email': params['email'], 'password': Users.set_password(params['password']), 'nick_name': params['nickName'], 'head_img': params['headImg'], 'first_word': first_word, 'created_at': nowTime, 'updated_at': nowTime } user = Users().add(data) if user == False: return Utils.formatError(CONST['CODE']['BAD_REQUEST']['value'], '注册失败') else: result = UsersAuthJWT.authenticate(params['email'], params['password']) # 发送延时推广进群广告 invite = Invite() invite.setAction("invite") invite.setId(result['data']['user']['id']) # 延时2分钟推送 delayQueue.product(invite.__dict__, 120) return result return Utils.formatError(CONST['CODE']['BAD_REQUEST']['value'], '账号已注册')
def adminCreateRoom(message): admin_user_info = UsersAuthJWT().adminIdentify( message['Authorization']) if isinstance(admin_user_info, str): return Utils.formatError(CONST['CODE']['ERROR_AUTH_CHECK_TOKEN_FAIL']['value'], admin_user_info) filters = { Admin.id == admin_user_info['data']['id'], } admin_user_info = Admin().getOne(filters) filters = { AddressBook.be_focused_user_id == message['user_id'], AddressBook.focused_user_id == admin_user_info['id'], AddressBook.type == 1 } addressBookInfo = AddressBook().getOne(filters) if addressBookInfo == None: room_uuid = Utils.unique_id() # 建立通讯录关系 status = AddressBook.adminAddRoomAndAddressBook( room_uuid, admin_user_info, message['user_id']) if status == False: return Utils.formatError(CONST['CODE']['BAD_REQUEST']['value'], msg='添加失败') # 添加后同步房间 addressBookData = AddressBook.get(room_uuid) for item in addressBookData: roomList = AddressBook.getRoomList( item.be_focused_user_id)['list'] if item['type'] == CONST['ADDRESSBOOK']['ADMIN']['value']: socketio.emit('room', Utils.formatBody( roomList), namespace="/api", room='@broadcast.'+str(item.be_focused_user_id)) else: socketio.emit('room', Utils.formatBody( roomList), namespace="/api", room='@broadcast.'+str(item.be_focused_user_id)) else: room_uuid = addressBookInfo['room_uuid'] return Utils.formatBody({'room_uuid': room_uuid})
def chat(message, user_info): """ @param dict message @param dict user_info @return dict """ msg = message['data']['msg'] room_uuid = message['data']['room_uuid'] Type = message['data']['type'] room_data = Room.get(room_uuid) if room_data == None: return Utils.formatError(CONST['CODE']['ROOM_NO_EXIST']['value'], "房间不存在") room_type = room_data.type created_at = message['data']['created_at'] save_action = message['data']['save_action'] user_data = Users().getOne({Users.id == user_info['data']['id']}) return ChatService.sendChatMessage(msg, room_uuid, Type, room_data, room_type, created_at, save_action, user_data)
def upload(params): filename = secure_filename(params['name']) base64Data = params['dataUrl'].split(',')[1] if (base64Data and Utils.allowed_file(filename)): file_suffix = params['name'].split('.')[1] path = UPLOAD_FOLDER + Utils.unique_id() + '.' + file_suffix full_path = os.getcwd() + path f = open(full_path, 'wb') data = base64.b64decode(base64Data) f.write(data) #f.write(params['arrayBuffer']) f.close return Utils.formatBody({ 'path': path, 'name': filename }, msg='上传成功') return Utils.formatError(Code.BAD_REQUEST, '文件类型不允许')
def sendChatMessage(msg, room_uuid, Type, room_data, room_type, created_at, save_action, user_data, user_type=0): data = { 'msg': msg, 'name': user_data['nick_name'], 'user_id': user_data['id'], 'type': Type, 'head_img': user_data['head_img'], 'room_uuid': room_uuid, 'created_at': created_at, 'read_status': 0, 'user_type': user_type } if room_data != None and room_type == CONST['ROOM']['ADMIN']['value']: address_book_data = AddressBook.get(room_uuid) # 发送消息 socketio.emit('chat', Utils.formatBody(data), namespace='/api', room=room_uuid) # 视频消息则直接返回 if Type == CONST['CHAT']['VIDEO']['value']: return # 如果是云端存储则记录,这边判断不判断都存储 # if save_action == CONST['SAVE']['CLOUD']['value']: res = Msg().getOne({Msg.room_uuid == room_uuid, Msg.created_at == created_at, Msg.user_id == user_data['id']}) if res == None: copy_data = data.copy() copy_data['msg'] = json.dumps(msg) copy_data['send_status'] = CONST['STATUS']['SUCCESS']['value'] Msg().add(copy_data) else: copy_data = data.copy() copy_data['msg'] = json.dumps(msg) copy_data['send_status'] = CONST['STATUS']['SUCCESS']['value'] filters = { Msg.name == copy_data['name'], Msg.created_at == copy_data['created_at'], Msg.room_uuid == room_uuid } Msg().edit(copy_data, filters) # 聊天时同步房间信息 Room.updateLastMsgRoom(room_uuid, data, created_at) # 更新聊天提示数字 AddressBook.updateUnreadNumber(room_uuid, user_data['id']) AddressBook.cleanUnreadNumber(room_uuid, user_data['id']) # 更新客户端房间信息 for item in address_book_data: roomList = AddressBook.getRoomList(item.be_focused_user_id) socketio.emit('room', Utils.formatBody( roomList), namespace='/api', room='@broadcast.'+str(item.be_focused_user_id)) if room_data != None and room_type == CONST['ROOM']['ALONE']['value']: address_book_data = AddressBook.get(room_uuid) # 视频消息则直接返回 if Type == CONST['CHAT']['VIDEO']['value']: videoData = data videoData["room_type"] = room_type # 发送消息 for item in address_book_data: if item['be_focused_user_id'] != user_data['id']: emit('video', Utils.formatBody(videoData), room='@broadcast.'+str(item.be_focused_user_id)) return # 发送消息 emit('chat', Utils.formatBody(data), room=room_uuid) # 如果是云端存储则记录,这边判断不判断都存储 # if save_action == CONST['SAVE']['CLOUD']['value']: res = Msg().getOne({Msg.room_uuid == room_uuid, Msg.created_at == created_at, Msg.user_id == user_data['id']}) if res == None: copy_data = data.copy() copy_data['msg'] = json.dumps(msg) copy_data['send_status'] = CONST['STATUS']['SUCCESS']['value'] Msg().add(copy_data) else: copy_data = data.copy() copy_data['msg'] = json.dumps(msg) copy_data['send_status'] = CONST['STATUS']['SUCCESS']['value'] filters = { Msg.name == copy_data['name'], Msg.created_at == copy_data['created_at'], Msg.room_uuid == room_uuid } Msg().edit(copy_data, filters) # 聊天时同步房间信息 Room.updateLastMsgRoom(room_uuid, data, created_at) # 更新聊天提示数字 AddressBook.updateUnreadNumber(room_uuid, user_data['id']) AddressBook.cleanUnreadNumber(room_uuid, user_data['id']) # 更新客户端房间信息 for item in address_book_data: print(AddressBook,item) roomList = AddressBook.getRoomList(item.be_focused_user_id) socketio.emit('room', Utils.formatBody( roomList), namespace='/api', room='@broadcast.'+str(item.be_focused_user_id)) elif room_data != None and room_type == CONST['ROOM']['GROUP']['value']: # 获取用户的权限,如果禁言状态返回错误 filters = { UserRoomRelation.user_id == user_data['id'], UserRoomRelation.room_uuid == room_uuid } selfUserRoomRelationData = UserRoomRelation().getOne(filters) if selfUserRoomRelationData['status'] == CONST['GROUP']['BLOCK']['value']: return Utils.formatError(CONST['CODE']['ERROR']['value'], '禁言中') # 获取群组内用户 user_room_relation_data = UserRoomRelation.get(room_uuid) # 发送消息 emit('chat', Utils.formatBody(data), room=room_uuid) # 如果是云端存储则记录 # if save_action == CONST['SAVE']['CLOUD']['value']: res = Msg().getOne({Msg.room_uuid == room_uuid, Msg.created_at == created_at, Msg.user_id == user_data['id']}) if res == None: copy_data = data.copy() copy_data['msg'] = json.dumps(msg) copy_data['send_status'] = CONST['STATUS']['SUCCESS']['value'] Msg().add(copy_data) else: copy_data = data.copy() copy_data['msg'] = json.dumps(msg) copy_data['send_status'] = CONST['STATUS']['SUCCESS']['value'] filters = { Msg.name == copy_data['name'], Msg.created_at == copy_data['created_at'], Msg.room_uuid == room_uuid } Msg().edit(copy_data, filters) # 聊天时同步房间信息 Room.updateLastMsgRoom(room_uuid, data, created_at) # 更新聊天提示数字 UserRoomRelation.updateUnreadNumber(room_uuid, user_data['id']) UserRoomRelation.cleanUnreadNumber(room_uuid, user_data['id']) # 更新客户端房间信息 for item in user_room_relation_data: roomList = UserRoomRelation.getRoomList(item.user_id) socketio.emit('groupRoom', Utils.formatBody( roomList), namespace='/api', room='@broadcast.'+str(item.user_id)) return Utils.formatBody({'action': "chat", "data": data})