Beispiel #1
0
    def create(self):
        """添加好友"""
        form = CreateFriendForm(data=request.json)
        if not form.validate():
            return {
                'code': RET.SERVERERR,
                'msg': getFlatten(form.errors.values())
            }
        #判断用户是否在重复添加好友
        res = db.session.query(ChatFriend.id).filter(
            ChatFriend.self_id == token.id,
            ChatFriend.friend_id == form.data['friend_id'],
            ChatFriend.is_active == True).first()
        if res:
            return {'code': RET.USERERR, 'msg': '您已经发出过申请了,请去我的申请中查看!'}

        try:
            friend = ChatFriend(
                self_id=token.id,
                friend_id=form.data['friend_id'],
                room=get_room_name(token.id, form.data['friend_id']),
                remark=form.friend_name,  #在form中动态添加的好友名称
                initiator_id=token.id)
            db.session.add(friend)
            db.session.commit()
        except Exception as e:
            return {'code': RET.SERVERERR, 'msg': error_map[RET.SERVERERR]}
        return {
            'code': RET.OK,
            'msg': error_map[RET.OK],
            'data': friend.to_dict()
        }
Beispiel #2
0
    def create(self):
        """
        创建聊天室
        请求:{'name':'xxx'}
        响应:{聊天室完整信息}
        """

        if token.pre != 'user':
            return {'code': RET.ROLEERR, 'msg': '匿名用户不可以创建聊天室!'}

        form = CreateChatRoomForm(data=request.json)
        if form.validate():
            mid_room = ChatUserRoom(chat_room=ChatRoom(
                name=form.name.data,
                create_user=token.id,
                img=form.img.data,
                desc=form.desc.data,
            ),
                                    user_id=token.id,
                                    is_create_user=True)
            try:
                db.session.add(mid_room)
                db.session.commit()
                room = mid_room.chat_room
            except:
                db.session.rollback()
                return {'code': RET.SERVERERR, 'msg': error_map[RET.SERVERERR]}
            return {
                'code': RET.OK,
                'msg': error_map[RET.OK],
                'data': room.to_dict()
            }
        return {'code': RET.PARAMERR, 'msg': getFlatten(form.errors.values())}
Beispiel #3
0
    def post(self):
        """
        * 上传文件接口
        * 请求:{file:文件对象}
        * 响应:{'code':2000,'msg':'ok',url:文件存储后的url}
        """
        form = UploadForm(request.files)
        if not form.validate():
            return {
                'code': RET.PARAMERR,
                'msg': getFlatten(form.errors.values())
            }
        f = form.file.data
        filename = random_filename(f.filename)

        Path = os.path.join(current_app.static_folder, 'upload')
        if not os.path.isdir(Path):
            os.makedirs(Path)
        filePath = os.path.join(Path, filename)
        f.save(filePath)

        #url中文件的路径
        urlFilePath = urljoin('upload/', filename)
        return {
            'code': RET.OK,
            'msg': 'ok',
            'url': url_for('static', _external=True, filename=urlFilePath)
        }
Beispiel #4
0
 def post(self):
     """
     * 新建意见反馈:
     * 请求:{type:1,content:'',contact:'',feedbackImages:[]}
     * 响应:{code:'2000',msg:'ok'}
     """
     form = FeedbackForm(data=request.json)
     if form.validate():
         img_list = [
             FeedbackImages(url=i) for i in form.feedbackImages.data
         ]
         data = {
             'type_id':
             form.data['type'],
             'content':
             form.data['content'],
             'contact':
             form.data.get('contact', ''),
             'user_id':
             token.id,
             'images':
             img_list,
             'image':
             form.feedbackImages.data[0]
             if len(form.feedbackImages.data) > 0 else ''
         }
         try:
             fb = Feedback(**data)
             db.session.add(fb)
             db.session.commit()
         except Exception as ex:
             db.session.rollback()
             return {'code': RET.SERVERERR, 'msg': error_map[RET.SERVERERR]}
         return {'code': RET.OK, 'msg': error_map[RET.OK]}
     return {'code': RET.PARAMERR, 'msg': getFlatten(form.errors.values())}
