def test_search_user_by_email(user_factory, db, test_client): expected_data = { 'id': 1, 'username': '******', 'first_name': 'Peter', 'surname': 'Parker', 'emails': [ { 'id': 1, 'email': 'email_1', } ] } user = user_factory(username='******', first_name='Peter', surname='Parker') _email = Email(email='email_1', user=user) db.session.add(user) db.session.commit() response = test_client.get(f'/user/search', query_string={'email': 'email_1'}) assert response.status_code == 200 data = response.json data.pop('created_at') assert data == expected_data
def get_user_profile(user): ''' Returns user profile. Creates one if needed ''' if not (user and user.is_authenticated()): return None pr = cache.get('users_profile:auth_user=%s' % user.id, None) if pr: return pr pr = get_profile_by_email_or_phone(user.username) if not pr: pr = Profile.objects.filter(user=user).order_by('id')[:2] if len(pr) > 1: fb_log.info('Multiple profiles for user: %s' % user.username) if pr: pr = pr[0] if not pr: pr = Profile(user=user) pr.created_on = datetime.now() pr.save() if is_valid_email(user.username): try: email = Email(email=user.username, user=pr, type='primary') email.save() except: pass if is_valid_mobile(user.username): try: phone = Phone(phone - user.username, user=pr, type='primary') phone.save() except: pass cache.set('users_profile:auth_user=%s' % user.id, pr) return pr
def test_delete_user(user_factory, db, test_client): user = user_factory(username='******', first_name='Peter', surname='Parker') _email = Email(email='email_1', user=user) db.session.add(user) db.session.commit() response = test_client.delete(f'/user/{user.id}') assert response.status_code == 204 assert len(User.query.all()) == 0
def test_update_user_update_username(user_factory, db, test_client): user = user_factory(username='******', first_name='Peter', surname='Parker') _email = Email(email='email_1', user=user) db.session.add(user) db.session.commit() data = {'username': '******'} response = test_client.put(f'/user/{user.id}', json=data) assert response.status_code == 200 user = User.query.all()[0] assert user.username == 'Superhero'
def test_update_user_add_emails(user_factory, db, test_client): user = user_factory(username='******', first_name='Peter', surname='Parker') _email = Email(email='email_1', user=user) db.session.add(user) db.session.commit() data = {'emails': [{'email': 'email_2'}, {'email': 'email_1'}]} response = test_client.put(f'/user/{user.id}', json=data) assert response.status_code == 200 user = User.query.all()[0] assert len(user.emails) == 2
def test_update_user(user_factory, db, test_client): first_name = 'Miles' surname = 'Morales' user = user_factory(username='******', first_name='Peter', surname='Parker') _email = Email(email='email_1', user=user) db.session.add(user) db.session.commit() data = {'first_name': first_name, 'surname': surname} response = test_client.put(f'/user/{user.id}', json=data) assert response.status_code == 200 assert response.json['first_name'] == first_name assert response.json['surname'] == surname user = User.query.all()[0] assert user.first_name == first_name assert user.surname == surname
usr.set_password(password) if first_name: usr.first_name = first_name if last_name: usr.last_name = last_name usr.save() try: profile = Profile.objects.get(user=usr) except Profile.DoesNotExist: profile = Profile(user=usr, created_on=datetime.now()) profile.full_name = '%s %s' % (first_name, last_name) if first_name and last_name: profile.full_name = '%s %s' % (first_name, last_name) profile.save() email = Email(user=profile, email=username, type='primary', cleaned_email=clean_username) email.save() except Exception, e: log.exception('Error get_or_create_user %s' % repr(e)) return None, None log.info('get_or_create_user is_type is %s' % is_type) return usr, profile def formatMoney(value): try: str_value = str(value).split('.')[0] dec = '' if len(str(value).split('.')) > 1: dec += '.' + str(value).split('.')[1][:2]
def migrate(): # Migration plan # Read user, user address book from atg # Create one user in tinla per atg user #ezone_orders_users = FtbOrder.objects.select_related('order').all().values( # 'order__profile').distinct() #atg_users = DpsUser.objects.filter(dps_id__in = ezone_orders_users) atg_users = DpsUser.objects.all() count = atg_users.count() log.info('Found %s users in atg.' % count) index = 0 exists = 0 non_existing = 0 newly_created = 0 migrated = 0 errors = 0 attached = 0 not_attached = 0 atg_users = queryset_iterator(atg_users) for atg_user in atg_users: index += 1 db.reset_queries() # Check if username is already taken in tinla # Tinla's usernames are phone numbers and email addresses email = None phone = None profile = None auth_user = None found = False username = atg_user.login try: email = Email.objects.select_related( 'user', 'user__user').get(email=username) profile = email.user auth_user = profile.user found = True except Email.DoesNotExist: try: phone = Phone.objects.select_related( 'user', 'user__user').get(phone=username[:10]) profile = phone.user auth_user = profile.user found = True except Phone.DoesNotExist: pass if found: exists += 1 if profile.atg_login: migrated += 1 if profile.atg_login != username: log.info( 'Skipping user: %s. Check if it matches with: %s' % (username, profile.atg_login)) else: try: profile.atg_login = username profile.atg_password = atg_user.password profile.save() log.info( 'User exists. Just mapping atg_login and atg_password %s' % username) attached += 1 except: log.info('User exists. Duplicate atg_login %s' % username) not_attached += 1 else: non_existing += 1 log.info('%s not found in tinla' % username) # No email and phone taken. if phone_re.match(username): phone = Phone(phone=username[:10]) if email_re.match(username): email = Email(email=username) try: profile = new_profile(atg_user, phone, email) if profile: newly_created += 1 log.info('Created new profile for %s. id is %s' % (username, profile.id)) except Exception, e: errors += 1 log.exception('Error migrating %s. %s' % (username, repr(e))) if index % 10000 == 0: log.info('Processed %s/%s' % (index, count))
def add_assignment(request): # Error signs and error messages. errMsg = '' success = 0 # Get raw data data = request.POST name = data.get('name') assign_now = data.get('assign_now') date = data.get('date') researcher = request.user.id students = data.get('stuData') templates = data.get('tempData') labels = data.get('labelData') response_attempts = data.get('response_attempts') record_attempts = data.get('record_attempts') allow_typed_response = convert_boolean(data.get('allow_typed_response')) allow_self_rating = convert_boolean(data.get('allow_self_rating')) # Transfer string type list to list type students = decode(students) templates = decode(templates) labels = decode(labels) # Verify date datetime_now = datetime.datetime.now(get_localzone()) if assign_now == 'true': sched_datetime = datetime_now else: sched_datetime = get_localzone().localize( datetime.datetime.strptime(date, "%m/%d/%Y %I:%M %p")) if sched_datetime < datetime_now: success = 1 errMsg = errMsg + 'Custom assignment date needs to be in the future.\n\n' # Determine if students, labels, and templates are empty. stuIsNull = isNull(students) labelIsNull = isNull(labels) tempIsNull = isNull(templates) # Save the data that can be directly assigned to assignment. assignment = Assignment() assignment.name = name assignment.date_assigned = sched_datetime researcher = Researcher.objects.get(id=researcher) assignment.researcher = researcher assignment.response_attempts = response_attempts assignment.recording_attempts = record_attempts assignment.allow_typed_response = allow_typed_response assignment.allow_self_rating = allow_self_rating assignment.save() # Assign student information to assignment, # and judge whether there is an error that both students and labels are empty. # Also check if chosen labels have any students in them if stuIsNull and labelIsNull: success = 1 errMsg = errMsg + 'Either students or labels must not be empty.\n\n' labelStudents = Student.objects.filter(labels__label_name__in=labels, labels__researcher=researcher) if stuIsNull and not labelIsNull: if stuIsNull and labelStudents.count() <= 0: success = 1 errMsg = errMsg + 'The chosen label(s) does not contain any students.\n\n' if not stuIsNull: for stu in students: stuTmp = Student.objects.get(email=stu) assignment.students.add(stuTmp) if not labelIsNull: for students in labelStudents: stuTmp = Student.objects.get(email=students.email) assignment.students.add(stuTmp) # Assign label information to assignment for label in labels: labelTmp = SubjectLabel.objects.get(label_name=label, researcher=researcher) assignment.subject_labels.add(labelTmp) # Assign template information to assignment if tempIsNull: success = 1 errMsg = errMsg + 'Template must not be empty.\n\n' else: for temp in templates: tempTmp = ConversationTemplate.objects.get(pk=temp) assignment.conversation_templates.add(tempTmp) subject = 'Simulated Conversation Assignment Update' msg = 'You have a new assignment. Please check your home page.' recipient = [i[0] for i in assignment.students.values_list('email')] # when an error occurs, there is no need to add this task to the schedule. if success == 0: if assign_now == 'true': sendMail(subject, msg, recipient, '*****@*****.**') else: email = Email(subject=subject, message=msg, assignment=assignment) email.save() else: assignment.delete() return HttpResponse(json.dumps({ 'success': success, 'msg': errMsg, }))
def migrate_subscriptions(): start = datetime(day=1, month=4, year=2011) subscripions_qs = FtbDealsLogin.objects.filter( registration_time__gte=start) newsletter = NewsLetter.objects.get(pk=2) for subscription in subscripions_qs: if SubscriptionSync.objects.filter(ext_id=subscription.id): #print 'Skipping %s: Already synced' % subscription.id continue email = subscription.email_address or '' mobile = subscription.mobile_number or '' name = subscription.register_name or '' if len(email) > 50 or len(name) > 100: #print 'Skipping %s: Long data' % subscription.id continue source = 'atg' if subscription.facebook_user == 1: source = 'facebook-atg' profile = None is_valid_email = False e = None if utils.is_valid_email(email): is_valid_email = True try: e = Email.objects.get(email=email) profile = e.user except Email.DoesNotExist: pass is_valid_mobile = False m = None if utils.is_valid_mobile(mobile): is_valid_mobile = True try: m = Phone.objects.get(phone=mobile) profile = m.user except Phone.DoesNotExist: pass if not is_valid_mobile and is_valid_email: #print 'Skipping %s, %s, %s: Invalid data' % (email, mobile, name) continue if not profile: # Create a new profile in our system if is_valid_email: usr, profile = utils.get_or_create_user(email, email, password=None, first_name=name) if not is_valid_email: usr, profile = utils.get_or_create_user(mobile, '', password=None, first_name=name) if not profile: # Still not able to create profile #print 'Skipping %s, %s, %s: No profile' % (email, mobile, name) continue if not e: try: e = Email.objects.get(email=email) except Email.DoesNotExist: # Create a new email e = Email() e.user = profile e.email = email e.save() if not m: try: m = Phone.objects.get(phone=mobile) except Phone.DoesNotExist: m = Phone() m.user = profile m.phone = mobile m.save() # Create an entry into the subscription table subscr = DailySubscription() subscr.email_alert_on = e subscr.sms_alert_on = m subscr.source = source subscr.timestamp = subscription.registration_time subscr.newsletter = newsletter subscr.save() link = SubscriptionSync() link.ext_id = subscription.id link.account = 'futurebazaar' link.save()