def setUp(self): # Initialize functional test framework self.app = webtest.TestApp(self.router) self.logout() if not os.path.exists(temporaryFolder): os.mkdir(temporaryFolder) # Reset users word = "Спасибо1".decode("utf-8") self.userS = {"username": word, "password": word, "nickname": word, "email": word + "@example.com"} self.userN = dict((key, value.replace("1", "2")) for key, value in self.userS.iteritems()) for userIndex, valueByKey in enumerate([self.userS, self.userN], 1): username, password, nickname, email = [ valueByKey.get(x) for x in "username", "password", "nickname", "email" ] db.merge( User( id=userIndex, username=username, password_=hash(password), nickname=nickname, email=email, is_super=userIndex % 2, ) ) transaction.commit()
def test_reset(self): 'Make sure that resetting the password works' url = self.get_url('user_reset') email = self.userN['email'] password_ = hash(self.userN['password']) # Trying to reset an email that does not exist returns an error self.assertJSON(self.post(url, dict(email=email + 'x')), 0) # Resetting the password does not immediately change the password self.assertJSON(self.post(url, dict(email=email)), 1) self.assertEqual(db.query(User).filter_by(email=email, password_=password_).count(), 1) # Apply change self.get(self.get_url('user_confirm', ticket=db.query(User_.ticket).filter_by(email=email).order_by(User_.when_expired.desc()).first()[0])) self.assertEqual(db.query(User).filter_by(email=email, password_=password_).count(), 0)
def initialize_sql(engine): 'Create tables and insert data' # Create tables db.configure(bind=engine) Base.metadata.bind = engine Base.metadata.create_all(engine) # If the tables are empty, if not db.query(User).count(): # Prepare data userPacks = [ (u'admin', make_random_string(PASSWORD_LEN_MAX), u'Admin', u'*****@*****.**', True), (u'user', make_random_string(PASSWORD_LEN_MAX), u'User', u'*****@*****.**', False), ] # Insert data userTemplate = '\nUsername\t%s\nPassword\t%s\nNickname\t%s\nEmail\t\t%s' for username, password, nickname, email, is_super in userPacks: print userTemplate % (username, password, nickname, email) db.add(User(username=username, password_=hash(password), nickname=nickname, email=email, is_super=is_super)) print transaction.commit()
def test_registration(self): 'Make sure that registration works' url = self.get_url('user_register') username, password, nickname, email = [self.userN[x].replace('2', '3') for x in 'username', 'password', 'nickname', 'email'] params = ReplaceableDict(username=username, password=password, nickname=nickname, email=email) # Make sure the registration page appears properly self.assert_('Registration' in self.get(url).unicode_body) # Register self.post(url, params) # Register with the same username but with different case self.post(url, params.replace(username=username.upper(), nickname=nickname + 'x', email=email + 'x')) # Register with the same nickname but with different case self.post(url, params.replace(username=username + 'x', nickname=nickname.upper(), email=email + 'x')) # Register with the same email but with different case self.post(url, params.replace(username=username + 'x', nickname=nickname + 'x', email=email.upper())) # Confirm registration self.get(self.get_url('user_confirm', ticket=db.query(User_.ticket).filter_by(email=email).order_by(User_.when_expired.desc()).first()[0])) # Make sure the user exists self.assertEqual(db.query(User).filter_by(email=email).count(), 1) # Make sure that conflicting registrations have been deleted self.assertEqual(db.query(User_).filter_by(password_=hash(password)).count(), 0)
def login_(request): 'Process login credentials' # Make shortcuts environ, params, registry = [getattr(request, x) for x in 'environ', 'params', 'registry'] username, password = [params.get(x, '').strip() for x in 'username', 'password'] if not username or not password: return dict(isOk=0) # Check username user = db.query(User).filter_by(username=username).first() if not user: return dict(isOk=0) # If the password is incorrect, increment and return rejection_count if user.password_ != hash(password): user.rejection_count += 1 return dict(isOk=0, rejection_count=user.rejection_count) # If there have been too many rejections, expect recaptcha if user.rejection_count >= REJECTION_LIMIT: rChallenge, rResponse = [params.get(x, '') for x in 'recaptcha_challenge', 'recaptcha_response'] rPrivate = registry.settings.get('recaptcha.private', '') clientIP = environ.get('HTTP_X_REAL_IP', environ.get('HTTP_X_FORWARDED_FOR', environ.get('REMOTE_ADDR'))) # If the response is not valid, say so if not captcha.submit(rChallenge, rResponse, rPrivate, clientIP).is_valid: return dict(isOk=0, rejection_count=user.rejection_count) # Save user try: user.offset = int(params.get('offset', MINUTES_OFFSET)) except ValueError: user.offset = MINUTES_OFFSET user.when_login = datetime.datetime.utcnow() user.rejection_count = 0 # Set headers to set cookie if not hasattr(request, 'response_headerlist'): request.response_headerlist = [] request.response_headerlist.extend(remember(request, user.id, tokens=format_tokens(user))) # Return return dict(isOk=1)
def test_update(self): 'Make sure that updating credentials works' url = self.get_url('user_update') # Check that we only see the login page if the user is not logged in self.assert_('value=Login' in self.get(url).unicode_body) self.assert_('value=Login' in self.post(url).unicode_body) # Check that the update form is filled with the user's credentials self.login(self.userN) body = self.get(url).unicode_body self.assert_(self.userN['username'] in body) self.assert_(self.userN['nickname'] in body) self.assert_(self.userN['email'].lower() in body) token = get_token(body) # Updating credentials requires a token username, password, nickname, email = ['0' + self.userN[x] for x in 'username', 'password', 'nickname', 'email'] password_ = hash(password) params = ReplaceableDict(token=token, username=username, password=password, nickname=nickname, email=email) self.assertJSON(self.post(url, params.replace(token='')), 0) self.assertJSON(self.post(url, params), 1) # Make sure the credentials have not changed yet self.assertEqual(db.query(User).filter_by(username=username, password_=password_, nickname=nickname, email=email).count(), 0) # Make sure the credentials have changed after confirmation self.get(self.get_url('user_confirm', ticket=db.query(User_.ticket).filter_by(email=email).order_by(User_.when_expired.desc()).first()[0])) self.assertEqual(db.query(User).filter_by(username=username, password_=password_, nickname=nickname, email=email).count(), 1)
'Validate values and send confirmation email if values are okay' # Validate form try: form = UserForm().to_python(valueByName, user) except Invalid, error: return dict(isOk=0, errorByID=error.unpack_errors()) # Prepare ticket try: ticket = make_random_unique_string(TICKET_LEN, lambda x: db.query(User_).filter_by(ticket=x).first() == None) except RuntimeError: return dict(isOk=0, errorByID={'status': 'Could not generate ticket; please try again later'}) # Prepare user_ user_ = User_( username=form['username'], password_=hash(form['password']), nickname=form['nickname'], email=form['email'], user_id=user.id if user else None, ticket=ticket, when_expired=datetime.datetime.utcnow() + datetime.timedelta(hours=TICKET_HOURS)) db.add(user_) # Send message get_mailer(request).send_to_queue(Message( recipients=[formataddr((user_.nickname, user_.email))], subject='Confirm {}'.format(action), body=render('users/confirm.mak', { 'form': form, 'ticket': ticket, 'action': action, 'TICKET_HOURS': TICKET_HOURS,