Example #1
0
def login():
    # 如果提交,开始处理
    if request.method == 'POST':
        # 提交,即开始验证
        # 得到用户名,密码
        session['username'] = request.form['username']
        session['password'] = request.form['password']
        username = session['username']
        password = session['password']
        # 表单提交,检查数据库中有无此用户,以及密码是否正确
        result = db.check_user(username, password)
        # 此用户名不存在
        if result is None:
            return render_template('login.html', errorMessage='此用户名不存在')
        # 密码错误
        if result[3] != password:
            return render_template('login.html', errorMessage='密码错误')
        # 如果类型为1,即为管理员,重定向到管理员界面
        if result[2] == 1:
            return redirect('admin')
        # 如果类型为0,即为普通用户,重定向到主页
        if result[2] == 0:
            return redirect(url_for('index'))
    # 如果不是提交表单,即打开登录页面
    return render_template('login.html')
Example #2
0
def main():
    global user
    while True:
        login = input("Input username:\n")
        if db.check_user(login):
            print("Welcome " + login)
            break
        else:
            verification = input(
                "User does not exist, Do you want to create a new user [Y/n]\n"
            )
            if not verification or verification == "y":
                print(db.add_user(login))
                print("Welcome " + login)
                break

    user = login
    while True:
        command = input(">>> ")
        if command:
            seq = command.split()
            if seq[0] == "quit":
                break
            parse_command(seq)
        else:
            print(
                "Usage: get [...] | create <session type> | start <session type> | end <session type> | restart"
            )
Example #3
0
def create_room():
    message = ''
    rooms = get_rooms_for_user(current_user.username)
    if request.method == "POST":
        room_name = request.form.get('room_name')
        usernames = [username.strip()
                     for username in request.form.get('members').split(',')]

        if len(room_name):
            for username in usernames:
                user = check_user(username)
                if username ==  "": 
                    
                    break
                elif user ==None :
                    print("bruhh")
                    message = f"user:\"{username}\" doesn't exist"
                    return render_template('index.html', message1=message, have_rooms=True, rooms=rooms)
                    break
            room_id = save_room(room_name, current_user.username)
            if current_user.username in usernames:
                usernames.remove(current_user.username)
            add_room_members(room_id, room_name, usernames,
                             current_user.username)
            return redirect(url_for('chat_room', room_id=room_id))
        else:
            message = 'Failed to Create room'

    return render_template('index.html', message1=message, have_rooms=True, rooms=rooms)
Example #4
0
def store_to_db(shortlist, id, update, context, change):
    if check_user(id):
        overwrite(id, shortlist)
    else:
        create_update(id, shortlist)
    update.message.reply_text("Shortlist updated!")
    return ConversationHandler.END
Example #5
0
 def POST(self):
     data = web.input()
     
     if data['user'] =="":
         return render.register(("True", "用户名不能为空"))
     
     if len(data['user']) < 2 or len(data['user']) > 16:
         return render.register(("True", "用户名长度必须在2~16个字符之间"))
     
     if data['passwd1'] == "" or data['passwd2'] == "":
         return render.register(("True", "密码不能为空"))
     
     if data['passwd1'] != data['passwd2']:    #密码不一致
         return render.register(("True", "两次密码不一致,请重新输入!!"))
     
     if len(data['passwd1']) < 6 or len(data['passwd1']) > 20:
         return render.register(("True", "密码长度必须在6~20个字符之间"))
     
     user = data['user'].encode("UTF-8")
     if db.check_user(user):    
         return render.register(("True","用户名已经存在,请重新输入!!"))
     
     db.new_count(user, data['passwd1'])
     web.ctx.session.login = True
     web.ctx.session.uname = user
     
     up = image.Upload()
     up.operate()
 
     web.ctx.session.photo = db.get_photo(user)
     
     raise web.seeother('/information')
