Exemplo n.º 1
0
def handle_send_message_event(data):
    sender = User(username=data['username'], user_id=data['user_id'])
    user_type = data['user_type']
    current_room = get_room(data['room_id'])
    last_sender = None
    prev_msg = None
    if len(current_room.messages) > 0:
        index = len(current_room.messages) - 1
        prev_msg = current_room.messages[index]
        last_sender = prev_msg.sender

    if user_type == "BOT":
        sender.personality = data['personality']
        sender.user_type = user_type
        bot = assign_bot(personality=sender.personality)
        prev_content = prev_msg.content.message if prev_msg else None
        message = bot(prev_content)
    else:
        message = Message(sender=sender, content=Content(message=data['msg']))
        data['ok'] = "DIN TUR"

    if last_sender is None or last_sender.user_id != sender.user_id:
        data['message'] = asdict(message)
        current_room.messages.append(message)
        socket.emit('receive_message', data, to=current_room.room_id)
Exemplo n.º 2
0
def index():

    loginform = LoginForm()
    signupform = SignupForm()

    if request.method == 'POST' and not current_user.is_authenticated:

        if loginform.validate_on_submit():
            user = User.query.filter_by(
                username=loginform.username.data).first()

            if not user or not user.check_password(loginform.password.data):
                mess = {}
                mess['event'] = 191
                mess['htm'] = render_template(
                    'errormessage.html',
                    message='Incorrect password or username')
                socket.emit('newmessage', mess)

            elif user and user.check_password(loginform.password.data):
                login_user(user, remember=loginform.remember_me.data)

                if user.pw_reset_token or user.pwrt_valid or user.pwrt_vcode != 0:
                    user.pw_reset_token = ''
                    user.pwrt_valid = None
                    user.pwrt_vcode = 0
                    user.pwrt_try = 0

                user.last_activity = datetime.now()
                db.session.commit()
                return redirect('/')

    if current_user.is_authenticated and current_user.is_superuser:

        users = User.query.order_by(User.id).all()
        pockets = Pocket.query.order_by(Pocket.user_id).all()
        transfers = Transfer.query.order_by(Transfer.timestamp).all()
        categories = Category.query.order_by(Category.user_id).all()

        return render_template('index.html', title='SU index', loginform=loginform, signupform=signupform,\
                               users=users, pockets=pockets, transfers=transfers, categories=categories)

    elif current_user.is_authenticated and not current_user.is_superuser:

        pockets = Pocket.query.filter_by(_user=current_user).all()

        ptransfers = get_ptransfers(current_user, 5)
        ntransfers = get_ntransfers(current_user, 5)

        return render_template('index.html', title='Index', loginform=loginform, signupform=signupform, pockets=pockets,\
                               ptransfers=ptransfers, ntransfers=ntransfers)

    else:

        return render_template('index.html',
                               title='Index',
                               loginform=loginform,
                               signupform=signupform)
Exemplo n.º 3
0
def like(id, *args, **kwargs):
    currentUser = User.get().filter_by(id=kwargs['token']['id']).first()

    post = Post.get().filter_by(id=id).first()
    like = Post_Likes.get().filter(
        and_(Post_Likes.author == currentUser.id,
             Post_Likes.post == post.id)).first()

    not_id = str(db.session.execute(Sequence('notification_id_seq')))

    if like is not None:
        response = jsonify({'operation': 'disliked'})
        like.delete()
        body = 'unliked your post'
    else:
        response = jsonify({'operation': 'liked'})
        new_like = Post_Likes(post=post.id, author=currentUser.id)
        new_like.add()
        body = 'liked your post'

    not_check = Notification.get().filter_by(title=currentUser.name + ' ' +
                                             body).filter_by(
                                                 body=post.title).first()

    if not_check is None:
        notify = Notification(
            id=int(not_id),
            author=currentUser.id,
            user=post.author.id,
            type=2,
            title=post.title,
            body=currentUser.name + ' ' + body,
            link='/post/' +
            (str(post.title).replace(' ', '-')).replace('?', '') + '-' +
            str(post.id) + '?notification_id=' + not_id)
        notify.add()
    else:
        not_check.checked = False
        not_check.save()

    if post.author.status != 2:
        send_notification(
            post.author.id, {
                'text':
                currentUser.name + ' ' + body,
                'link':
                '/post/' +
                (str(post.title).replace(' ', '-')).replace('?', '') + '-' +
                str(post.id),
                'icon':
                currentUser.info.avatar_img,
                'id':
                not_id
            })

    socket.emit("notification", room="notification-{}".format(post.author.id))

    return make_response(response, 200)
