예제 #1
0
def authenticate_user(db: str, collection: str, username: str, password: str):
    user = get_user(get_client(db, collection), username)
    if not user:
        return False
    if not verify_password(password, user.hashed_password):
        return False
    return user
예제 #2
0
def page_text(name, message):
    """
    Generating texts for pages
    :param name: str, name of page
    :param message: dict, message object from vk [object][message]
    :return: text for page
    """
    if name == 'main':
        user_id = message['from_id']
        user_data = users.get_user(user_id)
        # dict {user_id: int, role: int,
        #     subscribe: bool, report: bool, show_profile: bool, show_report: bool,
        #     nickname: str, squad: str, practice: int, theory: int, guile: int, wisdom: int;
        #     if report True: date_report: str, income: int, pure_income: int, target: int}
        text = 'Hello, ' + user_data['nickname'] + '\n\n'
        if user_data['show_profile']:
            # stat's string
            text += '📡: ' + str(user_data['practice']) + '; 💾: ' + str(user_data['theory']) + \
                    '; 📱: ' + str(user_data['guile']) + '; 🔎: ' + str(user_data['wisdom']) + '\n'
            # overall string
            text += '⚔: ' + str(int(user_data['practice'] + 1.5*user_data['guile'])) + \
                    '; 🔐: ' + str(int(user_data['theory'] + 1.5*user_data['wisdom'])) + '\n\n'
        if user_data['show_report']:
            if user_data['report']:
                text += '🤑: ' + str(user_data['income']) + '; 💵: ' + str(user_data['pure_income']) +\
                        '; ✅: ' + str(fractions[user_data['target']]) + '\n\n'
            else:
                text += 'Today you don\'t send report\n\n'
        # TODO: get time before battle
        text += 'Time left for battle: ' + str('undefined')
        return text
    elif name == 'settings':
        text = 'Settings page'
        return text
    elif name == 'stats':
        # TODO: Remove brackets after complete stats
        text = 'Statistics.\nHere you can watch your performance (not working)'
        return text
    elif name == 'control':
        text = 'Control page.\nAll for your business'
        return text
    elif name == 'battle_push':
        text = 'Manage pushes for battle'
        return text
    elif name == 'target':
        user_id = message['from_id']
        role_id = users.get_role(user_id)
        text = 'Set target for ' + ('fraction' if role_id in [0, 1, 3] else users.get_squad(user_id))
        return text
    else:
        pass
    return
예제 #3
0
파일: auth.py 프로젝트: markisus/Alternote
 def post(self):
     form = LoginForm(**self.get_params())
     if form.validate():
         try:
             user = get_user(form.email.data)
         except KeyError:
             self.write("No username or wrong password")
             return
         if user['password'] == form.password.data:
             session = db_login(user['_id'])
             self.set_cookie('session', session)
             next = self.get_argument("next", "/")
             self.redirect(next)
             return
         else:
             self.write("No username or wrong password")
     self.write(self.template.render(form=form))
예제 #4
0
async def get_current_user(token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = TokenData(username=username)
    except PyJWTError:
        raise credentials_exception
    user = get_user(get_client(*USER_COLLECTION), username=token_data.username)
    if user is None:
        raise credentials_exception
    return user
예제 #5
0
def start(msg, command):
    chat = msg['peer_id']
    user_id = msg['from_id']
    user = users.get_user(user_id)
    globals()[command](msg=msg, chat=chat, user=user)
    return
예제 #6
0
def share(user_id, text, role_id):
    """
    Parses share and write into DB
    """
    user_info = users.get_user(user_id)
    shar = text.split(sep='\n\n')

    tl_flag = False
    sl_flag = False

    nick_pattern = r"\b[\w ]+\b(?=\s\()"
    squad_pattern = r"\b\w\w\b"
    emoji_pattern = r"&#\d+;"
    stat_pattern = r"\s\d+"
    """
        Parse block
    """

    row = shar[0].split(sep='\n')[0]

    nick = re.search(nick_pattern, row)[0].strip()

    sl = '▫'
    tl = '🔸'
    if sl in row:
        sl_flag = True
    elif tl in row:
        tl_flag = True
    else:
        pass

    f = fractions[re.findall(emoji_pattern, row)[-1]]

    if re.search(squad_pattern, row):
        squad = re.search(squad_pattern, row)[0]
    else:
        squad = f

    # TODO: Do smth with fraction

    prc_val = int(re.findall(stat_pattern, shar[1])[0])
    teo_val = int(re.findall(stat_pattern, shar[1])[1])
    hit_val = int(re.findall(stat_pattern, shar[1])[2])
    mud_val = int(re.findall(stat_pattern, shar[1])[3])

    # Check share with profile

    if nick != user_info['nickname']:
        vk_api.send(user_id, "Wrong Nickname, re-send profile to confirm")
        return

    if squad != user_info['squad']:
        vk_api.send(user_id, "Re-send profile to confirm squad")
        return

    if f != fraction:
        vk_api.send(user_id, "Send profile to confirm fraction")
        return

    message = str()
    message = message + nick + '\n'
    if tl_flag:
        message = message + "TL" + '\n'
    elif sl_flag:
        message = message + "SL" + '\n'
    else:
        message = message + "No Status" + '\n'
    message = message + str(f) + '\n'
    message = message + str(squad) + '\n'
    message = message + str(prc_val) + ', ' + str(teo_val) + '\n'
    message = message + str(hit_val) + ', ' + str(mud_val) + '\n'

    # If all ok, write new data in db

    users.set_profile(user_id, nick, squad, prc_val, teo_val, hit_val, mud_val)
    vk_api.send(user_id, "Share accepted!\n" + message)

    return
예제 #7
0
def message(msg):
    """
    Main processing with message
    :param msg: dict, message object from vk [object][message]
    :return: None
    """

    time = int(msg['date'])
    text = str(msg['text'])
    chat = int(msg['peer_id'])
    user = int(msg['from_id'])

    if user > 0:
        pl = 'payload' in msg.keys()
        fwd = len(msg['fwd_messages']) != 0
        com = text.startswith('/')
        if user != chat:
            if pl or com:
                pass
            else:
                return
        else:
            if pl or com or fwd:
                pass
            else:
                return
        try:
            get_user(user)
        except ValueError:
            reg_user(user, time - 1)
            if user == settings.creator:
                set_role(user, 0)
                vk_api.send(user, "You became a creator")

        if time == get_msg(user):
            vk_api.send(chat, "2fast4me")
            return
        else:
            update_msg(user, time)
    else:
        return

    # keyboards
    if pl:
        pl = json.loads(msg['payload'])
        payload(msg, pl)
        return

    # forwards
    if fwd and text == '':
        forward = msg['fwd_messages']
        forwards(msg, forward)
        return

    # commands
    if com:
        command = msg['text'].split()
        command[0] = command[0].replace('/', '')
        if command[0] in cmd():
            commands(msg, command[0])
        else:
            vk_api.send(chat, '\"/' + str(command[0]) + '\" not in list')
        return
    return
예제 #8
0
def retrieve_user(user_id: int, db: Session = Depends(get_db)):
    return users.get_user(db, user_id)