Example #6
0
def passchange():
    if request.method == 'GET':
        return render_template("pwchange.html")
    if db.check_user(request.form['username'],request.form['password']) and request.form['new'] == request.form['confirm']:
        db.change_pass(request.form['username'],request.form['new'])
        return render_template("pwchange.html",error="Password changed successfully.")
    else:
        return render_template("pwchange.html",error="Incorrect username and password combination or new passwords don't match.")
Example #7
0
	def post(self):
		username = self.get_argument("username", "")
		password = self.get_argument("password", "")
		result, value = db.check_user(username, password)
		if not result:
			self.render("login.html", alert=value)
		else:
			self.set_current_user(username, value)
			self.redirect("/")
Example #8
0
def login():
    if 'username' in session:
        return redirect(url_for('read'))
    if request.method == 'GET':
        return render_template("login.html")
    else:
        if db.check_user(request.form['username'],request.form['password']):
            session['username'] = request.form['username']
            return redirect(url_for('read'))
        else:
            return render_template("login.html", error="Wrong username/password combination")
Example #9
0
def display_selected(update, context):
    #checks if the user has shortlisted stock(s) previously
    update.message.reply_text("Searching...")
    if check_user(id):
        stocks = retrieve_stocks(id)
        update.message.reply_text(f'This is what you have shortlisted: {stocks}')
        stocks = stocks.split(' ')
        for ticker in stocks:
            enter(update, context, ticker)
    else:
        update.message.reply_text("User has not shortlisted any")
Example #10
0
def login():
    if (request.method == "POST"):
        username = request.form["username"]
        password = request.form["password"]

        success, msg = check_user(session, username, password)
        if (success):
            return redirect(url_for("listfile", token=msg))
        else:
            return render_template("login.html", error=msg)
    return render_template("login.html")
def login(request):
    if request.method == 'GET':
        return render_template('login.html')

    if request.method == 'POST':
        success, msg = check_user(session, request.form['username'],
                                  request.form['password'])

        if success:
            request.session['username'] = request.form['username']
            request.session['name'] = msg
            return redirect('/')
        else:
            return render_template('login.html', error=msg)
Example #12
0
def login():
    if request.method == 'GET':
        session['log'] = '0'
        return render_template("login.html")
    elif request.method == 'POST':
        data = request.json
        user_id = check_user(data['login'], data['passwd'])
        if user_id > -1:
            session['log'] = '1'
            session['user'] = user_id
            return jsonify({"status": "OK"})
        else:
            session['log'] = '0'
            return jsonify({"status": "ERROR"})
Example #13
0
def login():
    uname = session.get("username")
    if uname and user_exists(uname):
        return redirect("/")
    err = None
    if request.method == "POST":
        username = request.form.get("username", None)
        password = request.form.get("password", None)

        ok, err = check_user(username, password)
        if ok:
            session["username"] = username
            return redirect("/")

    return render_template("login.html", err=err)
Example #14
0
def check_user():
    '''
        Verifies username and password
    '''
    requires = ["username", "password"]  # #
    failed = bad_request(requires)
    if failed is not None:
        return failed

    username = request.json['username']  # # #
    password = request.json['password']

    user = db.check_user(username, password)
    if user is None:
        return {"msg": "username or password not found"}
    else:
        return user
Example #15
0
 def start_message(message):
     try:
         check_user = db.check_user(message.from_user.id)
         if check_user:
             # НЕ В ПЕРВЫЙ РАЗ
             bot.send_message(message.chat.id,
                              text=text_.repeat_start(),
                              reply_markup=keybaord.lang())
             save_user_profile_photo(message)
         else:
             # В ПЕРВЫЙ РАЗ
             bot.send_message(message.chat.id,
                              text=text_.first_start(),
                              reply_markup=keybaord.lang())
             db.add_user(message.from_user.id, message.from_user.username)
             save_user_profile_photo(message)
     except Exception as e:
         print(e)
Example #16
0
def login():
    if request.method == 'POST':
        if not checkloginstat():
            name = db.check_user(request.form['api_key'])

            if name == None:
                return 'wrong key'
            else:
                res = make_response(
                    render_template('logedin.html',
                                    username=name,
                                    k=request.form['api_key']))
                res.set_cookie('logedin', value='true', max_age=260000000)
                return res
        else:
            return redirect('https://api.matthew.tk/')
    elif checkloginstat():
        return redirect(url_for('already_logged'))
    else:
        return render_template('keysubmit.html')