Beispiel #5
0
 def put(self):
     """
     *修改密码:
     *请求:{pwd:'12345678',newPwd:'1111111','repeatPwd':'11111111'}
     *响应:{code:'2000',msg:'ok'}
     """
     form = PwdForm(data=request.json)
     if form.validate():
         try:
             token.user.pwd = form.newPwd.data
             db.session.commit()
         except:
             db.session.rollback()
             return {'code': RET.SERVERERR, 'msg': error_map[RET.SERVERERR]}
         return {'code': RET.OK, 'msg': error_map[RET.OK]}
     return {'code': RET.PARAMERR, 'msg': getFlatten(form.errors.values())}
Beispiel #6
0
 def put(self):
     """
     * 修改用户个人信息
     * 请求:{area:[{code: "110000",name: "北京市"},{code: "110000",name: "朝阳区"},{code:"110000",name: "望京"}],birth: "1950-01-01",email: "*****@*****.**",sex: "男"}
     * 响应:{完整用户信息}
     """
     form = UserInfoForm(data=request.json)
     if form.validate():
         try:
             for k, v in form.data.items():
                 setattr(token.user, k, v)
         except:
             db.session.rollback()
             return {'code': RET.SERVERERR, 'msg': error_map[RET.SERVERERR]}
         db.session.commit()
         return {'code': RET.OK, 'msg': 'OK', 'data': token.user.to_dict()}
     return {'code': RET.PARAMERR, 'msg': getFlatten(form.errors.values())}
Beispiel #7
0
 def post(self):
     """
     * 注册用户:
     * 请求:{userName:'******',nickName:'xx',pwd:'1234567',checkPwd:'1234567'}
     * 响应:{token:'12345678'}
     """
     form = UserForm(data=request.json)
     if form.validate():
         user = User(**form.data)
         try:
             db.session.add(user)
             token = Token.encryptTk(current_app.config, user.to_dict())
             db.session.commit()
         except:
             db.session.rollback()
             return {'code': RET.SERVERERR, 'msg': error_map[RET.SERVERERR]}
         if not token:
             return {'code': RET.SERVERERR, 'msg': error_map[RET.SERVERERR]}
         return {'code': RET.OK, 'msg': 'OK', 'data': {'token': token}}
     return {'code': RET.PARAMERR, 'msg': getFlatten(form.errors.values())}
Beispiel #8
0
 def post(self):
     """好友审核"""
     form = CheckFriendForm(data=request.json)
     if not form.validate():
         return {
             'code': RET.PARAMERR,
             'msg': getFlatten(form.errors.values())
         }
     friendCheck = db.session.query(ChatFriend).filter(
         ChatFriend.friend_id == token.id, ChatFriend.is_active == True,
         ChatFriend.status == 2, ChatFriend.id == form.data['id']).first()
     if not friendCheck:
         return {'code': RET.PARAMERR, 'msg': '不存在该好友审核'}
     selfFriend = ChatFriend(
         self_id=token.id,
         friend_id=friendCheck.self_id,
         room=friendCheck.room,
     )
     selfFriend.status = friendCheck.status = form.data['status']
     if friendCheck.status == 1:
         #用户同意好友请求
         friendCheck.become_friends_time = selfFriend.become_friends_time = datetime.datetime.now(
         )
         selfFriend.room = friendCheck.room
         userName = db.session.query(
             User.userName).filter(User.id == friendCheck.self_id).scalar()
         selfFriend.remark = userName
     try:
         db.session.add(selfFriend)
         db.session.commit()
     except:
         return {'code': RET.SERVERERR, 'msg': error_map[RET.SERVERERR]}
     data = selfFriend.to_dict()
     user = db.session.query(User).filter(
         data['self_id'] == User.id).first()
     data['user'] = user.to_dict()
     return {
         'code': RET.OK,
         'msg': error_map[RET.OK],
         'data': selfFriend.to_dict()
     }
