def loadUserDataById(self, user_id): self.transactions.clear() self.categories.clear() self.family_users.clear() conn = pymysql.connect(host=HOST, user=USER, password=PASSWORD, db=DB, charset='utf8') cursor = conn.cursor() sql = "SELECT * FROM `users` WHERE `ID` = '%s'" % (user_id) cursor.execute(sql) result = cursor.fetchone() self.user = User(result[0], result[1], result[2], result[3], result[4], result[5]) sql = "SELECT * FROM `families` WHERE `ID` = '%d'" % ( self.user.family_id) cursor.execute(sql) result = cursor.fetchone() self.family = Family(result[0], result[1], result[2], result[3], result[4]) sql = "SELECT * FROM `categories` WHERE `Owner_ID` = '%d' OR `Owner_ID` = '0'" % ( self.user.family_id) cursor.execute(sql) result = cursor.fetchall() for s in result: self.categories.append(Category(s[0], s[1], s[2])) sql = "SELECT * FROM `users` WHERE `Family_ID` = '%d'" % ( self.user.family_id) cursor.execute(sql) result = cursor.fetchall() for s in result: self.family_users.append(User(s[0], s[1], s[2], s[3], s[4], s[5])) sql = "SELECT * FROM `transactions` WHERE `Family_ID` = '%d' ORDER BY `Datetime` DESC" % ( self.user.family_id) cursor.execute(sql) result = cursor.fetchall() for s in result: if self.family.safemode == 1 and self.user.status == 3: b_user = self.getFamilyUserById(s[4]) if b_user.status != 3: continue else: self.transactions.append( Transaction(s[0], s[1], s[2], s[3], s[4], s[5], s[6])) else: self.transactions.append( Transaction(s[0], s[1], s[2], s[3], s[4], s[5], s[6])) cursor.close() conn.close()
def registration_action(): page_title = 'Регистрация | Auth Example' error = None # Проверяем данные if not request.form['email']: error = 'Требуется ввести Email' if not request.form['password']: error = 'Требуется ввести пароль' if not request.form['password2']: error = 'Требуется ввести повтор пароля' if request.form['password'] != request.form['password2']: error = 'Пароли не совпадают' # В случае ошибки рендерим тот же шаблон, но с текстом ошибки if error: return render_template('pages/registration.html', page_title=page_title, error=error) # Добавляем пользователя Storage.add_user( User(None, request.form['email'], request.form['password'])) # Делаем вид, что добавление всегда без ошибки # Перенаправляем на главную return redirect(url_for('home'))
def post(self): name = self.request.get('username') password = self.request.get('password') verify = self.request.get('verify') email = self.request.get('email') error = {} # let's check if user already exists user = User.by_name(name) if user: error['name'] = "User already exists" # let's check if a name it's been introduced and its format name_ok = name and validate(name, '^[a-zA-Z0-9_-]{3,20}$') if not name_ok: error['name'] = "That's not a valid user name" # let's check there is a password and its format password_ok = password and validate(password, '^.{3,20}$') if not password_ok: error['password'] = "******" # let's check the verify password is the same as the password if verify != password: error['verify'] = "Your passwords didn't match" # not needed, but if there is an email let's check its format if email != '': if not validate(email, '^[\S]+@[\S]+.[\S]+$'): error['email'] = "That's not a valid email" # if everything went right, let's introduce our new friend if not error: pw_hash = make_pw_hash(name, password) user = User(name=name, password=pw_hash, email=email) user.put() # now we logged the user in self.login(user) self.redirect('/') # if something went wrong, let's render again showing the error self.render('sign-up.html', name=name, email=email, error=error)
def registration_action(): page_title = 'Регистрация' error = None # Проверяем данные if not request.form['email']: error = 'Требуется ввести Email' if not request.form['password']: error = 'Требуется ввести пароль' if not request.form['password2']: error = 'Требуется ввести повтор пароля' if request.form['password'] != request.form['password2']: error = 'Пароли не совпадают' if Storage.is_user_registred(request.form['email']): error = 'Пользователь с таким email уже зарегистрирован' pattern_password = re.compile(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!#%*?&]{8,20}$') if not pattern_password.match(request.form['password']): error = 'Пароль должен быть от 8-ми до 20 символов, содержать хотя бы одно число, ' \ 'хотя бы одну латинскую букву в нижнем и верхнем регистре, хотя бы один спец символ' # В случае ошибки рендерим тот же шаблон, но с текстом ошибки if error: return render_template('pages/registration.html', page_title=page_title, error=error) # Добавляем пользователя Storage.add_user(User(None, request.form['email'], request.form['password'])) # Перенаправляем на главную return redirect(url_for('home'))
def fb_login(): if request.method != "POST": return "Error", 404 user = User.get_by_id(request.form["userID"]) response = {} response["status"] = "existing" if not user: user = User(id=request.form["userID"], userID=request.form["userID"], name=request.form["first_name"] + " " + request.form["last_name"], email=request.form["email"], rating=2.5, number_ratings=1) user.put() response["status"] = "new" if Admin.get_by_id(user.key.id()): session["admin"] = True else: session["admin"] = False session['first_name'] = request.form["first_name"] session['last_name'] = request.form["last_name"] session['email'] = request.form["email"] logged_in(user) return json.dumps(response)
def test_create_user(self): print '__________create user test_________' u = User(name='testbli', password_sha='testbli', email='*****@*****.**', activationCode='111') u.create()
def post(self): self.response.headers['Content-Type'] = 'text/plain; charset=utf-8' user = User() try: jsonUser = json.loads(self.request.body) user.parse(jsonUser) if user.isValid(): if user.isUnique(): user.created = datetime.today() user.save() # Save user in db! self.response.write('You are created!\n') else: self.response.write('We know you already.\n') # Trying to add notification ids. loaded_user = user.loadme() loaded_user_changed = False for reg_id in user.registration_ids: if reg_id not in loaded_user.registration_ids: loaded_user.registration_ids.append(reg_id) loaded_user_changed = True if loaded_user_changed: loaded_user.save() self.response.write('We updated your person.\n') self.response.write('Success!\n') else: self.response.write('Failed!\n') self.response.write('User not valid.\n') self.response.write(user.hash) self.response.write(user.type) except Exception, e: self.response.write('Failed!\n') self.response.write(e)
def find_and_enrich_following_for_user(username): friend_value = "#FRIEND#{}".format(username) resp = dynamodb.query( TableName="quick-photos", IndexName="InvertedIndex", KeyConditionExpression="SK = :sk", ExpressionAttributeValues={":sk": { "S": friend_value }}, ScanIndexForward=True, ) keys = [{ "PK": { "S": "USER#{}".format(item["followedUser"]["S"]) }, "SK": { "S": "#METADATA#{}".format(item["followedUser"]["S"]) }, } for item in resp["Items"]] friends = dynamodb.batch_get_item( RequestItems={"quick-photos": { "Keys": keys }}) enriched_friends = [ User(item) for item in friends["Responses"]["quick-photos"] ] return enriched_friends
def test_read_user(self): print '__________read user test_________' u = User(name='ujlikes') u = u.findByName() print u print u.salt print u.password_sha
def create(self) -> User: return User( username=slugify(self.fake.name()), email=self.fake.email(), password=self.fake.password(), first_name=self.fake.first_name(), last_name=self.fake.last_name(), phone=self.fake.last_name() )
def get_user_by_id(id: int): """Найти пользователя по id :param id: идентификатор пользователя :type id: int :return: пользователь :rtype: User""" user_data = db.execute('SELECT * FROM users WHERE id=?', (id,)).fetchone() if user_data: return User(id=user_data[0], email=user_data[1], password=user_data[2]) else: return None
def get_active_user(): """ Inspects the session data to look up the currently logged in user. Returns a User instance if someone is logged in, or None otherwise. """ try: user_dict = load_from_session(SessionKeys.CURRENT_USER) user = User(**user_dict) return user except KeyError: return None
def create_user(self, user: UserCreate) -> User: user_data = asdict(user) user_data.pop('password') return User( **user_data, id=random.randint(1, 100), transactions=[ Transaction(id=1, amount=Decimal(1000)), Transaction(id=2, amount=Decimal(2000)), Transaction(id=3, amount=Decimal(3000)), ], )
def test_entity_manipulation(self): switchToTestDatabase() #creating a user u=User(login='******',password='******') print User.create(u) , '\n' self.assertTrue(u.findByLogin()!= None) #finding & updating a user u=User(login='******') u=u.findByLogin() print 'user before update: ', u print 'changing password to strong' u.password='******' u.update() u=u.findByLogin() print u self.assertEqual(u.password,'strong') print 'changing password to VERYstrong' u.password='******' u.update() u=u.findByLogin() print u self.assertEqual(u.password,'VERYstrong') #try to update a non existing user raised=False try : u=User(login='******',password='******') u.update() except Exception : print 'catch an Illegal Attempt' print '\ntrying to update jose, but he don\'t exist' raised=True self.assertTrue(raised) self.assertEqual(u.findByLogin(),None) deleteTestDatabase()
def get_user_by_email_and_password(email: str, passwordHash: str): """Найти пользователя по email и паролю :param email: электронная почта :type email: str :param passwordHash: хэш пароля :type passwordHash: str :return: пользователь :rtype: User """ user_data = db.execute('SELECT * FROM users WHERE email=?', (email,)).fetchone() if user_data and check_password_hash(user_data[2], passwordHash): return User(id=user_data[0], email=user_data[1], password=user_data[2]) else: return None
def get_user_by_email(email: str) -> User: """Найти пользователя по email :param email: имейл пользователя :type email: str :return: пользователь :rtype: User""" user_data = db.execute('SELECT * FROM users WHERE email=?', (email, )).fetchone() if user_data: return User(id=user_data[0], email=user_data[1], password=user_data[2]) else: return None
def test_give_me_the_money_should_return_available_funds_from_all_accounts( self): # account_1 = Mock() # type(account_1).balance = PropertyMock(return_value=50) # account_2 = Mock() # type(account_2).balance = PropertyMock(return_value=100) account_1 = Mock() account_1.get_balance.return_value = 50 account_2 = Mock() account_2.get_balance.return_value = 100 user = User("Janusz", 40, [account_1, account_2]) self.assertEqual(user.give_me_the_money(), 150)
def addUser(request): # syncWithDB() global users if 'name' in request.args: name = str(request.args['name']) else: return "Error: No name field provided. Please specify an name." if request.method == 'GET': """return the information for some user""" user = User(name) users.append(user) user.saveToDB() return "User created"
def signup(): return login() fields = [] fields.append( Field(name="email", title="Email", the_type='email', identifier='email', placeholder="Email")) fields.append( Field(name="name", title="Name", the_type='name', identifier='name', placeholder="Name")) fields.append( Field(name='password', title="Password", the_type='password', identifier='password', placeholder='Password')) title = "Signup" form = Form(fields=fields, title=title) if request.method == 'GET': return render_template('signup.html', signup_form=form) try: exists = User.get_by_id(request.form['email']) if exists: form.error = "Email Taken" return render_template('signup.html', signup_form=form) else: user = User(email=request.form['email'], id=request.form['email'], password=request.form['password'], name=request.form['name']) user.put() return signed_up(user) except KeyError as err: form.error = "Email or Password Was Not Filled Out Correctly" return render_template('signup.html', signup_form=form)
def parse(data): if 'message' in data or 'callback_query' in data: msg = data.get('message') or data.get('callback_query') name = msg['from']['first_name'] if 'last_name' in msg['from']: name += f" {msg['from']['last_name']}" user = User(id=msg['from']['id'], name=name, messenger='telegram', nick=msg['from'].get('username'), lang=msg['from'].get('language_code')) return Message(sender=user, text=msg.get('text', ''), cmd=Telegram.parse_cmd(msg), attachments=[]) else: return None
def post(self): eid = self.request.get('id', default_value='') self.response.write('<h1>'+eid+'</h1>') key = self.request.get('key', default_value='') if eid is not None and eid != '': msg = Message.get_by_id(int(eid)) elif key is not None and key != '': msg = ndb.Key(urlsafe=key).get() else: self.err('Neither id or key is passed!\n') return if msg is None: self.err('Loading message failed!\n') return # Send to phone notification! usr = User() usr.hash = msg.recipient usr = usr.loadme() if usr is None: self.err('User-Recipient not found!'); return data = {'type': 'message', 'sender': msg.sender} notfication = GCM('AIzaSyD-z2JuoBkD51RyRHG6ULoWX2gE84apP7M') response = notfication.json_request(registration_ids=usr.registration_ids, data=data, collapse_key=None, delay_while_idle=False, time_to_live=None, retries=5) self.response.headers['Content-Type'] = 'application/json; charset=utf-8' self.debug(response) # Mark message as pushed. msg.pushed = datetime.now() msg.put()
def defineUser( self, name, first, last, email, organization, identity_id=None, description=None, displayname=None, sshpubstring=None, url=None, docurl=None, ): ''' Defines a new User object for usage elsewhere in the API. :param str name: The unique VC3 username of this user :param str first: User's first name :param str last: User's last name :param str email: User's email address :param str organization: User's institutional affiliation or employer :return: User A valid User object :rtype: User ''' u = User(name=name, state='new', first=first, last=last, email=email, organization=organization, identity_id=identity_id, description=description, displayname=displayname, sshpubstring=sshpubstring, url=url, docurl=docurl) u.storenew = True self.log.debug("Creating user object: %s " % u) return u
def fetch_user_and_photos(username): resp = dynamodb.query( TableName='quick-photos', KeyConditionExpression="PK = :pk AND SK BETWEEN :metadata AND :photos", ExpressionAttributeValues={ ":pk": { "S": "USER#{}".format(username) }, ":metadata": { "S": "#METADATA#{}".format(username) }, ":photos": { "S": "PHOTO$" }, }, ScanIndexForward=True) user = User(resp['Items'][0]) user.photos = [Photo(item) for item in resp['Items'][1:]] return user
def registration_action(): page_title = 'Регистрация | Auth Example' error = None # Проверяем данные if not request.form['email']: error = 'Требуется ввести Email' elif not request.form['password']: error = 'Требуется ввести пароль' elif not request.form['password2']: error = 'Требуется ввести повтор пароля' elif request.form['password'] != request.form['password2']: error = 'Пароли не совпадают' elif not re.search(r'[A-Z]{1}', request.form['password']): error = 'В пароле нет заглавной латинской буквы' elif not re.search(r'[a-z]{1}', request.form['password']): error = 'В пароле нет прописной латинской буквы' elif not re.search(r'[0-9]{1}', request.form['password']): error = 'В пароле нет цифры' elif not re.search(r'[@!/+-=%*]{1}', request.form['password']): error = 'В пароле нет спецсимвола' elif not re.search(r'[0-9a-zA-Z@!/+-=%*]{8,}', request.form['password']): error = 'В пароле меньше восьми символов' elif Storage.get_user_by_email(request.form['email']): error = 'Пользователь с таким email уже зарегестрирован' # В случае ошибки рендерим тот же шаблон, но с текстом ошибки if error: return render_template('pages/registration.html', page_title=page_title, error=error) # Добавляем пользователя Storage.add_user( User(None, request.form['email'], request.form['password'])) # Делаем вид, что добавление всегда без ошибки # Перенаправляем на главную return redirect(url_for('home'))
def post(self): username = self.request.get('username') password = self.request.get('password') verify = self.request.get('verify') email = self.request.get('email') c_username = self.check(username, "^[a-zA-Z0-9_-]{3,20}$") c_password = self.check(password, "^.{3,20}$") c_email = self.check(email,"^[\S]+@[\S]+\.[\S]+$") error = Error() user = getUser(username) if not user == None: error.name_error = "duplicate user name. please choose another." error.error = True if(password != verify): error.ver_error = "Password does not match" error.error = True if c_username == None: error.name_error = "Invalid Username" error.error = True if c_password == None: error.pwd_error = "Invalid Password" error.error = True if(email != "" and c_email == None): error.email_error = "Invalid email address" error.error = True if error.error: self.render_register(username, "", "", email,error) else : #save user in database user_class = USER if username == ADMINISTRATOR: user_class = ADMIN user = User(username=username, password=hash_pw(username,password), email=email, user_class=user_class) user.put() #set login cookie #redirect to index page self.redirect('/')
def parse(data): data_type = data['type'] if data_type == 'message_new': msg = data['object']['message'] client_info = data['object']['client_info'] name, nick = Vk._get_info(msg['from_id']) user = User(id=msg['from_id'], name=name, messenger='vk', nick=nick, lang=Vk._get_lang(client_info['lang_id'])) return Message( sender=user, text=msg['text'], cmd=Vk.parse_cmd(msg), attachments=[] # TODO attachments ) elif data_type == 'confirmation' and str( data.get('group_id')) == os.getenv('VK_GROUP'): abort(Response(os.getenv('VK_CONFIRMATION'))) else: return None
async def user_create(user: UserCreateRequest) -> User: try: user = create_user(**user.dict()) except IntegrityError: raise HTTPException(status_code=400) return User(**user.__data__)
city='Lethbridge', province='AB') # Commit the prescriber data db.session.add(prescriber1) db.session.add(prescriber2) db.session.add(prescriber3) db.session.add(prescriber4) db.session.add(prescriber5) db.session.commit() # Insert user data user1 = User( usename='Harbourfront', password_hash= 'pbkdf2:sha256:50000$YCxhKrbW$9b6b2c89619765d4836d31a2ee49e9303e1d92eb4ee800c21690a2bb0f757617', prescriber_id=7) user2 = User( usename='Mapleland', password_hash= 'pbkdf2:sha256:50000$Oc2sSeQH$96f5243d6b7d37ce6fa5214fe6c2bdce923bc059d71a0e2c7b1d2f7f0d44e307', dispenser_id=7) user3 = User( usename='Ambis', password_hash= 'pbkdf2:sha256:50000$GtB0Qett$abccbb4a849bdd93c7a07fdb1b2bfb2fdc966e7b6e2f35e67dc582f97e12fe2e', prescriber_id=7) user4 = User( usename='WestLincoln', password_hash=
def useradd(username, caller): if (caller.permission == 'common'): print("Falha. Você não tem permissão para isto") else: passwd = str(input("Escreva sua senha: \n")) user_db[username] = User(username, passwd, 'common')
def create(self, display_name): id = str(uuid.uuid4()) user = User(id, display_name) self.data_store[id] = user return user