Exemplo n.º 4
0
 def run(self):
     try:
         while True:
             if self.collecting is True and self.history is not None:
                 data = self.serial_connect.do_thing()
                 time.sleep(0.5)
                 if data.__len__ is not 0:
                     data_json = json.dumps(data, indent=4, sort_keys=True, default=str)
                     socket.emit('message', data_json)
     finally:
         print('Ending Thread Process')
Exemplo n.º 5
0
def login():

    if current_user.is_authenticated:
        logger.upd_log(
            f'{current_user.username} tried to reach loginsite, redirected to /',
            1)
        return redirect('/')

    form = LoginForm()

    if request.method == 'POST' and not current_user.is_authenticated:
        if form.validate_on_submit():
            user = User.query.filter_by(username=form.username.data).first()
            if not user:
                mess = {}
                mess['event'] = 1109
                socket.emit('generic', mess)
                logger.upd_log(
                    f'Login attempt with invalid username: {form.username.data} from IP: {request.access_route}',
                    2)
                return '', 204

            if user.check_password(form.password.data):
                login_user(user, remember=form.remember_me.data)
                logger.upd_log(
                    f'Successful login: {form.username.data} from IP: {request.access_route}',
                    0)
                return redirect('/')

            else:
                mess = {}
                mess['event'] = 1109
                socket.emit('generic', mess)
                logger.upd_log(
                    f'Login attempt with invalid password: {form.username.data} from IP: {request.access_route}',
                    2)
                return '', 204

    return render_template('/noauth/login.html', title='Belépés', form=form)
Exemplo n.º 6
0
def user(name, *args, **kwargs):
    currentUser = User.get().filter_by(name=kwargs['token']['name']).first_or_404()
    userFollowed = User.get().filter_by(name=name).first()

    check = User_Following.get().filter(and_(User_Following.user==currentUser.id,User_Following.followed==userFollowed.id)).first()

    if check is None:
        new_follow = User_Following(
            user=currentUser.id,
            followed=userFollowed.id
        )
        new_follow.add()
        response = jsonify({'operation': 'followed'})
        body = 'started following you'
    else:
        check.delete()
        body = 'unfollowed you'
        response = jsonify({'operation': 'unfollowed'})

    notification = Notification(
        author=currentUser.id,
        user=userFollowed.id,
        type=1,
        checked=False,
        body=currentUser.name + ' ' + body,
        link='/user/' + str(currentUser.name)
    )
    notification.add()

    if userFollowed.status != 2:
        send_notification(userFollowed.id, {
            'text': currentUser.name + ' ' + body,
            'link': '/user/' + str(currentUser.name),
            'icon': currentUser.info.avatar_img,
            'id': notification.id
        })

    socket.emit("notification", room="notification-{}".format(userFollowed.id))
    return make_response(response, 200)
Exemplo n.º 7
0
def message(data):
    try:
        last_date = time.datetime.strptime(data['last_date'],
                                           '%a, %d %b %Y %H:%M:%S %Z')
    except:
        last_date = time.datetime.now()

    if (time.datetime.now() - last_date).days >= 1:
        new_day_from_last = True
    else:
        new_day_from_last = False

    if time.datetime.now().date() == last_date.date():
        new_day = False
    else:
        new_day = True

    message = {
        'text': data['text'],
        'author': data['author'],
        'room': data['room'],
        'id': data['id'],
        'at': time.datetime.now().strftime("%H:%M"),
        'on': time.datetime.now().strftime("%A %d %b"),
        'datetime': str(time.datetime.now()),
        'new_day_from_last': new_day_from_last,
        'new_day': new_day
    }

    user = UserModel.query.filter_by(name=data['author']['name']).first()
    new_message = ConversationsModel(id=None,
                                     message=data['text'],
                                     user=user.id,
                                     created_on=None,
                                     conversation_id=data['id'])
    new_message.add()
    socket.emit("get_message", message, room=data['room'])