Example #17
0
def login():
    username = request.values.get('username', '')
    password = request.values.get('password', '')

    ret_data = {}
    is_login = db.check_user(username, password)
    if is_login:
        ret_data['status'] = 'ok'
    else:
        ret_data['status'] = 'error'
        ret_data['message'] = 'Username or password is wrong!'
        
    resp = Response(json.dumps(ret_data))
    
    if is_login:
        # New and save `uid` to cookie
        cookie = SecureCookie(secret_key=app.secret_key)
        cookie['uid'] = username
        cookie['is_guest'] = False
        cookie.save_cookie(resp, key='auth', max_age=USER_COOKIE_AGE)
        
    return resp
Example #18
0
def login():
    username = request.values.get('username', '')
    password = request.values.get('password', '')

    ret_data = {}
    is_login = db.check_user(username, password)
    if is_login:
        ret_data['status'] = 'ok'
    else:
        ret_data['status'] = 'error'
        ret_data['message'] = 'Username or password is wrong!'

    resp = Response(json.dumps(ret_data))

    if is_login:
        # New and save `uid` to cookie
        cookie = SecureCookie(secret_key=app.secret_key)
        cookie['uid'] = username
        cookie['is_guest'] = False
        cookie.save_cookie(resp, key='auth', max_age=USER_COOKIE_AGE)

    return resp
Example #19
0
 def start_message(message):
     try:
         check_user = db.check_user(message.from_user.id)
         if check_user:
             # НЕ В ПЕРВЫЙ РАЗ
             bot.send_message(message.chat.id,
                              text=f'{emoji.FLAG_RUSSIA}Уже всё давно настроено.\n'
                                   f'Отправьте мне свое черно-белое фото, и я его раскрашу'
                                   f'{emoji.RAINBOW}\n\n'
                                   f'{emoji.FLAG_UNITED_STATES}Everything works.\n'
                                   f'Send me your black and white photo, and we will color it'
                                   f'{emoji.RAINBOW}')
         else:
             # В ПЕРВЫЙ РАЗ
             bot.send_photo(message.chat.id, example_photo)
             bot.send_message(message.chat.id,
                              text=f'{emoji.FLAG_RUSSIA}Отправьте мне свое черно-белое фото, и я его раскрашу'
                                   f'{emoji.RAINBOW}\n\n'
                                   f'{emoji.FLAG_UNITED_STATES}Send me your black and white photo, and we will color it'
                                   f'{emoji.RAINBOW}')
             db.add_user(message.from_user.id, message.from_user.username)
     except Exception as e:
         print(repr(e))
Example #20
0
def api_main(access_token_json):
    """ Takes the JSON file returned from the Instagram OAuth and updates the
        database with that data and returns the username of the user so other
        functions can call that in the future.
    """

    username, access_token = get_token_and_username(access_token_json)

    insta_json_data = call_instagram_api(access_token)

    list_img = []
    if not check_user(username):
        list_img = get_list_of_img_id(username)

    user_info = read_insta_json(insta_json_data, list_img)
    #Iterate through all of the lists in user info

    for i in user_info:
        image_url = i[0]
        image_id = i[1]
        download_image(image_url, image_id)

        labels, is_spoof, is_racy, landmark, has_text, has_face, emotion = analyze_file(
            'app/static/img/' + image_id + '.jpg')
        google_image_output = [
            labels, is_spoof, is_racy, landmark, has_text, has_face, emotion
        ]

        i.append(google_image_output)

    # Get the information from the database using the output_db function.
    # The return values from this would only be the newly updated images that
    # didn't already exist on the database beforehand.

    update_db(username, user_info)

    return username
Example #21
0
def auth(username):
    row = check_user(username)
    return row[0] if row else None
