Beispiel #1
0
def main(email: str, *, oldmsn: bool = False, yahoo: bool = False) -> None:
    with Session() as sess:
        user = sess.query(User).filter(User.email == email).one_or_none()
        if user is None:
            print("Creating new user...")
            user = User(
                uuid=misc.gen_uuid(),
                email=email,
                verified=False,
                name=email,
                message='',
                groups={},
                settings={},
            )

            # TODO: Should be generated on-demand, not here
            #ticketxml = '<?xml version="1.0" encoding="utf-16"?>\r\n<Ticket xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\r\n  <TS>{}</TS>\r\n  <CID>{}</CID>\r\n</Ticket>'.format(
            #	now.isoformat()[0:19] + 'Z', cid_format(user.uuid, decimal = True)
            #)
            #user.set_front_data('msn', 'circleticket', misc.sign_with_new_key_and_b64(ticketxml))
        else:
            print("User exists, changing password...")
        pw = getpass.getpass("Password: "******"Done.")
Beispiel #2
0
async def user_auth_middleware(request, handler):
    session = await get_session(request)
    db_engine = request.app['db']
    userid = session.get('userid')
    usr = User()  # create anonymous user
    if userid is not None:
        async with db_engine.acquire() as conn:
            user_raw = await conn.execute(
                user.select().where(user.c.id == userid))
            if user_raw.rowcount > 1:
                logging.error(f'There are multiple users with id: {userid}')
            else:
                user_row = await user_raw.fetchone()
                usr = User(*user_row.as_tuple())

    request['user'] = usr
    resp = await handler(request)
    return resp
Beispiel #3
0
def start(user):
    chat_id = user.chat.id
    bot.send_message(chat_id,
                     f"Welcome to {game['name']}",
                     reply_markup=types.ReplyKeyboardRemove(selective=False))
    if User().get_by_chat_id(
            chat_id=chat_id
    ) is None:  # if user hasn't used the "/start" command yet:
        bot.send_message(chat_id, "Hello, stranger, let me scan you...")
        User().new(chat_id=chat_id)
        command_help(user)  # show the new user the help page
        bot.send_message(chat_id,
                         "Scanning complete, I know you now",
                         reply_markup=menu_builder.common_user_menu())
    else:
        bot.send_message(
            chat_id,
            "I already know you, no need for me to scan you again!",
            reply_markup=menu_builder.common_user_menu())
Beispiel #4
0
def _remove_from_contacts(user: db.User, uuids: Set[str]) -> bool:
    none_found = True
    for c in user.contacts:
        if c['uuid'] in uuids:
            none_found = False
            break
    if none_found: return False
    user.contacts = [c for c in user.contacts if c['uuid'] not in uuids]
    print("contacts", user.email)
    return True
Beispiel #5
0
def create_user(email: str, pw: str, name: str, message: str) -> User:
    user = User(uuid=str(uuid4()),
                email=email,
                verified=True,
                name=name,
                message=message,
                groups=[],
                settings={})
    # TODO: Should be generated on-demand, not here
    #ticketxml = '<?xml version="1.0" encoding="utf-16"?>\r\n<Ticket xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\r\n  <TS>{}</TS>\r\n  <CID>{}</CID>\r\n</Ticket>'.format(
    #	datetime.utcnow().isoformat()[0:19] + 'Z', cid_format(user.uuid, decimal = True)
    #)
    #user.set_front_data('msn', 'circleticket', misc.sign_with_new_key_and_b64(ticketxml))
    set_passwords(user, pw, support_old_msn=True, support_yahoo=True)
    return user
Beispiel #6
0
def set_contacts(user: User, contacts_by_group: Dict[str, List[User]]) -> None:
    #user.contacts = {}
    user.groups = []

    for i, (group_name, group_users) in enumerate(contacts_by_group.items()):
        group_id = str(i + 1)
        group_uuid = str(uuid4())
        if group_name:
            user.groups.append({
                'id': group_id,
                'uuid': group_uuid,
                'name': group_name,
                'is_favorite': False
            })
        for u in group_users:
            contact = add_contact_twosided(user, u)
            if group_name:
                contact.groups.append({'id': group_id, 'uuid': group_uuid})
Beispiel #7
0
def set_passwords(user: User,
                  pw: str,
                  *,
                  support_old_msn: bool = False,
                  support_yahoo: bool = False) -> None:
    user.password = hash.hasher.encode(pw)

    if support_old_msn:
        pw_md5 = hash.hasher_md5.encode(pw)
        user.set_front_data('msn', 'pw_md5', pw_md5)

    if support_yahoo:
        pw_md5_unsalted = hash.hasher_md5.encode(pw, salt='')
        user.set_front_data('ymsg', 'pw_md5_unsalted', pw_md5_unsalted)

        pw_md5crypt = hash.hasher_md5crypt.encode(pw, salt='$1$_2S43d5f')
        user.set_front_data('ymsg', 'pw_md5crypt', pw_md5crypt)
Beispiel #8
0
async def google_drive_auth_callback(request):
    session = await get_session(request)
    state = session.get('google_drive_auth_state', '')
    cfg = modules_config
    api_scopes = cfg.get('google_drive', {}).get('scopes', [])
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        google_drive_secrets_file, scopes=api_scopes, state=state)
    flow.redirect_uri = request.url.parent.join(
        request.app.router['google_drive_auth_callback'].url_for()).human_repr(
        )
    authorization_response = request.url.human_repr()

    try:
        flow.fetch_token(authorization_response=authorization_response)
    except InvalidGrantError:
        logging.exception("Error on getting google drive token: ")
        raise HTTPBadRequest()

    credentials = flow.credentials
    if not credentials.valid:
        raise HTTPBadRequest()

    # create user here
    google_plus = build('plus', 'v1', credentials=credentials)
    profile = google_plus.people().get(userId='me').execute()
    user = User(email=profile['emails'][0]['value'],
                username=profile.get('displayName', ''),
                profile_url=profile.get('url', ''),
                avatar_url=profile.get('image', {}).get('url', ''))
    await user.save_to_db(request.app['db'])
    session['userid'] = user.id
    tm = GoogleDriveTokenManager(
        access_token=credentials.token,
        refresh_token=credentials.refresh_token,
        expires=credentials.expiry,
        token_uri=credentials.token_uri,
    )
    raise HTTPFound(request.app.router['main_page'].url_for())