def add_users_to_shared_folder(folder_id, params):
    shared_folder = db_session_users.query(UserSharedFolder).filter_by(
        folder_id=folder_id).first()
    if not shared_folder:
        return jsonify(
            {'errors':
             "No shared folder exists for id: " + str(folder_id)}), 404

    shared_folder_owner_id = db_session_users.query(
        UserFolder.user_id).filter_by(id=folder_id).first()

    user_shared_folders = []
    mandrill_recipients = []
    for user in params['users']:
        user_access_to_folder = db_session_users.query(
            UserSharedFolder).filter_by(folder_id=folder_id,
                                        user_id=user['id']).first()
        if user_access_to_folder:
            return jsonify({'errors': 'Folder already shared with user'}), 409
        elif (shared_folder_owner_id != user['id']):  # no need to notify owner
            new_user_shared_folder = UserSharedFolder({
                "user_id": user['id'],
                "folder_id": folder_id,
                "editor": user['editor'],
                "viewer": user['viewer']
            })
            user_shared_folders.append(new_user_shared_folder)

            # new sharees need to be notified and emailed
            user_from_db = db_session_users.query(User).filter_by(
                id=user['id']).first()

            mandrill_recipients.append({
                'email': user_from_db.email,
                'name': user_from_db.first_name,
                'type': 'to'
            })

            if 'notif_status' in user_from_db.properties:
                folder_status = {"user_folders": {"viewed_status": False}}
                new_notif_status = merge_two_dicts(
                    user_from_db.properties['notif_status'], folder_status)
            else:
                new_notif_status = {"user_folders": {"viewed_status": False}}

            new_props = merge_two_dicts(user_from_db.properties,
                                        {'notif_status': new_notif_status})
            user_from_db.properties = merge_two_dicts(user_from_db.properties,
                                                      new_props)
            db_session_users.add(user_from_db)
            db_session_users.commit()

    db_session_users.add_all(user_shared_folders)
    db_session_users.commit()

    from app import socket
    for user in user_shared_folders:
        socket.emit('foldersNotification', room=user.user_id)

    if BASE_URL_FOR_EMAIL:
        base_url = BASE_URL_FOR_EMAIL
    else:
        base_url = 'http://%s:%s' % (API_BOUND_HOST, API_PORT)

    if 'user_msg' in params:
        user_msg = params['user_msg']
    else:
        user_msg = ''

    shared_folder_owner = db_session_users.query(User).filter_by(
        id=shared_folder_owner_id).first()

    if shared_folder_owner.first_name is not None:
        owner_first_name = shared_folder_owner.first_name + ' has'
    else:
        owner_first_name = 'I've'

    folder_url = '%s/content?folderTimelineView=true&no_skipping=true&folder_id=%s' % (
        base_url,
        folder_id,
    )
    #email sharees
    email_helper.send_via_mandrill(
        mandrill_recipients,
        '*****@*****.**',
        'Compliance.ai',
        'A Compliance.ai folder has been shared with you!',
        template='shared-folder-inline',
        vars={
            'url': folder_url,
            'base_url': base_url,
            'user_msg': user_msg,
            'owner_first_name': owner_first_name,
        },
    )

    return jsonify({'folder_shared_with_users': True})
Exemplo n.º 9
0
def new(*args, **kwargs):
    data = request.json

    if not data or not data['post_id'] or not data['content']:
        return make_response(jsonify({'operation': 'error', 'error': 'Missing data'}), 401)

    post = Post.get().filter_by(id=data['post_id']).first()

    if not post:
        return make_response(jsonify({'operation': 'error', 'error': 'No post'}), 401)

    currentUser = User.get().filter_by(name=kwargs['token']['name']).first_or_404()

    if data['type'] == 'post':
        new_reply = Post_Comments(post=data['post_id'], text=data['content'], author_id=currentUser.id)
    else:
        new_reply = Comment_Reply(text=data['content'], comment=data['reply_id'], author_id=currentUser.id)
    
    new_reply.add()

    not_id = str(db.session.execute(Sequence('notification_id_seq')))
    
    notify = Notification(
        id=int(not_id),
        author=currentUser.id,
        body='{} replied to your post'.format(currentUser.name),
        title=post.title,
        link=post.link + '?notification_id=' + str(not_id),
        user=post.author.id,
        type=4
    )
    notify.add()
    send_notification(post.author.id, {
        'text': '{} replied to your {}'.format(currentUser.name, data['type']),
        'link': post.link + '?notification_id=' + str(not_id),
        'icon': currentUser.info.avatar_img,
        'id': not_id
    })
    socket.emit("notification", room="notification-{}".format(post.author.id))
    mentions = re.findall("@([a-zA-Z0-9]{1,15})", cleanhtml(data['content']))
    mentioned = User.get().filter(User.name.in_(mentions)).all()
    for m in mentioned:
        not_id = str(db.session.execute(Sequence('notification_id_seq')))
        notify = Notification(
            id=int(not_id),
            author=currentUser.id,
            title='{} mentioned you in a comment'.format(m.name),
            body=cleanhtml(data['content'])[:20],
            link=post.link + '?notification_id=' + str(not_id),
            user=post.author.id,
            type=6
        )
        notify.add()
        send_notification(post.author.id, {
            'text': '{}  mentioned you in a comment'.format(currentUser.name),
            'link': post.link + '?notification_id=' + str(not_id),
            'icon': currentUser.info.avatar_img,
            'id': not_id
        })
        socket.emit("notification", room="notification-{}".format(m.id))

    reply_json = {}

    if data['type'] == 'post':
        serializer = CommentsSchema(many=False)
        serializer.context['currentUser'] = currentUser
        reply_json = serializer.dump(new_reply)
    else:
        serializer = RepliesSchema(many=False)
        serializer.context['currentUser'] = currentUser
        reply_json = serializer.dump(new_reply)

    return make_response(jsonify({'operation': 'success', 'reply': reply_json}), 200)