Example #22
0
remote_ipaddr1 = config.get('liqpay', 'remote_ipaddr1')
remote_ipaddr2 = config.get('liqpay', 'remote_ipaddr2')

remote_ipaddr = os.environ["REMOTE_ADDR"]

cgitb.enable()
date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Info_Client = dict()
Answer_Liqpay = dict()
form = cgi.FieldStorage()

if (form.getvalue('action') is not None and form.getvalue('login') is not None
        and form.getvalue('summ')):

    if form.getvalue('action') == 'check':
        Info_Client['server'] = db.check_user(form.getvalue('login'))
        Info_Client['login'] = form.getvalue('login')
        commission = float(form.getvalue('summ')) / 100 * float(
            persent_commission) + float(form.getvalue('summ')) / 100 * float(
                persent_commission) / 100 * float(persent_commission)
        Info_Client['summ'] = float(form.getvalue('summ')) + commission
        Info_Client['summ'] = float(form.getvalue('summ')) + commission + 0.01
        url = """https://www.liqpay.ua/api/pay?public_key=%s\
&amount=%s&currency=UAH\
&description=%s\
&type=buy&pay_way=card,delayed\
&language=ru\
&server_url=http://%s""" % (key, Info_Client['summ'], Info_Client['login'],
                            server_url)
        aResult = """Content-type: text/html \n\n
                       <!DOCTYPE html>
Example #23
0
    async def on_message(self, message):

        # Основная функция для игры и кручения казиныча
        if message.content.startswith('$play'):
            if db.check_user(str(message.author.id)):
                cont = message.content.split()
                if len(cont) > 1:
                    # Кручение на заданую ставку
                    bet = float(cont[1])
                    await roll_casino(bet, message)
                else:
                    # Кручение на 1 копейку
                    await roll_casino(1, message)

            else:
                await message.reply(
                    'Вы еще не зарегистрированы!\nДля регистрации напишите $reg'
                )

        # Регистрация нового пользователя
        if message.content.startswith('$reg'):
            if (db.check_user(str(message.author.id))):
                await message.reply(
                    'Вы уже зарегистрированы! Для просмотра баланса напишите $bal'
                )
            else:
                db.add_user(str(message.author), str(message.author.id))
                await message.reply('Вы были успешно зарегистрированы!')

        # Проверка баланса
        if message.content.startswith('$bal'):
            if (db.check_user(str(message.author.id))):
                a = db.get_bal(str(message.author.id))
                await message.reply('Ваш баланс составляет: ' + str(a[0]) +
                                    ' копеек!')
            else:
                await message.reply(
                    'Вы еще не зарегистрированы!\nДля регистрации напишите $reg'
                )

        # Вывод помощи
        if message.content.startswith('$help'):
            await message.reply(file=discord.File('img/papich.gif'))
            await message.reply(
                'Здравствуйте ' + message.author.name +
                '!\nМеня зовут Казиныч бот 🤖, я был создан специально по заказу величайших участников конференции Distance learning и призван крутить казиныч для все желающих работяг 👨‍🏭\n'
                +
                'Основная валюта в нашем казиныче - копейки 💰, но так же у нас есть специальные сезонные ивенты 🔥, так что следите за новостями\n'
                +
                'Что я могу: \n$play [ставка] - крутить казиныч\n$reg - зарегистрировать работягу в рабочий класс и выдать первые микрогрошы\n$bal - посмотреть баланс\n'
                +
                '$update - обновить свой ник в базе данных\n$trans <money> @<user>- передать средства другому игроку'
                + 'Желаю всем быть на удачичах и грошоподнималычах 🍀!')

        # Перевод денег с одного счета на другой
        if message.content.startswith('$trans'):
            if db.check_user(str(message.author.id)):
                cont = message.content.split(
                )  # Получаем все необходимые данные
                if len(cont) == 3:
                    money = float(cont[1])  # Записываем количество денег
                    recipient = str(cont[2])
                    recipient = recipient[3:len(recipient) -
                                          1]  # Записываем Id получателя
                    if db.check_user(recipient):  # Если получатель существует
                        source = str(
                            message.author.id)  # Записываем Id отправителя
                        balance = db.get_bal(source)
                        balance = float(str(
                            balance[0]))  # Получаем баланс отправителя
                        if (balance >= money):  # Если его хватает
                            balance_r = db.get_bal(recipient)
                            balance_r = float(str(
                                balance_r[0]))  # Получаем баланс получателя
                            db.update_bal(source, str(balance - money))
                            db.update_bal(recipient,
                                          str(balance_r +
                                              money))  # Обновляем балансы
                            r_n = db.get_name(str(recipient))
                            await message.reply(
                                'Операция прошла успешно!\nВы передали ' +
                                str(money) + ' копеек работяге ' + str(r_n[0]))
                        else:
                            # Если недостаточно средств
                            await message.reply(
                                'У вас недостаточно средств для перевода!')
                    else:
                        # Если получатель не найден
                        await message.reply('Данный пользователь не найден!')
                else:
                    # Вывод ошибки
                    await message.reply(
                        'Вы неправильно написали комамнду! Правильный формат - $trans [сумма] [имя + id пользователя]'
                    )

            else:
                await message.reply(
                    'Вы еще не зарегистрированы!\nДля регистрации напишите $reg'
                )

        #Обновление ника в базе данных
        if message.content.startswith('$update'):
            if db.check_user(str(message.author.id)):
                db.update_name(str(message.author.id), str(message.author))
                await message.reply('Вы успешно сменили ник на ' +
                                    str(message.author) + '!')
            else:
                await message.reply(
                    'Вы еще не зарегистрированы!\nДля регистрации напишите $reg'
                )
Example #24
0
def edit_room(room_id):
    room = get_room(room_id)
    admins = []
    not_admin = []
    error_msg = ''
    message = ''
    if room and is_room_admin(room_id, current_user.username):

        members = get_room_members(room_id)
        members_list = [username['_id']['username'] for username in members]
        for member in members:
            if is_room_admin(room_id, member['_id']['username']):
                admins.append(member['_id']['username'])
            else:
                not_admin.append(member['_id']['username'])
        if request.method == "POST":
            room_name = request.form.get('room_name')
            room['name'] = room_name
            update_room(room_id, room_name)
            make_admin = request.form.get('makeAdmin')
            removeAdmin = request.form.get('removeAdmin')
            add_member = request.form.get('addmember')
            rem_mem = request.form.get('remove_user')
            rem_room = request.form.get('delete_room')

            if make_admin:
                try:
                    update_admin(room_id, make_admin)
                    message = '{} is now an Admin🥳'.format(make_admin)
                except:
                    error_msg = 'Some error occured'

            if removeAdmin:
                try:
                    if len(admins) > 1:
                        remove_admin(room_id, removeAdmin)
                        message = '{} is no longer an Admin'.format(
                            removeAdmin)
                    else:
                        message = 'Atleast one admin should be present'
                except:
                    error_msg = 'Some error occured'

            if add_member:
                try:
                    user = check_user(add_member)
                    if user:
                        if add_member not in members_list:
                            add_mems = [username.strip()
                                        for username in add_member.split(',')]
                            add_room_members(room_id, room_name, add_mems,
                                             current_user.username)
                            message = '\"{}\" added successfully'.format(
                                add_member)
                        else:
                            message = "\"{}\" already in room".format(
                                add_member)
                    else:
                        message = "\"{}\" does not exist :(".format(add_member)
                except:
                    error_msg = "Some error occured"

            if rem_mem:
                is_admin = is_room_admin(room_id, rem_mem)
                try:
                    if len(members_list) > 1:
                        if is_admin and len(admins) == 1:
                            message = 'Atleast one Admin should be present '
                        else:
                            remove_room_member(room_id, rem_mem)
                            message = '{} removed successfully'.format(rem_mem)
                    else:
                        message = 'Atleast one member should be present'
                except:
                    error_msg = "Some error occured"
            if rem_room == 'Remove':
                try:
                    for member in members_list:
                        print("hi")
                        remove_room_member(room_id, member)
                    delete_room(room_id)
                    return redirect(url_for('home'))

                except:
                    error_msg = "Some error oocured"

                # return redirect(url_for('edit_room',room_id=room_id,message = message))

        return render_template('edit_room.html', not_admin=not_admin, admins=admins, room=room, members=members, error_msg=error_msg, room_id=room_id, message=message)

    else:
        return render_template('404.html', message='Only admins can Edit Room', room_id=room_id)
Example #25
0
def callback_inline(call):
    try:
        if call.message:
            if call.data == 'print_animeser':
                send_last_news(call.message.chat.id, 'animeser')
            elif call.data == 'print_animemov':
                send_last_news(call.message.chat.id, 'animemov')
            elif call.data == 'print_movies':
                send_last_news(call.message.chat.id, 'movies')
            elif call.data == 'print_games':
                send_last_news(call.message.chat.id, 'games')
            elif call.data == 'sub_animeser':
                if check_user(call.message.chat.id, 'animeser'):
                    bot.send_message(call.message.chat.id,
                                     'Вы уже подписаны на этот раздел!')
                else:
                    update_(call.message.chat.id, 'animeser', True)
                    bot.send_message(call.message.chat.id,
                                     'Вы успешно подписались на этот раздел!')
            elif call.data == 'sub_animemov':
                if check_user(call.message.chat.id, 'animemov'):
                    bot.send_message(call.message.chat.id,
                                     'Вы уже подписаны на этот раздел!')
                else:
                    update_(call.message.chat.id, 'animemov', True)
                    bot.send_message(call.message.chat.id,
                                     'Вы успешно подписались на этот раздел!')
            elif call.data == 'sub_movies':
                if check_user(call.message.chat.id, 'movies'):
                    bot.send_message(call.message.chat.id,
                                     'Вы уже подписаны на этот раздел!')
                else:
                    update_(call.message.chat.id, 'movies', True)
                    bot.send_message(call.message.chat.id,
                                     'Вы успешно подписались на этот раздел!')
            elif call.data == 'sub_games':
                if check_user(call.message.chat.id, 'games'):
                    bot.send_message(call.message.chat.id,
                                     'Вы уже подписаны на этот раздел!')
                else:
                    update_(call.message.chat.id, 'games', True)
                    bot.send_message(call.message.chat.id,
                                     'Вы успешно подписались на этот раздел!')
            elif call.data == 'unsub_animeser':
                if not check_user(call.message.chat.id, 'animeser'):
                    bot.send_message(call.message.chat.id,
                                     'Вы ещё не подписались на этот раздел!')
                else:
                    update_(call.message.chat.id, 'animeser', False)
                    bot.send_message(
                        call.message.chat.id,
                        'Вы успешно отписались от этого раздела!')
            elif call.data == 'unsub_animemov':
                if not check_user(call.message.chat.id, 'animemov'):
                    bot.send_message(call.message.chat.id,
                                     'Вы ещё не подписались на этот раздел!')
                else:
                    update_(call.message.chat.id, 'animemov', False)
                    bot.send_message(
                        call.message.chat.id,
                        'Вы успешно отписались от этого раздела!')
            elif call.data == 'unsub_movies':
                if not check_user(call.message.chat.id, 'movies'):
                    bot.send_message(call.message.chat.id,
                                     'Вы ещё не подписались на этот раздел!')
                else:
                    update_(call.message.chat.id, 'movies', False)
                    bot.send_message(
                        call.message.chat.id,
                        'Вы успешно отписались от этого раздела!')
            elif call.data == 'unsub_games':
                if not check_user(call.message.chat.id, 'games'):
                    bot.send_message(call.message.chat.id,
                                     'Вы ещё не подписались на этот раздел!')
                else:
                    update_(call.message.chat.id, 'games', False)
                    bot.send_message(
                        call.message.chat.id,
                        'Вы успешно отписались от этого раздела!')
    except Exception as e:
        print(repr(e))