def test_comment_field_created(self): user = User(username='******', password='******', number='+16666666666') user.save() event = Event(**{ u'where': 'test', u'when': timestamp(), u'what': 'test', u'broadcast': False, u'posted_from': [37.422834216666665, -122.08536667833332], u'creator': user[u'username'], }) event.save() comment = 'the test comment' post = self.post('/events/%s/comments/' % event[u'id'], {'comment': comment}) self.assertEqual(post.status, 200, 'comment POST 200') comment = Comment(user=self.get_user()[u'id'], event=event[u'id']) self.assertTrue(u'created' in comment, 'comment has created') get = self.get('/events/%s/comments/' % event[u'id']) self.assertEqual(get.status, 200, 'got comment') got_comment = json.loads(get.read())['comments'][0] self.assertTrue(u'created' in got_comment, 'comment has created')
def post(self, username): username = username.lower() #make sure we're not overwriting an existing user user = User.get({u'username': username}) if user is None: raise HTTPError(404) if username != self.get_session()[u'username']: raise HTTPError(403) old_password = self.body_dict().get('old_password') if old_password is None: self.output({'error': 'MISSING_FIELD', 'field': 'old_password'}, 400) return new_password = self.body_dict().get('new_password') if new_password is None: self.output({'error': 'MISSING_FIELD', 'field': 'new_password'}, 400) return if not User.hash_password(old_password) == user[u'password']: self.output({'error': 'INVALID_PASSWORD', 'field': 'old_password'}, 400) return user[u'password'] = User.hash_password(new_password) user.save()
def decorated(*args, **kwargs): token = None uid = None if 'Authorization' in request.headers and 'UID' in request.headers: token = request.headers['Authorization'] uid = int(request.headers['UID']) if not token or not uid: raise exceptions.InvalidToken('Token or UID Not supplied in header') User.verify_auth_token(token, uid) return f(*args, **kwargs)
def setUp(self): with open('api/test_data/test_data.json') as f: self.test_data = json.load(f) self.factory = RequestFactory() self.token = get_anonymous_user_token() self.auth_token = get_authenticated_user_token() self.test_uuid = str(uuid.uuid4()) self.user = FirebaseUser(self.test_data["users"]["firebase_data"]) u = User(self.test_uuid, 'display name', photo_url='') u.save(db)
def test_password_change(self): new_pass = u'newPassw0rd' response = self.post('/users/%s/' % self.get_user()[u'username'], { u'old_password': self._gen_user_password_, u'new_password': new_pass, }) self.assertEqual(response.status, 200, 'password changed') self.assertEqual(User.get(self.get_user()[u'id'])[u'password'], User.hash_password(new_pass), 'password changed succesfully')
def make_user(self, username=None): if username is None: self.__user_number__ += 1 username = '******' % self.__user_number__ u = User(**{ u'username': username, u'password': User.hash_password(self._gen_user_password_), u'number': '+16656656665', u'revision': uuid.uuid1().hex, u'created': timestamp(), }) u.save() return u
def test_get(self): """ Tests boundary condition when a user does not exists in the DB :return: """ u = User.get('random uid', db) self.assertEqual(u, None)
def invite(self, usernames=None, contacts=None, tz=None): if usernames is not None: #prevent people from inviting themselves if self[u'creator'] in usernames: usernames.remove(self[u'creator']) # convert usernames to user objects users = list(User.find({u'username': {'$in': usernames}})) else: users = list() ret = None if contacts is not None: registered, out_of_numbers, has_username = SMS.register(self, contacts, tz=tz) users += has_username users += [reg for reg in registered if reg not in users] if len(out_of_numbers) > 0: ret = out_of_numbers for user in users: Attendant(user=user[u'id'], event=self[u'id']).save() #send the invite notification if user[u'username'] is not None: name = user[u'username'] else: name = user[u'id'] notifications.send(name, {u'type': 'invite', u'event_revision': self[u'revision'], u'event_id': self[u'id']}) return ret
def get(self): #ensure that username and password are in the args self.require_args('username', 'password') username = self.get_argument(u'username').lower() password = User.hash_password(self.get_argument('password')) user = User.get({u'username': username, u'password': password}) if user is None: raise HTTPError(404) #otherwise generate a token, save it, and return it token = str(db.objects.session.insert({ u'timestamp': timestamp(), u'username': username })) self.write(token)
def get(self, request): """Returns events within a certain radius for a given location GET request parameters: [REQUIRED] id: firebase event id Arguments: request {[type]} -- [ Contains the django request object] Returns: [HttpResponseBadRequest] -- [If event id is not given] [JsonResponse] -- [Containing the event data] """ query = request.GET.get('id', '') if query == '': return HttpResponseBadRequest("Bad request: No Id specified") event = Event.get(query, DB) for key in event.reported_by: if event.reported_by[key]['anonymous']: event.reported_by[key] = { "displayName": "Anonymous", "photoURL": 'https://crowdalert.herokuapp.com/static/images/meerkat.svg', } else: user_id = event.reported_by[key]['userId'] udata = User.get(user_id, DB) event.reported_by[key] = { "displayName": udata.display_name, "photoURL": udata.photo_url, } data = event.to_response_dict() data['spam'] = get_spam_report_data(query) return JsonResponse(data, safe=False)
def get(self): #grab and sanitize the query q = self.get_argument(u'q', u'') q = username_sanitizer.sub('', q) #query: *q* users = User.find({u'username': re.compile(q)}) self.output([user[u'username'] for user in users])
def test_sms_user_creation(self): registered_user = User(username='******', password='******', number='+16666666666') registered_user.save() number = '+15555555555' name = 'Testy Smoth' user = User(number=number, display_name=name) self.assertEqual(user[u'number'], number) self.assertEqual(user[u'display_name'], name) self.assertEqual(user[u'username'], None) user.save() self.assertEqual(user[u'number'], number) self.assertEqual(user[u'display_name'], name) self.assertEqual(user[u'username'], None) got_user = User.get({u'number':number}) self.assertEqual(got_user[u'number'], number) self.assertEqual(got_user[u'display_name'], name) self.assertEqual(got_user[u'username'], None)
def serializable(self, name=False): d = super(Attendant, self).serializable() if name: user = User.get({u'id': self[u'user']}) if user[u'username'] is not None: d[u'username'] = user[u'username'] elif user[u'display_name'] is not None: d[u'display_name'] = user[u'display_name'] return d
def get_user(self): ''' Returns the user that made this request, based on the token used in the request. If no token was attached, or the token was invalid, returns None. ''' #late import to break the cycle from api.users.models import User session = self.get_session() return session and User.get({u'username': session[u'username']})
def create_user(uid, display_name='', photo_url=''): """ Returns an instance of User model :param uid: :param display_name: :param photo_url: :return: """ return User(uid, display_name, photo_url)
def test_sms_comment(self): display_name = 'Test User display' user = User(number='+16666666666', display_name=display_name) user.save() event = Event(**{ u'where': 'test', u'when': timestamp(), u'what': 'test', u'broadcast': False, u'posted_from': [37.422834216666665, -122.08536667833332], u'creator': user[u'username'], }) event.save() comment = 'the test comment' Comment(**{ u'comment': comment, u'event': event[u'id'], u'user': user[u'id'] }).save() get = self.get('/events/%s/comments/' % event[u'id']) self.assertEqual(get.status, 200, 'comment GET 200') try: get = json.loads(get.read()) except ValueError: self.assertTrue(False, 'comment GET not JSON') self.assertTrue('comments' in get, 'comments returned') self.assertEqual(len(get['comments']), 1, 'correct number of comments') self.assertFalse('username' in get['comments'][0], 'username field unavailable') self.assertTrue('display_name' in get['comments'][0], 'display_name field available') self.assertEqual(get['comments'][0]['display_name'], display_name, 'display_name field set correctly')
def test_case_insensitive_login(self): User(**{ u'username': u'test', u'password': User.hash_password(u'passw0rd'), u'number': u'16475557000', }).save() response = self.get('/token/', {u'password': u'passw0rd', u'username': u'TesT'}, auth=False) self.assertEqual(response.status, 200, '/token/ GET')
def put(self, username): username = username.lower() #make sure we're not overwriting an existing user if User.get({u'username': username}) is not None: raise HTTPError(409) #set up the password password = self.body_dict().get('password') if not password: raise HTTPError(403) User(**{ u'username': username, u'password': User.hash_password(password), u'number': self.body_dict().get('number'), u'revision': uuid.uuid1().hex, u'created': int(timestamp()), }).save() self.set_status(201)
def test_new_comment(self): user = User(username='******', password='******', number='+16666666666') user.save() event = Event(**{ u'where': 'test', u'when': timestamp(), u'what': 'test', u'broadcast': False, u'posted_from': [37.422834216666665, -122.08536667833332], u'creator': user[u'username'], }) event.save() comment = 'the test comment' post = self.post('/events/%s/comments/' % event[u'id'], {'comment': comment}) self.assertEqual(post.status, 200, 'comment POST 200') get = self.get('/events/%s/comments/' % event[u'id']) self.assertEqual(get.status, 200, 'comment GET 200') try: get = json.loads(get.read()) except ValueError: self.assertTrue(False, 'comment GET not JSON') self.assertTrue('comments' in get, 'comment GET has comments') self.assertEqual(len(get['comments']), 1, 'comment GET return 1 ' 'comment') self.assertTrue('comment' in get['comments'][0], 'comment GET has ' 'comments') self.assertEqual(get['comments'][0]['comment'], comment, 'comment GET ' 'returned the right comment') self.assertTrue('username' in get['comments'][0], 'comment GET has username') self.assertFalse('display_name' in get['comments'][0], 'comment GET does not have display_name')
def test_sms_notification_creation(self): if not settings.TEST_SMS: return user = User(username='******', password='******', number='+16666666666') user.save() event = Event(**{ u'where': 'test', u'when': timestamp(), u'what': 'test', u'broadcast': False, u'posted_from': [37.422834216666665, -122.08536667833332], u'creator': user[u'username'], }) event.save() number = '+16475551234' name = 'Testy Smoth' reg, out, is_user = SMS.register(event, [{u'number':number, u'name':name}, {u'number':user[u'number'], u'name':name}]) self.assertEqual(len(reg), 1, 'correct ammout registered') self.assertEqual(len(out), 0, 'correct ammout out of numbers') self.assertEqual(len(is_user), 1, 'correct ammout are already users') reged = reg[0] self.assertEqual(reged.__class__, User) self.assertTrue(u'id' in reged) result = notifications.send(reged[u'id'], {u'type': 'invite', u'event_revision': event[u'revision'], u'event_id': event[u'id']}) self.assertEqual(len(result), 1, 'the correct number of notifications ' 'were sent') self.assertTrue(result[0], 'the notification was sent correctly')
def test_save(self): """ Saves the test user in the database and checks if the process is successful by comparing the dictionaries :return: """ u = create_user(self.test_uuid) u.save(db) _u = User.get(self.test_uuid, db) self.assertEqual(u.to_dict(), _u.to_dict())
def to_notify(cls, event, skip=list()): atts = cls.find({u'event': event[u'id']})#, u'status': status.ATTENDING}) ids = [ObjectId(a[u'user']) for a in atts] users = User.find({u'_id': {u'$in': ids}}) ret = [event[u'creator']] for u in users: if u[u'username'] is not None: ret.append(u[u'username']) else: ret.append(u[u'id']) ret = [u for u in ret if u not in skip] return ret
def test_update(self): """ Tests updating user data :return: """ u = create_user(uid=self.test_uuid) uid = u.save(db) u.update(display_name='updated display name', db=db) _u = User.get(uid, db) self.assertEqual(u.to_dict(), _u.to_dict())
def post(self): data = request.get_json() username = data.get('username') email = data.get('email') password = data.get('password') try: user = User.create(username=username, password=password, email=email) except: return "Unable to process request.", 400 return user, 200
def prep_for_response_sms(self): user = User(username='******', password='******', number='+16666666666') user.save() event = Event(**{ u'where': 'test', u'when': timestamp(), u'what': 'test', u'broadcast': False, u'posted_from': [37.422834216666665, -122.08536667833332], u'creator': user[u'username'], }) event.save() smsuser = User(number='+16475555555', display_name='Testy Smoth') smsuser.save() Attendant(user=user[u'id'], event=event[u'id']).save() SMSRegister(contact_number=smsuser[u'number'], twilio_number=settings.TWILIO_NUMBERS[0], event=event[u'id'], expires=event[u'when'], user=user[u'id']).save() return user, event, smsuser
def post(self): data = request.get_json() username = data.get('username') email = data.get('email') password = data.get('password') try: user = User.create( username=username, password=password, email=email ) except: return "Unable to process request.", 400 return user, 200
def get(self, username): u = User.get({u'username': username}) if u is None: raise HTTPError(404) cur_user = self.get_session()[u'username'] follower = Follower.get({u'follower': username, u'followee': cur_user}) following = Follower.get({u'follower': cur_user, u'followee': username}) self.output({ u'username': u['username'], u'created': u[u'created'], u'id': u[u'id'], u'follower': (follower is not None), u'following': (following is not None), })
def test_registraction_username_validation(self): User(**{ u'username': u'test', u'password': User.hash_password(u'passw0rd'), u'number': u'16475557000', }).save() response = self.put('/users/test/', { u'password': u'passw0rd', u'number': u'+16747005290', }, auth=False) self.assertEqual(response.status, 409, 'cannot reuse usernames') response = self.put('/users/tesT/', { u'password': u'passw0rd', u'number': u'+16747005290', }, auth=False) self.assertEqual(response.status, 409, 'usernames case insensitive')
def post(self, event_id): ''' Updates an invitee's attendance ''' body = self.body_dict() username = self.get_session()[u'username'] user = User.get({u'username': username}) #make sure the event exists event = Event.get(event_id) if not event: raise HTTPError(404) #try to grab the user's existing attendance status att = Attendant.get({u'event': event[u'id'], u'user': user[u'id']}) #if the user isn't invited, we need to error out if broadcast is off if att is None: if event[u'broadcast']: att = Attendant(user=user[u'id'], event=event[u'id']) else: raise HTTPError(403) # create a list of acceptable statuses valid_statuses = [v for k, v in status.__dict__.iteritems() if k[0] != '_'] #make sure status is present and a correct value if body.get(u'status') not in valid_statuses: raise HTTPError(400) notify = (att[u'status'] == status.INVITED and body[u'status'] == status.ATTENDING) att[u'status'] = body[u'status'] att.save() if notify: #Send out the attendant notifications for uname in Attendant.to_notify(event, skip=[username]): notifications.send(uname, {u'type': 'attendant', u'event_revision': event[u'revision'], u'event_id': event[u'id'], u'attendant': username})
def save_instance(self, instance, using_transactions, real_dry_run): if not real_dry_run: try: # extra logic if object already exist user = User.objects.get(email=instance.email) pass except Exception: # create new object user = User(id=instance.id) password = instance.password password = make_password(password) created_by = self.context['request'].user project = self.context['request'].user.project user.created_by = created_by user.project = project user.password = password user.save()
def get_comments_from_thread(thread): """ Returns comments thread from Firestore along with the users' information """ comment = Comment.get(thread, DB) if len(comment.participants) == 0: return {"comments": {}, "userData": {}} user_data = {} for user in comment.participants: tmp_user = User.get(user, DB) print(user) user_data[user] = tmp_user.to_dict() response = { 'userData': user_data, 'comments': Comment.get_comment_data(thread, DB) } for comment_uuid in response['comments'].keys(): spam_report_data = get_spam_report_data(comment_uuid) response['comments'][comment_uuid]['spam'] = spam_report_data return response
def get(self, event_id): ''' Gets all comments for a given event. ''' #make sure the event exists if not Event.get(event_id): raise HTTPError(404) #show them comments! comments = Comment.find({u'event': event_id}) comments.sort(u'timestamp', pymongo.ASCENDING) ret_coms = [] for c in comments: user = User.get(c[u'user']) ret = c.__data__ ret[u'username'] = user.__data__.get(u'username', None) if ret[u'username'] is None: del ret[u'username'] ret[u'display_name'] = user.__data__.get(u'display_name', None) if ret[u'display_name'] is None: del ret[u'display_name'] ret_coms.append(ret) self.output({u'comments': ret_coms})
def make_user(self, data): return User(**data)
def user(self): return User.get(self[u'user'])
amount=10000) db_session.add(bill1) db_session.add(bill2) db_session.add(bill3) db_session.commit() role1 = Role(name="admin", description="Administration Privileges") role2 = Role(name="user", description="User Privileges") db_session.add(role1) db_session.add(role2) db_session.commit() user1 = User( email="*****@*****.**", username="******", password="******") user2 = User( email="*****@*****.**", username="******", password="******") db_session.add(user1) db_session.add(user2) db_session.commit() role_user1 = RolesUsers(user=user1, role=role1) role_user2 = RolesUsers(user=user2, role=role2) db_session.add(role_user1) db_session.add(role_user2)
def get(self, username): user = User.get_by_or_abort404(username=username) return user, 200
def delete(self, username): user = User.get_by_or_abort404(username) user.delete() return {}, 204
def get(cls, q): if u'username' in q: q[u'user'] = User.get({u'username': q[u'username']})[u'id'] del q[u'username'] return super(Attendant, cls).get(q)
def get(self): ''' Gets a list of events ''' #store username for later use username = self.get_session()[u'username'] user = User.get({u'username': username}) #grab the sorting/filtering types from the args #funky names avoid conflict with python builtins q_sort = self.get_argument(u'sort', u'soon') q_filter = self.get_argument(u'filter', u'invited') category = self.get_argument(u'category', None) if not q_filter in (u'invited', u'creator', u'public'): raise HTTPError(404) #prep the geospatial info lat = self.get_argument('lat', None) lng = self.get_argument('lng', None) if lat is not None and lng is not None: where = [float(lat), float(lng)] elif q_sort == u'nearby': raise HTTPError(403) events_invited = [ObjectId(att[u'event']) for att in Attendant.find({u'user': user[u'id']})] #prep filtering if q_filter == 'invited': q_filter = {'$or': [ {u'creator': username}, {u'_id': {'$in': events_invited}}, { u'broadcast': True, u'creator': {'$in': user.following()} } ]} elif q_filter == u'creator': q_filter = {u'creator': self.get_argument(u'username', username), u'$or': [{u'_id': {'$in': events_invited}}, {u'broadcast': True}, {u'broadcast': False, u'creator': username}]} elif q_filter == u'public': q_filter = {u'broadcast': True} if category is not None: q_filter[u'category'] = category # This can be uncommented when mongogb gets support for $and # # Limit to nearby times # q_filter.update({'$or': [{u'when': {u'$lt': timestamp() + UNTIL_LIMIT, # u'$gt': timestamp() - SINCE_LIMIT}}, # {u'when': None}]}) # Handle geo sorting if q_sort == u'nearby': #set the sort q_filter.update({u'posted_from': {u'$near': where}}) #use 'soon' as a secondary sort q_sort = u'soon' # Run the query events = db.objects.event.find(q_filter, limit=30) #perform the required sorting if q_sort == u'created': events.sort(u'created', direction=DESCENDING) elif q_sort == u'soon': events.sort(u'when', direction=DESCENDING) events.sort(u'created', direction=DESCENDING) #output the results result = {u'events': [e[u'revision'] for e in events]} self.write(result)
def usernames(self): ids = [ObjectId(a[u'user']) for a in self] users = User.find({u'_id': {u'$in': ids}}) usernames = [u[u'username'] for u in users if u[u'username'] is not None] return usernames
def register(event, contacts, tz=None): # late import to User model can use phone number normalizer from api.users.models import User if not u"id" in event: event[u"id"] = str(event[u"_id"]) registered = list() out_of_numbers = list() has_username = list() for contact in contacts: contact[u"number"] = contact[u"number"] user = User.get({u"number": contact[u"number"]}) if user is None: user = User(number=contact[u"number"], display_name=contact[u"name"]) user.save() # Connectsy users don't get SMS if user[u"username"] is not None: has_username.append(user) continue # make sure this user still has numbers available potential_numbers = [n for n in settings.TWILIO_NUMBERS] for reg in SMSRegister.find({u"contact_number": contact[u"number"]}): if from_timestamp(reg[u"expires"]) > datetime.now(pytz.utc): potential_numbers = [n for n in potential_numbers if n != reg[u"twilio_number"]] if len(potential_numbers) == 0: out_of_numbers.append(contact) continue if tz is None: tz = "America/Toronto" if event[u"when"]: expires = event[u"when"] else: print "created", event[u"created"] expires = timestamp(dt=from_timestamp(event[u"created"]) + timedelta(days=2)) registered.append(user) r = SMSRegister( contact_number=contact[u"number"], twilio_number=potential_numbers[0], event=event[u"id"], expires=expires, user=user[u"id"], tz=tz, ) r.save() # register with the notifications system as well note = { u"user": user[u"id"], u"timestamp": timestamp(), u"client_type": "SMS", u"client_id": r[u"contact_number"], } NotificationRegister(**note).save() return registered, out_of_numbers, has_username
def test_user_get_absolute_url(user: User): assert user.get_absolute_url() == f"/users/{user.username}/"