Beispiel #9
0
    def post(self):
        """
        * 获取邮箱验证码:
        * 请求:{email:'*****@*****.**'}
        * 响应:{code:'2000',msg:'ok'}
        """
        from apps.user.task import send_mail
        form = EmailForm(data=request.json)
        if form.validate():
            self.user = form.data['user']
            if current_app.redis.get(self.email_redis_key):
                timeRemaining = current_app.redis.ttl(self.email_redis_key)
                return {
                    'code': RET.PARAMERR,
                    'msg': f'{timeRemaining}秒后才可以重新发送邮箱验证码'
                }

            code = self.generate_code
            current_app.redis.setex(self.email_redis_key,
                                    current_app.config['MAIL_VERIFY_EXPIRE'],
                                    code)
            send_mail.delay(self.user.email, code)
            return {'code': RET.OK, 'msg': error_map[RET.OK]}
        return {'code': RET.PARAMERR, 'msg': getFlatten(form.errors.values())}
Beispiel #10
0
 def create(self):
     """用户发送消息"""
     form = FriendMsgForm(data=request.json)
     if not form.validate():
         return {
             'code': RET.PARAMERR,
             'msg': getFlatten(form.errors.values())
         }
     msg = FriendsMessage(msg=form.msg.data,
                          type=form.type.data,
                          from_user_id=token.id,
                          to_user_id=form.to_user_id.data,
                          status=form.status.data,
                          room=form.room.data)
     db.session.add(msg)
     db.session.commit()
     msg = msg.to_dict()
     msg['user'] = token.user.to_dict()
     emit('FRIEND_NEW_MSG',
          msg,
          room=FriendRoomUtil.get_room(form.to_user_id.data),
          namespace='/',
          broadcast=True)
     return {'code': RET.OK, 'msg': error_map[RET.OK], 'data': msg}
Beispiel #11
0
    def post(self):
        """
        * 登录接口:
        * 请求:{email:'*****@*****.**',code:'123456',username:'',pwd:'',type:1}
        * 响应:{token:'1234567890123',user:{完整用户信息}}
        """
        res = current_app.redis.get(self.login_error_key)
        if res and int(res) >= current_app.config['LOGIN_ACCESS_NUM']:
            return {'errno': RET.LOGINERR, 'msg': '密码输入次数过多,请十分钟之后重试'}

        js = request.json
        type = js.get('type')
        if type is None:
            return {'code': RET.PARAMERR, 'msg': error_map[RET.PARAMERR]}
        #密码认证
        if type == 0:
            form = LoginPwdForm(data=js)
            if not form.validate():
                return {
                    'code': RET.PARAMERR,
                    'msg': getFlatten(form.errors.values())
                }

            user = User.query.filter(
                User.userName == form.userName.data).first()
            if not user:
                return {'code': RET.USERERR, 'msg': '用户不存在!'}

            flag = user.check_password(form.pwd.data)

            if not flag:
                current_app.redis.incr(self.login_error_key)
                current_app.redis.expire(
                    self.login_error_key,
                    current_app.config['LOGIN_ERROR_TIME'])
                return {'code': RET.PARAMERR, 'msg': '用户名或密码错误!'}

        #邮箱验证码验证
        elif type == 1:
            form = LoginEmailForm(data=js)
            if not form.validate():
                return {
                    'code': RET.PARAMERR,
                    'msg': getFlatten(form.errors.values())
                }
            user = User.query.filter(User.email == form.email.data).first()
            if not user:
                return {'code': RET.PARAMERR, 'msg': '用户名或验证码错误!'}
            code = current_app.redis.get(
                EmailView.pubilc_email_redis_key(user.userName))
            if not code:
                return {'code': RET.PARAMERR, 'msg': '用户名或验证码错误!'}
            if code != form.code.data:
                return {'code': RET.PARAMERR, 'msg': '验证码错误!'}
            else:
                current_app.redis.delete(
                    EmailView.pubilc_email_redis_key(user.userName))

        token = Token.encryptTk(current_app.config, user.to_dict())
        return {
            'code': RET.OK,
            'msg': error_map[RET.OK],
            'data': {
                'token': token,
                'user': user.to_dict()
            }
        }