def post(self): email = self.request.get('email') error = check_email_valid(email) if not error and Guest.query(Guest.email == email).get(): error = u"Данный Email уже существует" if error: invite = Invite.query(Invite.url == self.request.path[1:]).get() template_values = { 'error': error, 'title': invite.title, 'url': invite.url, } template = JINJA_ENVIRONMENT.get_template('invite.html') self.response.write(template.render(template_values)) return path = self.request.get('url') invite = Invite.query(Invite.url == path).get() if invite.count == invite.users_count: self.redirect('/') return invite.users_count += 1 invite.put() token = hashlib.md5(u'%s-%s' % (datetime.now(), email)).hexdigest() guest = Guest(email=email, token=token, date=datetime.now(), invite=invite) guest.put() self.response.set_cookie('token', token, max_age=3600) template = JINJA_ENVIRONMENT.get_template('sign.html') self.response.write(template.render())
def invite_management(): form = CreateInviteForm() existing_invites = Invite.query().fetch(100) return render_template("admin/invites.html", existing_invites=existing_invites, form=form)
def retrieve_invite(self, request): """ JWT required. Retrieve the next 10 invites associated with the user starting from the provided offset, or 0 """ offset = request.offset payload = token.decode_jwt(request.jwt_token) try: user = Key(urlsafe=payload.get('user_key')) except TypeError: raise endpoints.BadRequestException('key was unable to be retrieved') except ProtocolBufferDecodeError: raise endpoints.BadRequestException('key was unable to be retrieved') except Exception as e: raise endpoints.InternalServerErrorException('An error occurred when attempting to take the turn') # user is here let's get their invites invites = Invite.query(Invite.to_player == user, Invite.rejected == False, Invite.accepted == False).fetch(limit=10, offset=offset) return RetrieveInviteResponseForm( invites=[InviteForm( inviter=invite.from_player.urlsafe(), inviter_name=invite.from_player_name ) for invite in invites] )
def create_user(auth, email, name, password, invite_code): """Creates a new user and assigns a OAuth consumer key/secret""" key, secret = create_consumer() invite = Invite.query(Invite.code==invite_code, Invite.is_used==False).get() if not invite: raise UserCreationError("Invalid invite code: %s" % invite_code) success, info = auth.store.user_model.create_user( legit_auth_id(email), unique_properties=['email', 'consumer_key', 'consumer_secret'], email=email, name=name, org=invite.org, invite_code=invite.code, permissions=INITIAL_PERMISSIONS, password_raw=password, consumer_key=key, consumer_secret=secret) if not success: error_msg = "That email is already in use." if 'email' in info else "Something has gone horrible wrong. Email Rob, he probably messed up." raise UserCreationError(error_msg) else: invite.is_used = True invite.put() return info
def create_user(auth, email, name, password, invite_code): """Creates a new user and assigns a OAuth consumer key/secret""" key, secret = create_consumer() invite = Invite.query(Invite.code == invite_code, Invite.is_used == False).get() if not invite: raise UserCreationError("Invalid invite code: %s" % invite_code) success, info = auth.store.user_model.create_user( legit_auth_id(email), unique_properties=['email', 'consumer_key', 'consumer_secret'], email=email, name=name, org=invite.org, invite_code=invite.code, permissions=INITIAL_PERMISSIONS, password_raw=password, consumer_key=key, consumer_secret=secret) if not success: error_msg = "That email is already in use." if 'email' in info else "Something has gone horrible wrong. Email Rob, he probably messed up." raise UserCreationError(error_msg) else: invite.is_used = True invite.put() return info
def getSentInvitations(institution_key): """Query that return list of invites for this user.""" invites = [] queryInvites = Invite.query(Invite.institution_key == institution_key) invites = [invite.make() for invite in queryInvites] return invites
def get_invites(user_email): """Query that return list of invites for this user.""" invites = [] queryInvites = Invite.query(Invite.invitee.IN(user_email), Invite.status == 'sent') invites = [ invite.make() if invite.institution_key.get().state == "active" else '' for invite in queryInvites ] return invites
def query(self): """ Returns a list of invites from the user 1 - Can be filtered by search_term 2 - Will be ordered according to date Descending """ result = [] invite_attendees_group = self.get_invites_grouped_by_attendee() if not invite_attendees_group: return [] all_invites = Invite.query(Invite.key.IN( invite_attendees_group.keys())).order(-Invite.start).fetch() result = [] for invite in all_invites: if self.search_term and self.search_term.lower( ) not in invite.title.lower(): continue invite_attendee = invite_attendees_group[invite.key] result.append({ 'unique_id': invite.unique_id, 'title': invite.title, 'start': convert_to_user_date( invite.start, invite.utc_offset).strftime("%Y-%m-%d %H:%M"), 'end': convert_to_user_date( invite.end, invite.utc_offset).strftime("%Y-%m-%d %H:%M") if invite.end is not None else '', 'poster_image_id': invite.poster_picture.urlsafe() if invite.poster_picture else None, 'confirmed': 0, 'organizer': invite.user.id() if invite.user else None, 'invite_attendee_id': invite_attendee.unique_id, 'invite_attendee_role': invite_attendee.attendee_status, 'response_on': invite_attendee.last_response_on }) return result
def cancel_invite(self, request): """ JWT required. Cancel the invite associated with the user """ target_user = request.target_user payload = token.decode_jwt(request.jwt_token) try: user = Key(urlsafe=payload.get('user_key')) except TypeError: raise endpoints.BadRequestException('key was unable to be retrieved') except ProtocolBufferDecodeError: raise endpoints.BadRequestException('key was unable to be retrieved') except Exception as e: raise endpoints.InternalServerErrorException('An error occurred when attempting to take the turn') if target_user is None or target_user is '': raise endpoints.BadRequestException('The target user was not provided') invite = Invite.query(Invite.from_player == user, Invite.rejected == False, Invite.accepted == False).get() if invite is None: invite = Invite.query(Invite.to_player == user, Invite.rejected == False, Invite.accepted == False).get() if invite is None: raise endpoints.BadRequestException('No pending invites exist for these users') # let's cancel the invite try: invite.rejected = True invite.put() return message_types.VoidMessage() except: raise endpoints.InternalServerErrorException('An error occurred while attempting to cancel the invite')
def get(self): if not users.is_current_user_admin(): self.error(404) self.response.write("<html><head><title>404 Not Found</title></head><body><h1>" "404 Not Found</h1>The resource could not be found.<br /><br /></body></html>") return sort_tag = self.request.get('sort') invite_order = sort_tag_dict[sort_tag] template_values = { 'invites': Invite.query().order(invite_order), } template = JINJA_ENVIRONMENT.get_template('invites_list.html') self.response.write(template.render(template_values))
def post(self): name = self.request.get('name') email = self.request.get('email') invite_code = uuid.uuid4().hex[:invite_code_len].upper() while(Invite.query(Invite.code==invite_code).get()): invite_code = uuid.uuid4().hex[:invite_code_len].upper() invite = Invite(code=invite_code, name=name, email=email) invite.put() context = { 'invite': invite, 'invite_url': webapp2.uri_for('invite', invite_code=invite.code) } path = os.path.join(os.path.dirname(__file__), './templates/admin/index.html') self.response.out.write(template.render(path, context))
def test_send_invites(self): # create the invite resp = self.testapp.post_json( '/_ah/spi/CreateInviteHandler.create_invite', { "jwt_token": self.jwt_token_player_one, "player_two_key": self.user_two.key.urlsafe() }) # verify the invite was sent to user_two resp = self.testapp.post_json( '/_ah/spi/RetrieveInviteHandler.retrieve_invite', {"jwt_token": self.jwt_token_player_two}) data = json.loads(resp.body) self.assertEqual(len(data['invites']), 1, 'One invite was not created') invite = Invite.query(Invite.from_player == self.user_one.key, Invite.to_player == self.user_two.key).get() self.assertIsNotNone(invite)
def get(self, invite_code): invite = Invite.query(Invite.code==invite_code).get() if invite: invite.last_viewed = datetime.now() invite.viewed += 1 invite.put() path = os.path.join(os.path.dirname(__file__), './templates/invite.html') context = { 'invite': invite, 'rsvped': invite.accepted is not None, 'accepted': invite.accepted is None or invite.accepted, 'rejected': invite.accepted is False, } self.response.out.write(template.render(path, context)) else: self.response.set_status(404) self.response.write('not found')
def query(self): """ Returns a list of invites from the user 1 - Can be filtered by search_term 2 - Will be ordered according to date Descending """ result = [] invite_attendees_group = self.get_invites_grouped_by_attendee() if not invite_attendees_group: return [] all_invites = Invite.query( Invite.key.IN(invite_attendees_group.keys()) ).order(-Invite.start).fetch() result = [] for invite in all_invites: if self.search_term and self.search_term.lower() not in invite.title.lower(): continue invite_attendee = invite_attendees_group[invite.key] result.append({ 'unique_id': invite.unique_id, 'title': invite.title, 'start': convert_to_user_date( invite.start, invite.utc_offset ).strftime("%Y-%m-%d %H:%M"), 'end': convert_to_user_date( invite.end, invite.utc_offset ).strftime("%Y-%m-%d %H:%M") if invite.end is not None else '', 'poster_image_id': invite.poster_picture.urlsafe() if invite.poster_picture else None, 'confirmed': 0, 'organizer': invite.user.id() if invite.user else None, 'invite_attendee_id': invite_attendee.unique_id, 'invite_attendee_role': invite_attendee.attendee_status, 'response_on': invite_attendee.last_response_on }) return result
def post(self, invite_code): invite = Invite.query(Invite.code==invite_code).get() if invite: errors = {} status = self.request.get('status') if status not in ['accepted', 'rejected']: errors['status'] = 'invalid' else: invite.accepted = (status == 'accepted') if status == 'accepted': guest = self.request.get('guest') try: guest = int(guest) if guest < 0: errors['guest'] = 'has to be more than zero' else: invite.guest = guest except: errors['guest'] = 'has to be a number' path = os.path.join(os.path.dirname(__file__), './templates/invite.html') if errors: context = { 'invite': invite, 'updated': False, 'errors': errors, 'accepted': invite.accepted is None or invite.accepted, 'rejected': invite.accepted is False, } else: invite.put() context = { 'invite': invite, 'updated': True, 'accepted': invite.accepted is None or invite.accepted, 'rejected': invite.accepted is False, } self.response.out.write(template.render(path, context)) else: self.response.set_status(404) self.response.write('not found')
def get(self): token = self.request.cookies.get('token') if token: template = JINJA_ENVIRONMENT.get_template('sign.html') self.response.write(template.render()) return path = self.request.path[1:] invite = Invite.query(Invite.url == path).get() if invite.count == invite.users_count: self.redirect('/') return invite.views_count += 1 invite.put() template_values = { 'title': invite.title, 'url': invite.url, } template = JINJA_ENVIRONMENT.get_template('invite.html') self.response.write(template.render(template_values))
def clear_data_store(): # Clean the Datastore users = User.query().fetch(keys_only=True) ndb.delete_multi(users) posts = Post.query().fetch(keys_only=True) ndb.delete_multi(posts) institutions = Institution.query().fetch(keys_only=True) ndb.delete_multi(institutions) invites = Invite.query().fetch(keys_only=True) ndb.delete_multi(invites) events = Event.query().fetch(keys_only=True) ndb.delete_multi(events) index_institution = search.Index(name=INDEX_INSTITUTION) delete_all_in_index(index_institution) index_user = search.Index(name=INDEX_USER) delete_all_in_index(index_user)
def post(self): email = self.request.get('email') pattern = re.compile("[^@]+@[^@]+\.[^@]+") if not pattern.match(email): self.redirect('/invite_view') return path = self.request.get('url') invite = Invite.query(Invite.url == path).get() if invite.count == invite.users_count: self.redirect('/') return invite.users_count += 1 invite.put() token = hashlib.md5(u'%s-%s' % (datetime.now(), email)).hexdigest() guest = Guest(email=email, token=token, date=datetime.now(), invite=invite) guest.put() self.response.set_cookie('token', token, max_age=3600) template = JINJA_ENVIRONMENT.get_template('sign.html') self.response.write(template.render())
def create_invite(self, request): """ JWT required. Provided the user does not have an active game with the provided player two, creates an invite for player two. If player two has already invited the user to play a game, accepts the invite and creates a game for them. If a game is created, the user will be able to retrieve it from game endpoint and begin playing. """ player_two_key = request.player_two_key payload = token.decode_jwt(request.jwt_token) try: user = Key(urlsafe=payload.get('user_key')).get() # grab player two please player_two = Key(urlsafe=player_two_key).get() except TypeError: raise endpoints.BadRequestException('key was unable to be retrieved') except ProtocolBufferDecodeError: raise endpoints.BadRequestException('key was unable to be retrieved') except Exception as e: raise endpoints.InternalServerErrorException('An error occurred when attempting to take the turn') if player_two is None: raise endpoints.BadRequestException('Player does not exist') # awesome we have player one and two game = Game.query( Game.player_one == user.key, Game.player_two == player_two.key, Game.player_one_completed == False, Game.player_two_completed == False).get() if game is None: game = Game.query(Game.player_one == player_two.key, Game.player_two == user.key, Game.player_one_completed == False, Game.player_two_completed == False).get() # if a game exists between these users, they need to finish it first please if game is not None: # not entirely certain what to set here, as the request wasn't necessarily wrong, but the # user already has a game with player_two raise endpoints.BadRequestException("An existing game must be finished before starting another one") # let's check for an existing invite between these players invite = Invite.query( Invite.from_player == user.key, Invite.to_player == player_two.key, Invite.accepted == False, Invite.rejected == False ).get() if invite is not None: raise endpoints.BadRequestException( "A pending invite must be accepted or declined before creating another one") invite = Invite.query( Invite.from_player == player_two.key, Invite.to_player == user.key, Invite.accepted == False, Invite.rejected == False ).get() if invite is not None: # awesome! the inviter already has an invitation from the invitee. # start a game, and create the turncards for each player try: game = Game( player_one=player_two.key, player_one_name=player_two.username, player_two=user.key, player_two_name=user.username ) game.put() player_one_turncard = TurnCard( owner=player_two.key, game=game.key ) player_two_turncard = TurnCard( owner=user.key, game=game.key ) player_one_turncard.put() player_two_turncard.put() return CreateInviteResponseForm( game_key=game.key.urlsafe(), game=game.to_form() ) except Exception as e: # print e.message raise endpoints.InternalServerErrorException('An error occurred while attempting to create a game') # alright there are no invites between these players yet so let's make one try: invite = Invite( from_player=user.key, from_player_name=user.username, to_player=player_two.key, to_player_name=player_two.username ) invite.put() return CreateInviteResponseForm() except: raise endpoints.InternalServerErrorException('An error occurred while attempting to create an invite')