Exemplo n.º 10
0
def new_dim(data):
    socket.emit("change_dim", data, broadcast=True)
Exemplo n.º 11
0
def new_color(data):
    socket.emit("change_color", data, broadcast=True)
Exemplo n.º 12
0
def newmessage(data):

    sid = request.sid

    #incoming request for error message with message - DONE
    if data['event'] == 291:
        mess = {}
        mess['event'] = 191
        mess['htm'] = render_template('errormessage.html',
                                      message=data['message'])
        socket.emit('newmessage', mess, room=sid)
        return True

    #Experimental details
    #request for details view
    if data['event'] == 293 and current_user.is_authenticated:

        pid = int(data['pid'])
        pocket = Pocket.query.get(pid)

        transfers = Transfer.query.filter_by(_pocket=pocket).order_by(
            Transfer.timestamp).all()

        if len(transfers) < 1:
            mess = {}
            mess['event'] = 191
            mess['htm'] = render_template(
                'errormessage.html', message='No tansfers in this pocket!')
            socket.emit('newmessage', mess, room=sid)
            return False

        daterange = {}
        daterange['min'] = transfers[0].timestamp.timestamp() * 1000
        daterange['max'] = transfers[-1].timestamp.timestamp() * 1000

        temp = {}
        temp['pid'] = pid
        temp['min'] = transfers[0].timestamp
        temp['max'] = transfers[-1].timestamp

        charts = drawcharts2(temp)

        mess = {}
        mess['event'] = 193
        mess['htm'] = render_template('details2.html',
                                      p=pid,
                                      pocket=pocket,
                                      user=current_user,
                                      daterange=daterange,
                                      charts=charts,
                                      transfers=transfers)
        socket.emit('newmessage', mess, room=sid)

        return True

    #refresh details daterange
    if data['event'] == 294 and current_user.is_authenticated:

        pid = int(data['pid'])

        fromdate = datetime.fromtimestamp(int(data['mintime'] / 1000),
                                          tz=pytz.utc)
        todate = datetime.fromtimestamp(int(data['maxtime'] / 1000),
                                        tz=pytz.utc)

        pocket = Pocket.query.get(pid)
        transfers = Transfer.query.filter_by(_pocket=pocket).order_by(
            Transfer.timestamp).filter(Transfer.timestamp >= fromdate).filter(
                Transfer.timestamp <= todate).all()

        newdate = {}
        newdate['min'] = transfers[0].timestamp.timestamp() * 1000
        newdate['max'] = transfers[-1].timestamp.timestamp() * 1000

        temp = {}
        temp['pid'] = pid
        temp['min'] = fromdate
        temp['max'] = todate

        charts = drawcharts2(temp)

        mess = {}
        mess['event'] = 194
        mess['htm'] = render_template('charts.html',
                                      charts=charts,
                                      transfers=transfers,
                                      newdate=newdate)
        socket.emit('newmessage', mess, room=sid)
        return True

    #incoming request for refresh the usercarousel
    if data['event'] == 281 and current_user.is_authenticated:

        pockets = Pocket.query.filter_by(user_id=current_user.id).all()

        nth = {}
        for index, p in enumerate(pockets):
            nth['uc_' + str(p.id)] = index

        mess = {}
        mess['slides'] = nth
        mess['event'] = 181

        ptransfers = get_ptransfers(current_user, 5)
        ntransfers = get_ntransfers(current_user, 5)

        mess['htm'] = render_template('usercarousel.html',
                                      title='Index',
                                      pockets=pockets,
                                      ptransfers=ptransfers,
                                      ntransfers=ntransfers)
        socket.emit('newmessage', mess, room=sid)

        return True

    #user sends resetpassword data, check
    if data['event'] == 287 and current_user.is_authenticated:

        rp = rpwd(data, current_user)

        if rp == 0:
            #OK, inform the user! 187 event
            mess = {}
            mess['event'] = 187
            mess['htm'] = render_template(
                'infomessage.html',
                message='Password has been changed succesfully!')
            socket.emit('newmessage', mess, room=sid)
            return True

        elif rp == 1:
            #wrong password!
            message = 'The old password does not match!'
            mess = {}
            mess['event'] = 191
            mess['htm'] = render_template('errormessage.html', message=message)
            socket.emit('newmessage', mess, room=sid)
            return True

        elif rp == 2:
            #mismatch
            message = 'The new passwords do not match!'
            mess = {}
            mess['event'] = 191
            mess['htm'] = render_template('errormessage.html', message=message)
            socket.emit('newmessage', mess, room=sid)
            return True

        elif rp == 3:
            #wrong pw compleyity
            message = 'Password must have UPPER and lowercase chars, numbers, and must be at least 8 chars length!'
            mess = {}
            mess['event'] = 191
            mess['htm'] = render_template('errormessage.html', message=message)
            socket.emit('newmessage', mess, room=sid)
            return True

        elif rp == 4:
            #old and new password is the same
            message = 'The old and the new password must be different!'
            mess = {}
            mess['event'] = 191
            mess['htm'] = render_template('errormessage.html', message=message)
            socket.emit('newmessage', mess, room=sid)
            return True

    #User wants to reset password
    if data['event'] == 288 and current_user.is_authenticated:
        mess = {}
        mess['event'] = 188
        mess['htm'] = render_template('rpassword_modal.html')
        socket.emit('newmessage', mess, room=sid)
        return True

    #user requests for helpmodal
    if data['event'] == 289 and current_user.is_authenticated:
        mess = {}
        mess['event'] = 189
        mess['htm'] = render_template('helpmodal.html')
        socket.emit('newmessage', mess, room=sid)
        return True

    #user want to add transfer
    if data['event'] == 251 and current_user.is_authenticated:

        if data['type'] == 1:
            cats = Category.query.order_by(
                Category.name).filter_by(_user=current_user).filter_by(
                    type=1).filter_by(hidden=False).all()
            typ = 1
        else:
            cats = Category.query.order_by(
                Category.name).filter_by(_user=current_user).filter_by(
                    type=-1).filter_by(hidden=False).all()
            typ = -1

        pockets = Pocket.query.filter_by(_user=current_user).order_by(
            Pocket.name).all()

        actual_pocket = int(data['pocket'].split('_')[1])

        mess = {}
        mess['event'] = 151
        mess['htm'] = render_template('addtransfer_modal.html',
                                      categories=cats,
                                      pockets=pockets,
                                      ap=actual_pocket,
                                      type=typ)
        socket.emit('newmessage', mess, room=sid)

        return True

    #user sends transfer details
    if data['event'] == 252 and current_user.is_authenticated:
        if add_transfer(data):
            mess = {}
            mess['event'] = 152
            socket.emit('newmessage', mess, room=sid)
        return True

    #user wants to see the categories
    if data['event'] == 261 and current_user.is_authenticated:
        categories = Category.query.order_by(Category.name).filter_by(
            user_id=current_user.id).filter_by(hidden=False).all()

        tr_nums = {}
        for c in categories:
            n = Transfer.query.filter_by(_category=c).all()
            num = len(n)
            tr_nums[c.id] = num

        mess = {}
        mess['event'] = 161
        mess['htm'] = render_template('category_modal2.html',
                                      categories=categories,
                                      tr_nums=tr_nums)
        socket.emit('newmessage', mess, room=sid)
        return True

    #user want to del a category - DONE
    if data['event'] == 262 and current_user.is_authenticated:

        id = data['id']

        if delcategory(id):
            mess = {}
            mess['event'] = 162
            mess['id'] = id
            socket.emit('newmessage', mess, room=sid)
            return True

    #user want to edit a category
    if data['event'] == 263 and current_user.is_authenticated:
        if data['id']:
            id = data['id']
            c = Category.query.get(int(id))

        mess = {}
        mess['event'] = 164
        mess['htm'] = render_template('addcategory_modal.html', c=c)
        socket.emit('newmessage', mess, room=sid)
        return True

    #user wants to add a category
    if data['event'] == 264 and current_user.is_authenticated:

        mess = {}
        mess['event'] = 164
        mess['htm'] = render_template('addcategory_modal.html')
        socket.emit('newmessage', mess, room=sid)
        return True

    #user sends a category
    if data['event'] == 268 and current_user.is_authenticated:

        if add_cat(data, current_user):

            categories = Category.query.order_by(Category.name).filter_by(
                user_id=current_user.id).filter_by(hidden=False).all()

            tr_nums = {}
            for c in categories:
                n = Transfer.query.filter_by(_category=c).all()
                num = len(n)
                tr_nums[c.id] = num

            mess = {}
            mess['event'] = 169
            mess['htm'] = render_template('category_modal2.html',
                                          categories=categories,
                                          tr_nums=tr_nums)
            socket.emit('newmessage', mess, room=sid)
            return True

        else:
            mess = {}
            mess['event'] = 191
            mess['htm'] = render_template(
                'errormessage.html', message='This category already exists!')
            socket.emit('newmessage', mess, room=sid)
            return True

    # user wants to signup
    if data['event'] == 211:

        r = verifiy_signup(data)

        if r == 0:
            #ok, data are great, i added you to the database, try to login
            mess = {}
            mess['event'] = 111
            mess['htm'] = render_template('infomessage.html',
                                          message='You can login now!')
            socket.emit('newmessage', mess, room=sid)
            return True

        elif r == 1:
            #invalid email address
            socket.emit('newmessage', {'event': 119}, room=sid)
            mess = {}
            mess['event'] = 191
            mess['htm'] = render_template(
                'errormessage.html',
                message='Invalid email or email is already registered!')
            socket.emit('newmessage', mess, room=sid)
            return True

        elif r == 2:
            # invalid  password
            socket.emit('newmessage', {'event': 119}, room=sid)
            mess = {}
            mess['event'] = 191
            mess['htm'] = render_template(
                'errormessage.html',
                message=
                'Passord must have UPPER and lowercase chars, numbers, and must be at least 8 chars length!'
            )
            socket.emit('newmessage', mess, room=sid)
            return True

        elif r == 3:
            # passwords do not match
            socket.emit('newmessage', {'event': 119}, room=sid)
            mess = {}
            mess['event'] = 191
            mess['htm'] = render_template('errormessage.html',
                                          message='Passwords do not match!')
            socket.emit('newmessage', mess, room=sid)
            return True

        elif r == 4:
            # did not agree
            socket.emit('newmessage', {'event': 119}, room=sid)
            mess = {}
            mess['event'] = 191
            mess['htm'] = render_template(
                'errormessage.html',
                message='Please read and accept the terms!')
            socket.emit('newmessage', mess, room=sid)
            return True

        elif r == 5:
            # username already exists
            socket.emit('newmessage', {'event': 119}, room=sid)
            mess = {}
            mess['event'] = 191
            mess['htm'] = render_template(
                'errormessage.html',
                message=
                'Somebody registered with this username, choose another!')
            socket.emit('newmessage', mess, room=sid)
            return True

        else:
            # no, noo, something isn't ok
            socket.emit('newmessage', {'event': 119}, room=sid)
            mess = {}
            mess['event'] = 191
            mess['htm'] = render_template('errormessage.html',
                                          message='SIGNUP NOT SUCCESS!')
            socket.emit('newmessage', mess, room=sid)
            return True

    #ser wants to login, sends data - DONE
    if data['event'] == 221:

        if validate_loginattempt(data):
            mess = {}
            mess['event'] = 121
            socket.emit('newmessage', mess, room=sid)
        else:
            mess = {}
            mess['event'] = 191
            mess['htm'] = render_template(
                'errormessage.html',
                message='Username or password is invalid!')
            socket.emit('newmessage', mess, room=sid)

        return True

    #user wants to reset password - answer: 127
    if data['event'] == 227 and not current_user.is_authenticated:

        #reset here and send an email!

        mess = {}
        mess['event'] = 127
        mess['htm'] = render_template('resetpw_modal.html',
                                      ver_code=generate_vercode(6))
        socket.emit('newmessage', mess, room=sid)
        return True

    #validate resetpassword form, and if ok, send mail
    if data['event'] == 2271 and not current_user.is_authenticated:

        u = User.query.filter_by(email=str(data['reset_mail'])).first()
        if not u:
            #NO USER
            print('No user!')
            return True
        else:
            u.pw_reset_token = generate_rnd(32)
            u.pwrt_valid = datetime.now() + timedelta(minutes=30)
            u.pwrt_vcode = int(data['reset_code'])
            u.pwrt_try = 5
            db.session.commit()
            sendmail(app.config['SENDGRID_API_KEY'], str(u.pw_reset_token),
                     str(u.email), request.url_root, str(u.username))
            return True

    #somebody sent a password reset creditentials
    if data['event'] == 2272 and not current_user.is_authenticated:

        user = User.query.filter_by(pw_reset_token=data['token']).first()

        if not user:
            return False

        else:

            if user.pwrt_try <= 0:
                #ran out of tries, reset tries and redirect to mainpage

                user.pw_reset_token = ''
                user.pwrt_valid = None
                user.pwrt_vcode = 0
                user.pwrt_try = 0
                db.session.commit()

                mess = {}
                mess['event'] = 1272
                mess['location'] = request.url_root
                socket.emit('newmessage', mess, room=sid)
                return True

            if user.pwrt_vcode != int(data['code']):
                user.pwrt_try -= 1
                db.session.commit()

                mess = {}
                mess['event'] = 191
                mess['htm'] = render_template(
                    'errormessage.html',
                    message='Wrong authentication code! You have {} tries left!'
                    .format(user.pwrt_try))
                socket.emit('newmessage', mess, room=sid)
                return True

            #everything seems to be OK, change password!

            user.set_password(data['p1'])
            db.session.commit()

            mess = {}
            mess['event'] = 1272
            mess['location'] = request.url_root
            socket.emit('newmessage', mess, room=sid)

        return True

    #user want to read the terms
    if data['event'] == 228:
        mess = {}
        mess['event'] = 128
        mess['htm'] = render_template('termsmodal.html')
        socket.emit('newmessage', mess, room=sid)
        return True

    #delete username
    #admin wants to del an user - DONE
    if data['event'] == 271:
        if current_user.is_superuser:

            mess = {}
            mess['event'] = 171
            mess['to_del'] = deluser(data)
            socket.emit('newmessage', mess, room=sid)

            pockets = Pocket.query.filter_by(user_id=int(data['userid'])).all()
            mess = {}
            mess['event'] = 171
            for pocket in pockets:
                mess['to_del'] = pocket.id
                socket.emit('newmessage', mess, room=sid)
        return True

    #admin wants to restore category
    if data['event'] == 272 and current_user.is_superuser:
        c = Category.query.get(int(data['cid']))
        if c.hidden:
            c.hidden = False
            db.session.commit()
            mess = {}
            mess['event'] = 172
            socket.emit('newmessage', mess, room=sid)
        return True

    #admin wants to hide a category
    if data['event'] == 273 and current_user.is_superuser:
        c = Category.query.get(int(data['cid']))
        if not c.hidden:
            c.hidden = True
            db.session.commit()
            mess = {}
            mess['event'] = 172
            socket.emit('newmessage', mess, room=sid)
        return True

    #admin wats to delete a category
    if data['event'] == 274 and current_user.is_superuser:
        c = Category.query.get(int(data['cid']))
        db.session.delete(c)
        db.session.commit()
        mess = {}
        mess['event'] = 172
        socket.emit('newmessage', mess, room=sid)
        return True

    #request for help content
    if data['event'] == 2711 and current_user.is_authenticated:
        content = 'help/help_' + str(data['helpcontent']) + '.html'
        mess = {}
        mess['event'] = 1711
        mess['htm'] = render_template(content)
        socket.emit('newmessage', mess, room=sid)
        return True

    #user want to add a pocket - DONE
    if data['event'] == 241 and current_user.is_authenticated:
        mess = {}
        mess['event'] = 141
        mess['htm'] = render_template('addpocket_modal.html')
        socket.emit('newmessage', mess, room=sid)
        return True

    #user want to delete a pocket - DONE
    if data['event'] == 242 and current_user.is_authenticated:
        mess = {}
        mess['event'] = 142
        mess['htm'] = render_template('delpocket_confirm.html',
                                      p_id=data['p_id'])
        socket.emit('newmessage', mess, room=sid)
        return True

    #user send a new pocket data - DONE
    if data['event'] == 243 and current_user.is_authenticated:
        if addpocket(data, current_user):

            pockets = Pocket.query.filter_by(user_id=current_user.id).all()

            ptransfers = get_ptransfers(current_user, 5)
            ntransfers = get_ntransfers(current_user, 5)

            mess = {}
            mess['event'] = 148
            mess['status'] = 1
            mess['htm'] = render_template('usercarousel.html',
                                          pockets=pockets,
                                          ptransfers=ptransfers,
                                          ntransfers=ntransfers)
            socket.emit('newmessage', mess, room=sid)

        return True

    #user confirms to delete a pocket - DONE
    if data['event'] == 244 and current_user.is_authenticated:

        if delpocket(data):
            mess = {}
            mess['event'] = 149
            mess['status'] = 1
            mess['pid'] = 'uc_' + str(data['p_id'])
            socket.emit('newmessage', mess, room=sid)
        return True

    #user wants to edit a pocket by id
    if data['event'] == 245 and current_user.is_authenticated:
        #print(data)
        p = Pocket.query.get(int(data['pid']))
        mess = {}
        mess['event'] = 145
        mess['htm'] = render_template('editpocket_modal.html', pocket=p)
        socket.emit('newmessage', mess, room=sid)
        return True

    #user sends edited pocket data
    if data['event'] == 246 and current_user.is_authenticated:

        p = Pocket.query.get(int(data['pid']))
        p.name = str(data['pname'])
        p.description = str(data['pdesc'])
        db.session.commit()

        mess = {}
        mess['event'] = 146
        socket.emit('newmessage', mess, room=sid)
        return True

    #DEV section
    # user asks for random transfers to generate
    if data['event'] == 410 and current_user.is_authenticated:
        p_id = data['pid'].split('_')[-1]
        #generate(100,[1000,15000], p_id)
        return True
