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 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 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 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 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 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 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 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 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 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 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 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 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 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): ''' 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 __init__(self, username=None, number=None, **kwargs): if username: kwargs[u'user'] = User.get({u'username': username})[u'id'] elif number: kwargs[u'user'] = User.get({u'number': number})[u'id'] super(Attendant, self).__init__(**kwargs)
def user(self): return User.get(self[u'user'])
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 __init__(self, **kwargs): if u'username' in kwargs: kwargs[u'user'] = User.get({u'username': kwargs[u'username']})[u'id'] super(Comment, self).__init__(**kwargs)
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