def test_validate_confirmation_token(self): # Ensure valid token can be successfully confirmed in the views timestamp = time.time() token = generate_confirmation_token('*****@*****.**', 1, timestamp) with self.client: self.client.post('/login', data=dict(email='*****@*****.**', password='******'), follow_redirects=True) response = self.client.get('/confirm/' + str(token), follow_redirects=True) user = User() user = user.get('username', '*****@*****.**', g.rdb_conn) self.assertTrue(user.confirmed) self.assertEqual(response.status_code, 200) self.assertIn('Dashboard', response.data) self.assertIn('You have confirmed your account. Thanks!', response.data)
def signUpPage(): if request.method == 'POST': username = request.form["name"] password = request.form["pass"] if username is None or password is None: return redirect(url_for("signUpPage")) if session.query(User).filter_by( username=username).first() is not None: flash("user already exits") return redirect(url_for("signUpPage")) user = User(username=username) user.hash_password(password) session.add(user) session.commit() flash("New Id Created!") return redirect(url_for("loginPage")) else: return render_template('signUp.html')
def test_user_registration(self): # Ensure user registration behaves correctly. with self.client: response = self.client.post('/signup', data=dict(email='*****@*****.**', company="test", contact="test", password='******', confirm='test_user'), follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertIn('Dashboard', response.data) user = User() user = user.get('username', '*****@*****.**', g.rdb_conn) self.assertTrue(user.email == '*****@*****.**') self.assertTrue(user.status == 'active') self.assertFalse(user.confirmed) self.assertTrue(user.is_active('*****@*****.**', g.rdb_conn))
def test_validate_confirmation_token_invalid_email(self): # Ensure invalid email cannot be successfully confirmed in the views timestamp = time.time() token = generate_confirmation_token('*****@*****.**', 1, timestamp) with self.client: self.client.post('/login', data=dict(email='*****@*****.**', password='******'), follow_redirects=True) response = self.client.get('/confirm/' + str(token), follow_redirects=True) user = User() user = user.get('username', '*****@*****.**', g.rdb_conn) self.assertFalse(user.confirmed) self.assertEqual(response.status_code, 200) self.assertIn('Login', response.data) self.assertIn('The confirmation link is invalid', response.data)
class Database: ''' Database class contains tables. ''' #Add self.users = {} self.groups = {} self.loggedInAs = None all_privs = {'Create_User' : True, 'Delete_Tbl' : True} #admin admin = User('admin', 'admin', all_privs, set(), set()) self.users.update({'admin': admin}) self.loggedInAs = admin #groups admin_group = Group('admins', {'Create_User' : True, 'Delete_Tbl' : True}, set(), set()) self.groups.update({'admins': admin_group}) viewer_group = Group('admins', {}, set(), set()) self.groups.update({'viewers': viewer_group})
def register(self): print('> username: '******'> password: '******'> password again: ') while new_pass != password: print('Passwords don\'t match.') new_pass = getpass.getpass('> password again: ') print('> age: ') age = input() print('> gender (optional): ') gender = input() user = User() if user.init_components(username, password, age, gender): insert_user(user) Menu.__doc_promotion(user) Menu.__patient_promotion(user) self.register()
def register(): # force logout # logout_user() email = request.form['email'] password = request.form['password'] location = request.form['ZipCode'] user = User(email=email, location=location) user.password = password # this calls the hash setter try: user.tomongo() return Response(json.dumps({'success': True}), 200, {'ContentType': 'application/json'}) except Exception as e: print(e) return Response(json.dumps({'success': False}), 500, {'ContentType': 'application/json'})
def viewhistory_page(cid, start, limit): verify = verifyLogin( app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/view-history/' + cid tmpl = 'monitors/view-history.html' # Check Users Status if user.status != "active": data['url'] = '/dashboard/mod-subscription' tmpl = 'member/mod-subscription.html' else: monitor = Monitor() monitor.get(cid, g.rdb_conn) if monitor.uid == user.uid: data['monitor'] = { 'cid': monitor.cid, 'name': monitor.name, 'ctype': monitor.ctype, 'uid': monitor.uid, 'data': monitor.data } chktime = time.time() - float(data['dataret']) data['monitor-history-count'] = monitor.history( method="count", time=chktime, rdb=g.rdb_conn) data['monitor-history'] = monitor.history( method="mon-history", time=chktime, start=int(start), limit=int(limit), rdb=g.rdb_conn) data['monitor-history-paging'] = [] data['monitor-history-paging-start'] = int(start) cur = 0 while cur < data['monitor-history-count'] - 200: cur = cur + 200 data['monitor-history-paging'].append(cur) else: flash('This monitor does not belong to your user.', 'warning') page = render_template(tmpl, data=data) return page else: flash('Please Login.', 'warning') return redirect(url_for('user.login_page'))
def checkaction_page(cid, action): ''' Dashboard Update Checks: This will update health checks via the url parameters ''' verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.config = app.config user.get('uid', verify, g.rdb_conn) if user.status != "active": pass else: # Update the Monitor monitor = Monitor(cid) monitor.config = app.config monitor.get(cid, g.rdb_conn) if user.uid == monitor.uid: if action == "false": monitor.healthcheck = "web-false" result = monitor.webCheck(g.rdb_conn) print("/dashboard/action-checks - Manual monitor failure") elif action == "true": monitor.healthcheck = "web-true" print("/dashboard/action-checks - Manual monitor true") result = monitor.webCheck(g.rdb_conn) if result: print("/dashboard/action-checks - Manual monitor queued") flash('Health check status change is queued.', 'success') else: print("/dashboard/action-checks - \ Manual monitor action failed") flash( 'Something went wrong. \ Could not modify health check.', 'danger') else: print("/dashboard/action-checks - \ Manual monitor action failed: do not own") flash('It does not appear you own this health check.', 'danger') return redirect(url_for('member.dashboard_page'))
def monitors_page(): verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.config = app.config user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/monitors/' data['monitor_list'] = app.config['MONITORS'] tmpl = 'monitors/index.html' data['js_bottom'] = [ 'monitors/monitorlist.js', ] # Check Users Status if user.status != "active": data['url'] = '/dashboard/mod-subscription' tmpl = 'member/mod-subscription.html' else: pass data['monitors'] = user.getMonitors(g.rdb_conn) data['reactions'] = user.getReactions(g.rdb_conn) # If there are no monitors print a welcome message if len(data['monitors']) < 1 and len(data['reactions']) < 1: data['welcome'] = True else: data['welcome'] = False if len(data['monitors']) < 1: data['mons'] = False else: data['mons'] = True if len(data['reactions']) < 1: data['reacts'] = False else: data['reacts'] = True page = render_template(tmpl, data=data) return page else: flash('Please Login.', 'warning') return redirect(url_for('user.login_page'))
def createGuestRequest(userId, password, courseName): session = server.DBSession() user = session.query(User).filter(User.username == userId).first() if (user != None or user == '' or password == '' or courseName == ''): return -1 u = User() u.username = userId u.password = password # The user role is changed to guest upon approval of their request. u.role = "unassigned" u.courses = [courseName] u.surveysResponded = [] u.authenticated = False session.add(u) session.commit() session.close() return 1
def __init__(self, i_playlist=0, i_user=0, config=None): self.id = 0 self.name = False self.description = False self.i_user = 0 self.owner = User() self.songs = [] self.count = 0 if config: self.Config = config else: self.Config = Config() if i_user: self.i_user = i_user if i_playlist: self.open(i_playlist)
def login(): user_list = Users.objects error = "" try: if request.method == "POST": u = request.form['username'] p = request.form['password'] for user in user_list: if user.username == u and user.password == p: user = User() login_user(user, remember=False) return redirect(url_for("index")) error = "Invalid credentials. Please try again!" except Exception as e: flash(e) return render_template("login.html", error=error) return render_template('login.html', error=error)
def __init__(self, name, load=True): self.users = {} self.groups = {} self.loggedInAs = None all_privs = {'Create_User' : True, 'Delete_Tbl' : True} #admin admin = User('admin', 'admin', all_privs, set(), set()) self.users.update({'admin': admin}) self.loggedInAs = admin #groups admin_group = Group('admins', {'Create_User' : True, 'Delete_Tbl' : True}, set(), set()) self.groups.update({'admins': admin_group}) viewer_group = Group('admins', {}, set(), set()) self.groups.update({'viewers': viewer_group}) self.tables = {} self._name = name self.savedir = f'dbdata/{name}_db' if load: try: self.load(self.savedir) print(f'Loaded "{name}".') return except: print(f'"{name}" db does not exist, creating new.') # create dbdata directory if it doesnt exist if not os.path.exists('dbdata'): os.mkdir('dbdata') # create new dbs save directory try: os.mkdir(self.savedir) except: pass # create all the meta tables self.create_table('meta_length', ['table_name', 'no_of_rows'], [str, int]) self.create_table('meta_locks', ['table_name', 'locked'], [str, bool]) self.create_table('meta_insert_stack', ['table_name', 'indexes'], [str, list]) self.create_table('meta_indexes', ['table_name', 'index_name'], [str, str]) self.save()
def login(): user = User() if request.method == "POST": user.get_user(request.form['username']) if user.username == 'Random': return "User not in database." if user.passcomp(request.form['password']) == True: session['username'] = request.form['username'] session['i_user'] = user.id session['i_playlist'] = 0 print "request.get['next'] = {0}".format(request.args.get('next')) return redirect(api.redirect_url(request)) else: return "Login Incorrect" else: return render_template('login.html', api=api)
def set_city(message): """ Method to change the city and country of user in database. :param message: Message from user. It looks like JSON ( learn more at https://tlgrm.ru/docs/bots/api#message ). :return: """ try: chat_id = message.chat.id location = message.text.split(',') city = location[0] country = location[1] except Exception as err: print(err) bot.reply_to(message, 'Try again...') bot.register_next_step_handler(message, set_city) else: user = User() user.change_location_for_user(chat_id, city, country) bot.send_message(chat_id, 'Your city updated!')
def update_tags(name): tag_name = yield name print(f'tag_name = {tag_name}') u = User() u.chat_id = list(Tags.handlers.keys())[-1] u.getTags() tags = u.choose_tags(tag_name.lower().strip()) print(f'tags = {tags}') while len(tags) == 0: new_name = yield "Набора з такою назвою не існує. Повторіть або напишіть ВИХІД" if new_name.lower().strip() == 'вихід': u.changeScope('general') finish = yield 'Наступного разу вийде краще ))' break else: tag_name = new_name tags = u.choose_tags(tag_name.lower().strip()) question = yield from add_or_remove_tag( f'Зараз в цьому наборі такі ключові слова: {tags}', tag_name, tags)
def test_already_confirmed(self): # Ensure user is redirected if already confirmed timestamp = time.time() token = generate_confirmation_token( '*****@*****.**', 1, timestamp) with self.client: self.client.post('/login', data=dict( email='*****@*****.**', password='******' ), follow_redirects=True) user = User() user = user.get('username', '*****@*****.**', g.rdb_conn) r.table('users').get(user.uid).update( {'confirmed': True}).run(g.rdb_conn) response = self.client.get( '/confirm/'+str(token), follow_redirects=True) self.assertEqual(response.status_code, 200) self.assertIn('Runbooks', response.data) self.assertIn('Account already confirmed. Thank you.', response.data)
def process_batch_input(batch_input_file, output_log, logger): global index #with open('.' + batch_input_file, 'r') as f: with open(batch_input_file, 'r') as f: for idx, line in enumerate(f.readlines()): #logger.info('File %s: Processing line numer: %d', batch_input_file, idx) line.rstrip() json_line = json.loads(line) if 'D' in json_line: degree = json_line['D'] num_tracked = json_line['T'] #logger.info('Degree of network = %s number of tracked purchases = %s', degree, num_tracked) social_network = SocialNetwork(output_log, degree, num_tracked) elif json_line['event_type'] == 'purchase': timestamp = json_line['timestamp'] purchase_amount = float(json_line['amount']) purchase = (-1 * index, timestamp, purchase_amount) user_id = json_line['id'] if not user_id in social_network.network: # create user user = User(user_id, num_tracked) # add his purchase user.add_purchase(purchase) # add user to network social_network.add_user(user) else: user = social_network.network[user_id] user.add_purchase(purchase) elif json_line['event_type'] in ['befriend', 'unfriend']: user1_id = json_line['id1'] user2_id = json_line['id2'] timestamp = json_line['timestamp'] event_type = json_line['event_type'] if event_type == 'befriend': social_network.add_friend(user1_id, user2_id) elif event_type == 'unfriend': social_network.remove_friend(user1_id, user2_id) index += 1 return social_network
def register(): log = input('What is your name? :') while log in User.population.keys(): log = input('this name is already taken, choose another name:') while True: pw1 = input('type your password: '******'password have to consists of letters and numbers: ') pw1 = input('type your password: '******'please repeat your password: '******'t match") else: u = User(log, pw1) return u
def reactions_page(): verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.get('uid', verify, g.rdb_conn) data = startData(user) data['active'] = 'dashboard' data['url'] = '/dashboard/reactions/' tmpl = 'reactions/index.html' # Check Users Status if user.status != "active": data['url'] = '/dashboard/mod-subscription' tmpl = 'member/mod-subscription.html' else: pass page = render_template(tmpl, data=data) return page else: return redirect(url_for('user.login_page'))
def file_recieve(message): if message.document: path = file_saver.save_file(message.chat.id, message.text) next_notify_time = datetime.datetime.now() + test_notify_delta[0] new_memo = Memo(user_id=message.chat.id, memo_type="text", memo_name=memo_name.pop(message.chat.id), link=path, notify_time=next_notify_time, notify_count=0) user = User(message.chat.id) user.add_memo(new_memo=new_memo) bot.send_message( message.chat.id, "<b>Мемо успешно создан.</b>\n" "Включи уведомления и я буду присылать тебе напоминания.", parse_mode='html', reply_markup=keyboards.back_to_main) bot.clear_step_handler_by_chat_id(chat_id=message.chat.id)
def login(username): #the message contains the request type + the client's username to be checked request = Request(Method.CHECK_USER, username) clientSocket.send(pickle.dumps(request)) #receive response from server response = clientSocket.recv(1024) response = pickle.loads(response) if response.status == Status.ERROR: #the username is already taken; inform the user and exit exitGracefully(4) else: user = User(username) assignedPort = response.body if assignedPort: daemon = threading.Thread(target=daemon_listener, args=[assignedPort], daemon=True) daemon.start() print("username legal, connection established.")
def userAuthenticated(): code = request.args['code'] payload = { 'client_id': client_id, 'client_secret': clientSecret, 'redirect_uri': redirect_uri, 'code': code, 'grant_type': 'authorization_code' } try: response = requests.post(fenixacesstokenpage, params=payload) if response.status_code == 200: r_json = response.json() user = User(r_json['access_token']) user_list.append(user) return redirect('/?key=' + user.key) abort(401) except requests.exceptions.RequestException: abort(500)
def insertData(self): username = self.name_lineEdit.text() password = self.password_lineEdit.text() if (not username) or (not password): msg = QMessageBox.information(self, 'Внимание!', 'Вы не заполнили все поля.') return if Validate.validate_login( username) is None and Validate.validate_password( password) is None: msg = QMessageBox.information( self, 'Внимание!', 'И логин и пароль введены неправильно') return if Validate.validate_login(username) is None: msg = QMessageBox.information(self, 'Внимание!', 'Такой логин задать нельзя') return if Validate.validate_password(password) is None: msg = QMessageBox.information(self, 'Внимание!', 'Такой пароль задать нельзя') return if Validate.validate_login(username) and Validate.validate_password( password): user = User(username, password, randint(1, 999999)) spi = { 'username': user.login, 'password': user.password, 'id': user.uniq_id } with open("all_users.json", 'a+') as file: json.dump(spi, file) msg = QMessageBox.information(self, 'Успех', str(spi)) return
def delreaction_page(rid): ''' Dashboard Delete Domains: This will delete a domain based on url parameters ''' verify = verifyLogin(app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies) if verify: user = User() user.config = app.config user.get('uid', verify, g.rdb_conn) if user.status != "active": pass else: appliedcount = 0 results = r.table('monitors').filter({ 'uid': user.uid }).run(g.rdb_conn) for x in results: monitor = Monitor() monitor.config = app.config monitor.get(x['id'], g.rdb_conn) mondata = monitor.data if rid in mondata['reactions']: appliedcount = appliedcount + 1 if appliedcount < 1: # Delete the Reaction reaction = Reaction(rid) reaction.config = app.config result = reaction.deleteReaction(user.uid, rid, g.rdb_conn) if result: flash('Reaction was successfully deleted.', 'success') else: flash('Reaction was not deleted.', 'danger') else: flash( 'You must first detach this reaction \ from all monitors before deleting.', 'danger') return redirect(url_for('member.dashboard_page'))
def gmix(request): user = User(request) if user.type == 'email': local_player = get_or_create_player(user.email) if user.pref_true('local_public'): local_player.owner = 'sys' else: local_player.owner = user.full_email save_player(local_player) style = user.pref_value("style") if style == 0: style = 'blue' players = get_active_players() return render_to_response( 'gmix/index.html', { 'players': players, 'style': style, 'styles': STYLES, 'user': user, 'local_public': user.pref_true('local_public') })
def login(): login = 0 # 0 - login / 1 - login com sucesso/ 2 - login invalido/ 3 - senha invalida cur = mysql.connection.cursor() if request.method == "POST": username = request.form["username"] password = request.form["password"] cur.execute("SELECT username, password FROM admin WHERE username = '******';".format(username)) tup = cur.fetchone() if not tup: login = 2 else: if tup[1] != password: login = 3 else: login = 1 user = User(tup[0],tup[1]) login_user(user) return render_template("home.html") return render_template("home.html")
def login(): login = 0 # 0 - login / 1 - login com sucesso/ 2 - login invalido/ 3 - senha invalida cur = mysql.connection.cursor() if request.method == "POST": username = request.form["lg_username"] password = request.form["lg_password"] cur.execute("SELECT login, password, picture FROM members WHERE login = '******';".format(username)) tup = cur.fetchone() if not tup: login = 2 else: if tup[1] != password: login = 3 else: login = 1 user = User(tup[0],tup[1],tup[2]) login_user(user) return render_template("home.html", pic = current_user.picture) return render_template("login.html")
def main(): load() current_id = None while True: try: updates = bot.get_updates(offset=current_id).wait() or [] for update in updates: current_id = update.update_id + 1 msg = update.message _user = User( msg.sender.id, '%s %s' % (msg.sender.first_name, msg.sender.last_name)) add(_user) print('"%s" from %s' % (msg.text, _user.name)) handle(find_user(_user.id), msg) if not len(updates): time.sleep(0.1) except Exception as e: print(e)