Exemplo n.º 13
0
def handle_join_room_event(data):
    join_room(data['room_id'])
    socket.emit('user_joined', data)
Exemplo n.º 14
0
def new_admin_message(data):

    if not current_user.is_authenticated or not current_user.is_superuser:
        logger.upd_log(
            f'Non-superuser tried to reach ws admin namespace from IP {request.access_route}',
            2)
        return False

    # where to send the answer -> sid
    sid = request.sid

    #check adduser creditentials
    if data['event'] == 2201:
        mess = {}
        mess['event'] = 1201
        mess['status'] = check_adduser(data)

        if mess['status'] == 0:
            mess['new_users'] = json.dumps(json.loads(get_sudata())['users'])

        socket.emit('admin', mess, room=sid)
        logger.upd_log(
            f'{current_user.username} adder new user with status code {mess["status"]}',
            1)
        return True

    #del user by id
    if data['event'] == 2251:
        mess = {}
        mess['event'] = 1251
        mess['status'] = del_user(data)
        mess['new_users'] = json.dumps(json.loads(get_sudata())['users'])
        socket.emit('admin', mess, room=sid)
        return True

    #send test mail
    if data['event'] == 2701:
        mess = {}
        mess['event'] = 1701
        mess['status'] = sendmail_flaskmail(data)
        socket.emit('admin', mess, room=sid)
        return True

    #request for refreshed logfile as json
    if data['event'] == 2801:
        mess = {}
        mess['event'] = 1801
        mess['data'] = logger.return_json()
        socket.emit('admin', mess, room=sid)
        return True

    #backup entire db
    if data['event'] == 2851:
        mess = {}
        mess['event'] = 1850
        mess['status'] = bu.backup_all()
        socket.emit('admin', mess, room=sid)
        return True

    #restore entire db
    if data['event'] == 2871:
        mess = {}
        mess['event'] = 1871
        mess['status'] = bu.restore_all()
        socket.emit('admin', mess, room=sid)
        return True

    #init password change
    if data['event'] == 2889:
        mess = {}
        mess['event'] = 1889
        mess['status'] = bu.change_backup_password(iterates=100,
                                                   password_length=32)
        socket.emit('admin', mess, room=sid)
        return True

    #reset entire db
    if data['event'] == 2899:
        mess = {}
        mess['event'] = 1899
        mess['status'] = reset_db()
        socket.emit('admin', mess, room=sid)
        return True
Exemplo n.º 15
0
def handle_data_updates(params):
    # to avoid circular references this line is put in this function
    from app import socket
    socket.emit('notification', {'data':'a notification'})
    return {'data': 'updates received'}