def register_companies(self, count = 10, verified = True): companies = [] for a in xrange(count): user = User.create_user('*****@*****.**' % a, User.make_random_password()) if not user: raise Exception('failed to create test user') User.collection.update({'_id' : user._id}, {'$set' : {'activated' : True}}) employee = CompanyEmployee({'user_id' : user._id, 'first_name' : 'test_user_' + str(a)}) employee.save() company = Company({'rek_id' : integer_to_code(a + 10000), 'owner_employee_id' : employee._id, 'short_name' : 'tc_' + str(a), 'full_name' : 'OOO Test Company ' + str(a), 'brand_name' : 'Test Company Brand ' + str(a), 'description' : 'Test company ' + str(a), 'category_text' : 'Testing', 'staff_size' : (a + 1) * 3, 'inn' : int(str(a + 1) + '0' * (12 - len(str(a)))) + a + 1, 'kpp' : int(str(a + 1) + '1' * (9 - len(str(a)))) + a + 1, 'is_account_activated' : True, 'account_status' : CompanyAccountStatus.VERIFIED if verified else CompanyAccountStatus.JUST_REGISTERED }) company.save() employee.set(company_id = company._id) companies.append(company) return companies
def get_admin_user(self): # mustdo: rework when user roles are added user = None employee = CompanyEmployee.objects.get_one( {'_id': self.owner_employee_id}) if employee: user_data = User.find_one({'_id': employee.user_id}) if user_data: user = User(user_data) return user, employee
def setUp(self): self.db = MongoDBTestRunner.test_db self.collections = {} for name in self.collection_names: self.collections[name] = self.db[name] self.client = Client() User.set_indexes() Contractor.set_indexes() self.company = None self.employee = None
def post(self, request, link_id): try: link_oid = ObjectId(link_id) except Exception: raise Http404() link = PasswordRecoveryLink.objects.get_one({'_id': link_oid}) if not link: raise Http404() new_password = request.POST.get('new_password', '').strip() new_password_repeat = request.POST.get('new_password_repeat', '').strip() pass_error = get_password_error(new_password) if pass_error: return render_to_response('set_new_password.html', { 'error': True, 'msg': pass_error }, context_instance=RequestContext(request)) if new_password != new_password_repeat: return render_to_response('set_new_password.html', { 'error': True, 'msg': u'Введеные пароли не совпадают' }, context_instance=RequestContext(request)) user_dict = User.collection.find_one({'_id': link.user}) if not user_dict: return render_to_response('set_new_password.html', { 'error': True, 'msg': u'Не удалось изменить пароль' }, context_instance=RequestContext(request)) user = User(user_dict) PasswordRecoveryLink.objects.collection.remove({'_id': link_oid}) # todo: validate password user.set_password(new_password) user.backend = "rek.mango.auth.Backend" login(request, user) return render_to_response('set_new_password.html', { 'password_set': True, 'SITE_DOMAIN_NAME': settings.SITE_DOMAIN_NAME }, context_instance=RequestContext(request))
def register_companies(self, count=10, verified=True): companies = [] for a in xrange(count): user = User.create_user('*****@*****.**' % a, User.make_random_password()) if not user: raise Exception('failed to create test user') User.collection.update({'_id': user._id}, {'$set': { 'activated': True }}) employee = CompanyEmployee({ 'user_id': user._id, 'first_name': 'test_user_' + str(a) }) employee.save() company = Company({ 'rek_id': integer_to_code(a + 10000), 'owner_employee_id': employee._id, 'short_name': 'tc_' + str(a), 'full_name': 'OOO Test Company ' + str(a), 'brand_name': 'Test Company Brand ' + str(a), 'description': 'Test company ' + str(a), 'category_text': 'Testing', 'staff_size': (a + 1) * 3, 'inn': int(str(a + 1) + '0' * (12 - len(str(a)))) + a + 1, 'kpp': int(str(a + 1) + '1' * (9 - len(str(a)))) + a + 1, 'is_account_activated': True, 'account_status': CompanyAccountStatus.VERIFIED if verified else CompanyAccountStatus.JUST_REGISTERED }) company.save() employee.set(company_id=company._id) companies.append(company) return companies
def get(self, request, link_id): try: link = UserActivationLinks.objects.get_one({'_id' : bson.ObjectId(link_id)}) if not link: raise Exception() except Exception: raise Http404() user_id = link.user User.collection.update({'_id' : user_id}, {'$set' : {'activated' : True}}) employee = CompanyEmployee.objects.get_one_partial({'user_id' : user_id}, {'company_id' : 1}) if employee and employee.company_id: Company.objects.update({'_id' : employee.company_id}, {'$set' : {'is_account_activated' : True}}) UserActivationLinks.objects.collection.remove({'_id' : link._id}) user = User.get({'_id' : user_id}) user.backend = "rek.mango.auth.Backend" if user: login(request, user) return render_to_response('base.html', {'page_status': 'account_activated'}, context_instance=RequestContext(request))
def get(self, request, link_id): try: link = UserActivationLinks.objects.get_one( {'_id': bson.ObjectId(link_id)}) if not link: raise Exception() except Exception: raise Http404() user_id = link.user User.collection.update({'_id': user_id}, {'$set': {'activated': True}}) employee = CompanyEmployee.objects.get_one_partial( {'user_id': user_id}, {'company_id': 1}) if employee and employee.company_id: Company.objects.update({'_id': employee.company_id}, {'$set': { 'is_account_activated': True }}) UserActivationLinks.objects.collection.remove({'_id': link._id}) user = User.get({'_id': user_id}) user.backend = "rek.mango.auth.Backend" if user: login(request, user) return render_to_response('base.html', {'page_status': 'account_activated'}, context_instance=RequestContext(request))
def handle(self, *args, **options): email = options.get('email', None) password = options.get('password', None) interactive = options.get('interactive') verbosity = int(options.get('verbosity', 1)) # Do quick and dirty validation if --noinput if not interactive: if not password or not email: raise CommandError("You must use --password and --email with --noinput.") try: is_valid_email(email) except exceptions.ValidationError: raise CommandError("Invalid email address.") password = password.strip() if not len(password) < 6: raise CommandError("Password length must be > 5.") # Prompt for username/email/password. Enclose this whole thing in a # try/except to trap for a keyboard interrupt and exit gracefully. if interactive: try: # Get an email while 1: if not email: email = raw_input('E-mail address: ') email = email.strip().lower() try: is_valid_email(email) except exceptions.ValidationError: sys.stderr.write("Error: That e-mail address is invalid.\n") email = None else: break # Get a password while 1: if not password: password = getpass.getpass() password2 = getpass.getpass('Password (again): ') if password != password2: sys.stderr.write("Error: Your passwords didn't match.\n") password = None continue if len(password.strip()) < 6: sys.stderr.write("Password length must be > 5.\n") password = None continue break except KeyboardInterrupt: sys.stderr.write("\nOperation cancelled.\n") sys.exit(1) email = email.strip().lower() try: user = User.create_user(email, password) User.collection.update({'_id' : user._id}, {'$set' : {'is_superuser' : True}}) except Exception, ex: sys.stderr.write("\nFailed to create user.\n%s\n" % unicode(ex))
def get_authorized_parameters(csrf_key, session_key, request): company = None django_request = DjangoFakeRequest(request, csrf_key) if csrf_checker.process_view(django_request, {}, None, None): return None, None, None user_data = get_authenticated_user(session_key) user = User(user_data) if user_data and user and not user.is_anonymous(): employee = CompanyEmployee.objects.get_one({'user_id' : user._id}) if employee: company = Company.objects.get_one(employee.company_id) else: return None, None, None return user, company, employee
def get_authorized_parameters(csrf_key, session_key, request): company = None django_request = DjangoFakeRequest(request, csrf_key) if csrf_checker.process_view(django_request, {}, None, None): return None, None, None user_data = get_authenticated_user(session_key) user = User(user_data) if user_data and user and not user.is_anonymous(): employee = CompanyEmployee.objects.get_one({'user_id': user._id}) if employee: company = Company.objects.get_one(employee.company_id) else: return None, None, None return user, company, employee
def clean_email(self): email = self.cleaned_data['email'].lower() if not validateEmail(email): setattr(self, 'email_error_str', u"Некорректный email") raise forms.ValidationError(u"Некорректный email") if User.find_one({'email' : email}): setattr(self, 'email_error_str', u"Пользователь с таким адресом электронной почты уже существует") raise forms.ValidationError(u"Пользователь с таким адресом электронной почты уже существует") return email
def get_admin_user(self): # mustdo: rework when user roles are added user = None employee = CompanyEmployee.objects.get_one({'_id' : self.owner_employee_id}) if employee: user_data = User.find_one({'_id' : employee.user_id}) if user_data: user = User(user_data) return user, employee
def get_company_admin_user(company): employee = CompanyEmployee.objects.get_one( {'_id': company.owner_employee_id}) if not employee: return None user_data = User.collection.find_one({'_id': employee.user_id}) if not user_data: return None return User(user_data)
def clean_email(self): email = self.cleaned_data['email'].lower() if not validateEmail(email): setattr(self, 'email_error_str', u"Некорректный email") raise forms.ValidationError(u"Некорректный email") if User.find_one({'email': email}): setattr( self, 'email_error_str', u"Пользователь с таким адресом электронной почты уже существует" ) raise forms.ValidationError( u"Пользователь с таким адресом электронной почты уже существует" ) return email
def post(self, request, link_id): try: link_oid = ObjectId(link_id) except Exception: raise Http404() link = PasswordRecoveryLink.objects.get_one({'_id' : link_oid}) if not link: raise Http404() new_password = request.POST.get('new_password', '').strip() new_password_repeat = request.POST.get('new_password_repeat', '').strip() pass_error = get_password_error(new_password) if pass_error: return render_to_response('set_new_password.html', {'error' : True, 'msg' : pass_error}, context_instance=RequestContext(request)) if new_password != new_password_repeat: return render_to_response('set_new_password.html', {'error' : True, 'msg' : u'Введеные пароли не совпадают'}, context_instance=RequestContext(request)) user_dict = User.collection.find_one({'_id' : link.user}) if not user_dict: return render_to_response('set_new_password.html', {'error' : True, 'msg' : u'Не удалось изменить пароль'}, context_instance=RequestContext(request)) user = User(user_dict) PasswordRecoveryLink.objects.collection.remove({'_id' : link_oid}) # todo: validate password user.set_password(new_password) user.backend = "rek.mango.auth.Backend" login(request, user) return render_to_response('set_new_password.html', {'password_set' : True, 'SITE_DOMAIN_NAME' : settings.SITE_DOMAIN_NAME}, context_instance=RequestContext(request))
def test_register_after_invite(self): SettingsManager.set_property('rnes', 3) self.register() self.login() data = {'msg': 'Come on! Join us now!', 'email': '*****@*****.**'} notifications = Notification.objects.get({}) self.assertEqual(len(notifications), 0) response = self.client.post('/invites/send/', data) self.assertEquals(response.status_code, 200) invites = Invite.objects.get({}) self.assertEqual(len(invites), 1) invite = invites[0] self.assertEqual(invite.message, 'Come on! Join us now!') self.assertEqual(invite.email, '*****@*****.**') data = simplejson.loads(response.content) self.assertTrue(isinstance(data, dict)) self.assertIn('success', data) self.assertTrue(data['success']) self.logout() response = self.client.get(u'/invites/join/%s/' % invite.cookie_code) self.assertEquals(response.status_code, 302) self.assertTrue(self.client.cookies.has_key('invite')) self.assertEqual(Company.objects.count(), 1) self.assertEqual(RecommendationRequest.objects.count(), 0) self.register(email="*****@*****.**", verified=False) self.login() self.assertEqual(Company.objects.count(), 2) invite = Invite.objects.get_one({}) self.assertEqual(RecommendationRequest.objects.count(), 1) self.assertEqual(invite.rec_request, RecommendationRequest.objects.get_one({})._id) user = User( User.collection.find_one({'email': "*****@*****.**"})) company = get_user_company(user) self.assertEqual(company.account_status, CompanyAccountStatus.JUST_REGISTERED)
def post(self, request): if 'email' not in request.POST: raise Http404() email = request.POST['email'].strip().lower() user = User.collection.find_one({'email': email}) if not user: return render_to_response('password_recovery.html', { 'user_not_found': True, 'email': email }, context_instance=RequestContext(request)) link = PasswordRecoveryLink({'user': user['_id']}) link.save() self.send_email(User(user), link._id) return render_to_response('password_recovery.html', { 'link_id': link._id, 'email': email }, context_instance=RequestContext(request))
def register_verification_requesters(self, target_company, count = 10, status = RecommendationStatusEnum.RECEIVED): requesters = [] for a in xrange(count): user = User.create_user('*****@*****.**' % a, 'aaa') User.collection.update({'_id' : user._id}, {'$set' : {'activated' : True}}) if not user: raise Exception('failed to create test user') employee = CompanyEmployee({'user_id' : user._id, 'first_name' : 'test_user_' + str(a)}) employee.save() company = Company({'rek_id' : integer_to_code(a + 10000), 'owner_employee_id' : employee._id, 'short_name' : 'tc_' + str(a), 'full_name' : 'OOO Test Company ' + str(a), 'brand_name' : 'Test Company Brand ' + str(a), 'description' : 'Test company ' + str(a), 'category_text' : 'Testing', 'staff_size' : (a + 1) * 3, 'inn' : int(str(a + 1) + '0' * (12 - len(str(a)))) + a + 1, 'kpp' : int(str(a + 1) + '1' * (9 - len(str(a)))) + a + 1, 'account_status' : CompanyAccountStatus.JUST_REGISTERED, 'is_account_activated' : True }) company.save() employee.set(company_id = company._id) request = RecommendationRequest({'requester' : company._id, 'recipient' : target_company._id, 'status' : status, 'message' : 'Please recommend me.', 'requester_email' : user.email}) request.save() requesters.append((company, employee, user, request)) return requesters
def register_companies(count=1, verified=False): companies = [] employees = [] users = [] for i in xrange(count): email = '*****@*****.**' % i rek_id = 'CCC%i' % i password = '******' brand_name = u'Порошки%i' % i created_user = User.create_user(email, password) if not created_user: raise Exception('failed to create user') new_employee = CompanyEmployee({'user_id':created_user._id, 'timezone' : 'Europe/Moscow'}) new_employee.save() new_company = Company({'rek_id':rek_id, 'owner_employee_id':new_employee._id, 'brand_name' : brand_name, 'is_account_activated' : True, 'date_creation' : timezone.now() + timedelta(days=i)}) if verified: new_company.account_status = 'verified' new_company.save() new_employee.set(company_id=new_company._id) users.append(created_user) employees.append(new_employee) companies.append(new_company) User.collection.update({}, {'$set' : {'activated' : True, 'is_active' : True}}, multi=True) return companies, employees, users
def handle(self, *args, **options): email = options.get('email', None) password = options.get('password', None) interactive = options.get('interactive') verbosity = int(options.get('verbosity', 1)) # Do quick and dirty validation if --noinput if not interactive: if not password or not email: raise CommandError( "You must use --password and --email with --noinput.") try: is_valid_email(email) except exceptions.ValidationError: raise CommandError("Invalid email address.") password = password.strip() if not len(password) < 6: raise CommandError("Password length must be > 5.") # Prompt for username/email/password. Enclose this whole thing in a # try/except to trap for a keyboard interrupt and exit gracefully. if interactive: try: # Get an email while 1: if not email: email = raw_input('E-mail address: ') email = email.strip().lower() try: is_valid_email(email) except exceptions.ValidationError: sys.stderr.write( "Error: That e-mail address is invalid.\n") email = None else: break # Get a password while 1: if not password: password = getpass.getpass() password2 = getpass.getpass('Password (again): ') if password != password2: sys.stderr.write( "Error: Your passwords didn't match.\n") password = None continue if len(password.strip()) < 6: sys.stderr.write("Password length must be > 5.\n") password = None continue break except KeyboardInterrupt: sys.stderr.write("\nOperation cancelled.\n") sys.exit(1) email = email.strip().lower() try: user = User.create_user(email, password) User.collection.update({'_id': user._id}, {'$set': { 'is_superuser': True }}) except Exception, ex: sys.stderr.write("\nFailed to create user.\n%s\n" % unicode(ex))
def create_staff_user(email): password = User.make_random_password() created_user = User.create_user(email, password) created_user.save() return created_user, password
def create_new_account(email, password, brand_name, promo_code=None, invite_cookie=None): # mustdo: add "transaction" created_user = User.create_user(email, password) if not created_user: raise Exception('failed to create user') activation_link = UserActivationLinks({'user': created_user._id}) activation_link.save() new_employee = CompanyEmployee({ 'user_id': created_user._id, 'timezone': 'Europe/Moscow' }) new_employee.save() new_company = Company({ 'rek_id': generate_rek_id(), 'owner_employee_id': new_employee._id, 'brand_name': brand_name }) new_company.save() new_billing_account = Account({ 'type': Account.TYPE_COMPANY, 'name': "Счет компании", 'details': { 'subject_id': new_company._id } }) new_billing_account.save() if promo_code: promo_code.use(new_company._id) promo_account = Account.objects.get_one( {'system_id': Account.FIXED_PROMO_ACCOUNT_ID}) transaction = Transaction({ 'source': promo_account._id, 'dest': new_billing_account._id, 'amount': Currency.russian_roubles( SettingsManager.get_property( "registration_promo_action_amount")), 'comment': u"Бонус при регистрации компании по промо-коду %s" % unicode(promo_code.code) }) transaction.save() transaction.apply() new_employee.set(company_id=new_company._id) if invite_cookie and len(invite_cookie): invite = Invite.objects.get_one({'cookie_code': invite_cookie}) if invite: rec_request = RecommendationRequest({ 'requester': new_company._id, 'recipient': invite.sender, 'status': RecommendationStatusEnum.ACCEPTED, 'message': u'Регистрация по приглашению: %s' % invite.message, 'viewed': True, 'requester_email': '*****@*****.**' }) rec_request.save() invite.rec_request = rec_request._id invite.save() if SettingsManager.get_property('rnes') < 2: new_company.objects.update({'_id': new_company._id}, { '$set': { 'account_status': CompanyAccountStatus.VERIFIED } }) new_company.account_status = CompanyAccountStatus.VERIFIED dest_account = Account.objects.get_one({ 'type': Account.TYPE_COMPANY, 'details.subject_id': invite.sender }) if dest_account: promo_account = Account.objects.get_one( {'system_id': Account.FIXED_PROMO_ACCOUNT_ID}) if promo_account: new_trans = Transaction({ 'source': promo_account._id, 'dest': dest_account._id, 'amount': Currency.russian_roubles( SettingsManager.get_property('invite_bonus')), 'comment': u'Бонус за приглашение компании "%s" (%s)' % (brand_name, new_company.rek_id) }) new_trans.save() new_trans.apply() return created_user, password, new_company, activation_link
def clean_email(self): email = self.cleaned_data['email'] if not User.find_one(email=email): raise forms.ValidationError("Такого адреса не существует") return email
def test_register_after_invite_and_verify(self): account = Account({ "system_id": Account.FIXED_PROMO_ACCOUNT_ID, "name": "Счет промо-акцийг", "type": Account.TYPE_VIRTUAL }) account.save() SettingsManager.set_property('rnes', 1) self.register() self.login() data = {'msg': 'Come on! Join us now!', 'email': '*****@*****.**'} notifications = Notification.objects.get({}) self.assertEqual(len(notifications), 0) response = self.client.post('/invites/send/', data) self.assertEquals(response.status_code, 200) invites = Invite.objects.get({}) self.assertEqual(len(invites), 1) invite = invites[0] self.assertEqual(invite.message, 'Come on! Join us now!') self.assertEqual(invite.email, '*****@*****.**') data = simplejson.loads(response.content) self.assertTrue(isinstance(data, dict)) self.assertIn('success', data) self.assertTrue(data['success']) self.logout() response = self.client.get(u'/invites/join/%s/' % invite.cookie_code) self.assertEquals(response.status_code, 302) self.assertTrue(self.client.cookies.has_key('invite')) self.assertEqual(Company.objects.count(), 1) self.assertEqual(RecommendationRequest.objects.count(), 0) self.register(email="*****@*****.**", verified=False) self.login() self.assertEqual(Company.objects.count(), 2) invite = Invite.objects.get_one({}) self.assertEqual(RecommendationRequest.objects.count(), 1) self.assertEqual(invite.rec_request, RecommendationRequest.objects.get_one({})._id) user = User( User.collection.find_one({'email': "*****@*****.**"})) company = get_user_company(user) self.assertEqual(company.account_status, CompanyAccountStatus.VERIFIED) trans = Transaction.objects.get_one({}) self.assertIsNotNone(trans) self.assertEqual(trans.state, Transaction.STATE_DONE) self.assertEqual(trans.amount.amount, SettingsManager.get_property('invite_bonus')) self.assertEqual(trans.source_account, account._id) dest_account = Account.objects.get_one({ 'type': Account.TYPE_COMPANY, 'details.subject_id': invite.sender }) self.assertEqual(trans.dest_account, dest_account._id)
def create_new_account(email, password, brand_name, promo_code = None, invite_cookie = None): # mustdo: add "transaction" created_user = User.create_user(email, password) if not created_user: raise Exception('failed to create user') activation_link = UserActivationLinks({'user' : created_user._id}) activation_link.save() new_employee = CompanyEmployee({'user_id':created_user._id, 'timezone' : 'Europe/Moscow'}) new_employee.save() new_company = Company({'rek_id':generate_rek_id(), 'owner_employee_id':new_employee._id, 'brand_name' : brand_name}) new_company.save() new_billing_account = Account({'type' : Account.TYPE_COMPANY, 'name' : "Счет компании", 'details' : {'subject_id' : new_company._id}}) new_billing_account.save() if promo_code: promo_code.use(new_company._id) promo_account = Account.objects.get_one({'system_id' : Account.FIXED_PROMO_ACCOUNT_ID}) transaction = Transaction({'source' : promo_account._id, 'dest' : new_billing_account._id, 'amount' : Currency.russian_roubles(SettingsManager.get_property("registration_promo_action_amount")), 'comment' : u"Бонус при регистрации компании по промо-коду %s" % unicode(promo_code.code)}) transaction.save() transaction.apply() new_employee.set(company_id=new_company._id) if invite_cookie and len(invite_cookie): invite = Invite.objects.get_one({'cookie_code' : invite_cookie}) if invite: rec_request = RecommendationRequest({'requester' : new_company._id, 'recipient' : invite.sender, 'status' : RecommendationStatusEnum.ACCEPTED, 'message' : u'Регистрация по приглашению: %s' % invite.message, 'viewed' : True, 'requester_email' : '*****@*****.**'}) rec_request.save() invite.rec_request = rec_request._id invite.save() if SettingsManager.get_property('rnes') < 2: new_company.objects.update({'_id' : new_company._id}, {'$set' : {'account_status' : CompanyAccountStatus.VERIFIED}}) new_company.account_status = CompanyAccountStatus.VERIFIED dest_account = Account.objects.get_one({'type' : Account.TYPE_COMPANY, 'details.subject_id' : invite.sender}) if dest_account: promo_account = Account.objects.get_one({'system_id' : Account.FIXED_PROMO_ACCOUNT_ID}) if promo_account: new_trans = Transaction({'source' : promo_account._id, 'dest' : dest_account._id, 'amount' : Currency.russian_roubles(SettingsManager.get_property('invite_bonus')), 'comment' : u'Бонус за приглашение компании "%s" (%s)' % (brand_name, new_company.rek_id)}) new_trans.save() new_trans.apply() return created_user, password, new_company, activation_link