Example #1
0
    def get(self, request):
        '''
        Returns the dbGaP authorization status of the user.
        '''
        user_email = None

        if endpoints.get_current_user() is not None:
            user_email = endpoints.get_current_user().email()

        if user_email is None:
            raise endpoints.UnauthorizedException("Authentication unsuccessful.")

        # this checks the controlled-access google group
        am_dbgap_authorized = is_dbgap_authorized(user_email)

        if not am_dbgap_authorized:
            return ReturnJSON(message="{} is not on the controlled-access google group.".format(user_email),
                              dbGaP_authorized=False)

        django.setup()

        # all the following five situations should never happen

        # 1. check to make sure they have an entry in auth_user
        try:
            django_user = Django_User.objects.get(email=user_email)
        except (ObjectDoesNotExist, MultipleObjectsReturned), e:
            logger.error("Email {} is in {} group but did not have a unique entry in auth_user table. Error: {}"
                         .format(user_email, CONTROLLED_ACL_GOOGLE_GROUP, e))
            request_finished.send(self)
            raise endpoints.NotFoundException("{} is in the controlled-access google group "
                                              "but does not have an entry in the user database."
                                              .format(user_email))
    def cloud_storage_file_paths(self, request):
        """
        Takes a cohort id as a required parameter and returns cloud storage paths to files
        associated with all the samples in that cohort, up to a default limit of 10,000 files.
        Authentication is required. User must have READER or OWNER permissions on the cohort.
        """
        user_email = None
        cursor = None
        db = None

        limit = request.get_assigned_value('limit')
        platform = request.get_assigned_value('platform')
        pipeline = request.get_assigned_value('pipeline')
        cohort_id = request.get_assigned_value('cohort_id')

        if endpoints.get_current_user() is not None:
            user_email = endpoints.get_current_user().email()

        if user_email is None:
            raise endpoints.UnauthorizedException(
                "Authentication failed. Try signing in to {} to register "
                "with the web application.".format(BASE_URL))

        django.setup()
        try:
            user_id = Django_User.objects.get(email=user_email).id
            Django_Cohort.objects.get(id=cohort_id)
            Cohort_Perms.objects.get(cohort_id=cohort_id, user_id=user_id)
        except (ObjectDoesNotExist, MultipleObjectsReturned), e:
            logger.warn(e)
            err_msg = "Error retrieving cohort {} for user {}: {}".format(cohort_id, user_email, e)
            if 'Cohort_Perms' in e.message:
                err_msg = "User {} does not have permissions on cohort {}. " \
                          "Error: {}".format(user_email, cohort_id, e)
            raise endpoints.UnauthorizedException(err_msg)
    def googlegenomics(self, request):
        """
        Returns a list of Google Genomics dataset and readgroupset ids associated with
        all the samples in a specified cohort.
        Authentication is required. User must have either READER or OWNER permissions on the cohort.
        """
        cursor = None
        db = None
        user_email = None
        cohort_id = request.get_assigned_value('cohort_id')

        if endpoints.get_current_user() is not None:
            user_email = endpoints.get_current_user().email()

        if user_email is None:
            raise endpoints.UnauthorizedException(
                "Authentication failed. Try signing in to {} to register with the web application."
                    .format(BASE_URL))

        django.setup()
        try:
            user_id = Django_User.objects.get(email=user_email).id
            Django_Cohort.objects.get(id=cohort_id)
            Cohort_Perms.objects.get(cohort_id=cohort_id, user_id=user_id)
        except (ObjectDoesNotExist, MultipleObjectsReturned), e:
            logger.warn(e)
            err_msg = "Error retrieving cohort {} for user {}: {}".format(cohort_id, user_email, e)
            if 'Cohort_Perms' in e.message:
                err_msg = "User {} does not have permissions on cohort {}. Error: {}" \
                    .format(user_email, cohort_id, e)
            request_finished.send(self)
            raise endpoints.UnauthorizedException(err_msg)
Example #4
0
    def list(self, unused_request):
        """
        Returns information about cohorts a user has either READER or OWNER permission on.
        Authentication is required. Optionally takes a cohort id as a parameter to
        only list information about one cohort.
        """
        user_email = None
        cursor = None
        db = None

        if endpoints.get_current_user() is not None:
            user_email = endpoints.get_current_user().email()

        if user_email is None:
            raise endpoints.UnauthorizedException(
                "Authentication failed. Try signing in to {} to register "
                "with the web application.".format(BASE_URL))

        django.setup()
        try:
            user_id = Django_User.objects.get(email=user_email).id
        except (ObjectDoesNotExist, MultipleObjectsReturned), e:
            logger.warn(e)
            request_finished.send(self)
            raise endpoints.NotFoundException("%s does not have an entry in the user database." % user_email)
Example #5
0
 def _get_user_info(self, request):
     """" Helper method to get user info """
     if request.email != None and request.user_name != None:
         user_name = request.user_name
         email = request.email
     else:
         user_name = endpoints.get_current_user().nickname()
         email = endpoints.get_current_user().email()
     return email, user_name
Example #6
0
 def GetUserId(self):
     
     if endpoints.get_current_user() == None:
         raise endpoints.UnauthorizedException("Must log in")
     
     user = User.query(User.username == endpoints.get_current_user().email()).get()
     if user == None:
         user = User(username = endpoints.get_current_user().email())
         user.put()
     return user.key
    def UserInsert(self, user):
        """ Creates create user"""
        current_user = endpoints.get_current_user()
        user_id = self.get_user_id(current_user)
        users = User.query(User.user_id == user_id)
        if users.count() == 0:
            user.user_id = user_id
            if user.image != None:
                image = user.image
                if len(image) > 6*1024*1024:
                    raise endpoints.BadRequestException("Max. image size is 6*1024*1024 bytes")
                write_retry_params = gcs.RetryParams(backoff_factor=1.1)
                filename = "/" + BUCKET_NAME + "/" +str(uuid.uuid4())
                png = images.rotate(image, 0, output_encoding=images.PNG)
                gcs_file = gcs.open(filename,'w',retry_params=write_retry_params,content_type='image/png',)
                gcs_file.write(png)
                gcs_file.close()
                blobkey = blobstore.create_gs_key("/gs" + filename)
                url = images.get_serving_url(blobkey)
                user.image_url = url
                user.blobkey = filename
            del user.image
            """TODO: write better code; temp fix to get users name"""
            headers = {'Authorization': os.getenv('HTTP_AUTHORIZATION')}
            url = "https://www.googleapis.com/plus/v1/people/me"
            result = urlfetch.fetch(url=url,
            method=urlfetch.GET,
            headers=headers)

            profile = json.loads(result.content)
            print(profile)
            user.name = profile['displayName']
            profUrl = profile['url']
            if user.im != None:
                try:
                    im_json = json.loads(user.im)
                except:
                    raise endpoints.BadRequestException("im needs to be empty or valid json")
            else:
                im_json = {}
            im_json["gplus"] = {"url":profUrl,"display":user.name}
            user.im = json.dumps(im_json)
            current_user = endpoints.get_current_user()
            email = current_user.email()
            if self.is_current_user_admin():
                user.is_volunteer = True
                user.is_admin = True
            else:
                user.is_volunteer = False
                user.is_admin = False
            user.put()
            print(user)
            return user
        else:
            return users.get()
Example #8
0
 def create_user(self, request):
     """Create a User. Requires a unique username"""
     name = str(endpoints.get_current_user())
     email = str(endpoints.get_current_user().email())
     if User.query(User.name == name).get():
         raise endpoints.ConflictException(
             'A User with that name already exists!')
     user = User(name=name, email=email)
     user.put()
     return StringMessage(message='User {} created!'.format(
         name))
Example #9
0
 def get_my_words(self, void_request):
     user = endpoints.get_current_user()
     if entities.User.get_by_user(user):
         entity = entities.Record.get_record(endpoints.get_current_user(),
                                             datetime.date.today())
         if entity:
             rec = entities.create_record_message(entity)
             return GetWordsResponse(records = [rec])
         else:
             return GetWordsResponse(records = [])
     else:
         return GetWordsResponse(records = [])
Example #10
0
	def get_directions_collection(self, request):
		current_user = endpoints.get_current_user()
		logging.info(current_user.email() if current_user is not None
             else 'Anonymous')
		current_user = endpoints.get_current_user()
		try:
			response = parseCollection(request)
			length = response['length']
			steps = response['steps']
			return DirectionsCollection(length=length, steps=steps)
		except (IndexError, TypeError):
			raise endpoints.NotFoundException('Reciepe url "%s" not found.' %
											  (request.sentence,))
    def _createSessionObject(self,request):
        """Create Session Object, returning SessionForm/request"""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)
        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")
        #Get conference key
        wsck = request.websafeConferenceKey
        #Get conference object
        c_key = ndb.Key(urlsafe = wsck)
        conf = c_key.get()
        #check if conf exist
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % wsck)
        #check if user is the creator of the conference
        if conf.organizerUserId != getUserId(endpoints.get_current_user()):
            raise endpoints.ForbiddenException(
                'You must be the organizer to create a session.')

        #copy Session/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_field()}
        #convert date and time from strings to Date objects;
        if data['date']:
            data['date'] = datetime.strptime(
                data['data'][:10], "%Y-%m-%d".date())
        if data['startTime']:
            datat['startTime'] = datetime.strptime(
                data['startTime'][:10], "%H,%M").time()
        # Allocate new Session ID with Conference key as the parent
        session_id = Session.allocate_ids(size = 1, parent = c_key)[0]
        # Make Session key from ID
        session_key = ndb.Key(Session, session_id, parent = c_key)
        data['key'] = session_key
        #Save session into database
        Session(**data).put()
        # Taskque for featuredSpeaker endpoint
        #check for featured speaker in conference:
        taskqueue.add(params={'speaker': data['speaker'],
                              'websafeConferenceKey': wsck
                              },
                      url='/tasks/check_featured_speaker')

        session = session_key.get()
        return self._copySessionToForm(session)
Example #12
0
 def grade_entry_insert(self, a_grade_entry):
     """ Insert a GradeEntry. """
     # Find the assignment using the assignment_id to make sure the owner is a match.
     an_assignment_key = ndb.Key(Assignment, a_grade_entry.assignment_id)
     assignment_for_entry = an_assignment_key.get()
     if assignment_for_entry is None:
         raise endpoints.NotFoundException('No Assignment found for that id.')
     if endpoints.get_current_user().email().lower() != assignment_for_entry.owner_email:
         raise endpoints.ForbiddenException("You can only edit/create grade entries in your own Assignments.")
     # Consider. It might be a nice feature for the client to check if the student name already has a grade.
     a_grade_entry.parent = assignment_for_entry # Keep both in the same entity group so that transactions could be used.
     a_grade_entry.owner_email = endpoints.get_current_user().email().lower()
     a_grade_entry.put()
     return a_grade_entry
Example #13
0
    def am_i_dbgap_authorized(self, request):
        '''
        Returns information about the user.
        :param token: Optional. Access token with email scope to verify user's google identity.
        :return: ReturnJSON with msg string indicating presence or absence on the controlled-access list.
        '''
        print >> sys.stderr,'Called '+sys._getframe().f_code.co_name
        user_email = None

        if endpoints.get_current_user() is not None:
            user_email = endpoints.get_current_user().email()

        # users have the option of pasting the access token in the query string
        # or in the 'token' field in the api explorer
        # but this is not required
        access_token = request.__getattribute__('token')
        if access_token:
            user_email = get_user_email_from_token(access_token)

        if user_email:
            # this checks the controlled-access google group
            am_dbgap_authorized = is_dbgap_authorized(user_email)

            if not am_dbgap_authorized:
                return ReturnJSON(msg="You are not on the controlled-access google group.")

            django.setup()
            # all the following five situations should never happen

            # 1. check to make sure they have an entry in auth_user
            try:
                django_user = Django_User.objects.get(email=user_email)
            except (ObjectDoesNotExist, MultipleObjectsReturned), e:
                logger.error("Email {} is in {} group but did not have a unique entry in auth_user table. Error: {}"
                             .format(user_email, CONTROLLED_ACL_GOOGLE_GROUP, e))
                request_finished.send(self)
                raise endpoints.NotFoundException("{} is in the controlled-access google group "
                                                  "but does not have an entry in the user database."
                                                  .format(user_email))

            # 2. check to make sure they have an entry in accounts_nih_user
            try:
                nih_user = NIH_User.objects.get(user_id=django_user.id)
            except (ObjectDoesNotExist, MultipleObjectsReturned), e:
                logger.error("Email {} is in {} group but did not have a unique entry in "
                             "accounts_nih_user table. Error: {}"
                             .format(user_email, CONTROLLED_ACL_GOOGLE_GROUP, e))
                raise endpoints.NotFoundException("{} is in the controlled-access google group "
                                                  "but does not have an entry in the nih_user database."
                                                  .format(user_email))
    def _createSessionObject(self, request):
        """Create or update Conference object, returning SessionForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")

        #get cinference key
        wsck = request.websafeConferenceKey
        # get conference object
        c_key = ndb.Key(urlsafe=wsck)
        conf = c_key.get()
        # check that conference exists or not
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % wsck)
        # check that user is owner
        if conf.organizerUserId != getUserId(endpoints.get_current_user()):
            raise endpoints.ForbiddenException(
                'You must be the organizer to create a session.')

        # copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        # convert date and time from strings to Date objects; 
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:10],  "%H, %M").time()
        # allocate new Session ID with Conference key as parent
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]
        # make Session key from ID
        s_key = ndb.Key(Session, s_id, parent=c_key)
        data['key'] = s_key
        data['websafeConferenceKey'] = wsck
        del data['sessionSafeKey']

        #  save session into database
        Session(**data).put()
        # This task wil send a confirmation email to the owner 
        taskqueue.add(params={'email': user.email(),
            'conferenceInfo': repr(request)},
            url='/tasks/send_confirmation_session_email'
        )
        return request
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""  # noqa
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # Get user id by calling getUserId(user)
        user_id = getUserId(user)

        # Create a new key of kind Profile from the id.
        p_key = ndb.Key(Profile, user_id)

        # Get the entity from datastore by using get() on the key
        profile = p_key.get()

        # If profile doesn't exist, we create a new one
        if not profile:
            profile = Profile(
                key=p_key,
                displayName=user.nickname(),
                mainEmail=user.email(),
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
            )
            # Save the profile to datastore
            profile.put()

        return profile      # return Profile
Example #16
0
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")

        # TODO 1
        # step 1. copy utils.py from additions folder to this folder
        #         and import getUserId from it
        # step 2. get user id by calling getUserId(user)
        # step 3. create a new key of kind Profile from the id

        # TODO 3
        # get the entity from datastore by using get() on the key
        profile = None
        if not profile:
            profile = Profile(
                key=None,  # TODO 1 step 4. replace with the key from step 3
                displayName=user.nickname(),
                mainEmail=user.email(),
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
            )
            # TODO 2
            # save the profile to datastore

        return profile  # return Profile
Example #17
0
 def getConferenceSessionsByTimeAndType(self, request):
     """Given a conference, Session Type and date,
     return matching sessions.
     """
     # Ensure that user is authed
     user = endpoints.get_current_user()
     if not user:
         raise endpoints.UnauthorizedException('Authorization Required')
     # Limit Sessions by Conference key
     confSessions = Session.query(
         ancestor=ndb.Key(urlsafe=request.websafeConferenceKey))
     # convert the time string passed to time() object
     lastTime = datetime.strptime(request.noLaterThen[:5], "%H:%M").time()
     # Retrieve Sessions that start on or before the noLaterThen time
     timeSessions = confSessions.filter(Session.startTime <= lastTime)
     # Store a list of the Keys that meet the time criteria
     timeKeys = [sesh.key for sesh in timeSessions]
     # Retrieve Sessions that are not of the typeOfSession passed in
     typeSessions = confSessions.filter(
         Session.typeOfSession != request.typeOfSession)
     # filter typeSessions by timeSession Keys
     sessions = typeSessions.filter(Session.key.IN(timeKeys))
     # Return a SessionForm for each Session
     return SessionForms(
         items = [self._copyConferenceSessionToForm(
             sesh) for sesh in sessions])
Example #18
0
 def _createSpeakerObject(self, request):
     """Create a Speaker object, returning SpeakerForm/request."""
     # Ensure that the current user is logged in and get user ID
     user = endpoints.get_current_user()
     if not user:
         raise endpoints.UnauthorizedException('Authorization required')
     # Verify that a name was provided for the speaker
     if not request.name:
         raise endpoints.BadRequestException(
             "Speaker 'name' field required")
     # Copy SpeakerForm/ProtoRPC Message into dict
     data = ({field.name: getattr(request, field.name)
             for field in request.all_fields()})
     # Create a key for the Speaker
     s_id  = Session.allocate_ids(size=1)[0]
     s_key = ndb.Key(Speaker, s_id)
     # Update stored session with session keys
     data['key'] = s_key
     # create Session, send email to organizer confirming
     # creation of Session & return (modified) SessionForm
     Speaker(**data).put()
     taskqueue.add(
         params = {
             'email'   : user.email(),
             'subject' : 'You Added %s as a Speaker!' % data['name'],
             'body'    : 'Here are the details for the added speaker:',
             'info'    : repr(request)},
         url    = '/tasks/send_confirmation_email')
     return request
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")

        # copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        del data['websafeKey']
        # del data['organizerDisplayName']

        # add default values for those missing (both data model & outbound Message)
        for df in DEFAULTS_SESSION:
            if data[df] in (None, []):
                data[df] = DEFAULTS_SESSION[df]
                setattr(request, df, DEFAULTS_SESSION[df])

        # Getting a TEMP conference key for the moment
        q = Conference.query()
        cons = q.get()
        c_key = cons.key
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, s_id, parent=c_key)
        data['key'] = s_key

        Session(**data).put()

        return request
    def _createSessionObject(self, request):
        """Create Session object from request and store in datastore."""
        # Check that user logged in
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # Get conference
        urlkey = request.websafeConferenceKey
        conf_key = ndb.Key(urlsafe=urlkey)
        conf = conf_key.get()

        # Check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % urlkey)

        # Check that logged in user is organizer
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the organizer can add sessions to the conference.')

        # Every session must have a name
        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")

        # Copy SessionForm/ProtoRPC Message into dictionary
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}

        # Prepare all data for SessionForm
        del data['websafeConferenceKey']
        del data['websafeKey']
        del data['organizerDisplayName']
        data['organizerUserId'] = user_id

        # Convert dates from strings to DateTime objects
        if data['date']:
          data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()

        # Convert time from strings to DateTime objects
        if data['startTime']:
          data['startTime'] = datetime.strptime(data['startTime'],"%H:%M:%S").time()

        # Generate session id
        session_id = Session.allocate_ids(size=1, parent=conf_key)[0]

        # Generate session key with conference key as parent
        session_key = ndb.Key(Session, session_id, parent=conf_key)
        data['key'] = session_key

        # Write to datastore
        Session(**data).put()


        # Make announcement for featured speaker via task queue.
        speaker = data['speaker']
        taskqueue.add(params={'speaker': speaker, 'websafeConferenceKey': urlkey}, url='/tasks/set_session_announcement')

        return self._copySessionToForm(session_key.get())
    def _updateConferenceObject(self, request):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")
        user_id = getUserId(user)

        # copy ConferenceForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}

        # update existing conference
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # check that conference exists
        if not conf:
            raise endpoints.NotFoundException("No conference found with key: %s" % request.websafeConferenceKey)

        # check that user is owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException("Only the owner can update the conference.")

        # Not getting all the fields, so don't create a new object; just
        # copy relevant fields from ConferenceForm to Conference object
        for field in request.all_fields():
            data = getattr(request, field.name)
            # only copy fields where we get data
            if data not in (None, []):
                # special handling for dates (convert string to Date)
                if field.name in ("startDate", "endDate"):
                    data = datetime.strptime(data, "%Y-%m-%d").date()
                    if field.name == "startDate":
                        conf.month = data.month
                # write to Conference object
                setattr(conf, field.name, data)
        conf.put()
        prof = ndb.Key(Profile, user_id).get()
        return self._copyConferenceToForm(conf, getattr(prof, "displayName"))
Example #22
0
    def locations_insert(self, location):
        """Insert a new location for the current user.

        Not part of the actual mirror API but used by the emulator.
        """

        if location.id is not None:
            raise endpoints.BadRequestException("ID is not allowed in request body.")

        location.put()

        # Notify location subscriptions

        data = {}
        data["collection"] = "locations"
        data["itemId"] = "latest"
        operation = Operation.UPDATE
        data["operation"] = operation.name

        header = {"Content-type": "application/json"}

        query = Subscription.query().filter(Subscription.user == endpoints.get_current_user())
        query = query.filter(Subscription.collection == "locations")
        query = query.filter(Subscription.operation == operation)
        for subscription in query.fetch():
            data["userToken"] = subscription.userToken
            data["verifyToken"] = subscription.verifyToken

            req = urllib2.Request(subscription.callbackUrl, json.dumps(data), header)
            try:
                urllib2.urlopen(req)
            except:
                logging.error(sys.exc_info()[0])

        return location
Example #23
0
    def addSessionToWishlist(self, request):
        """Add a session to user's wishlist"""
        user = endpoints.get_current_user()

        # check if logged in
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")

        # grab user profile
        prof = self._getProfileFromUser()

        # grab session using urlsafe key
        wsck = request.websafeSessionKey
        sess = ndb.Key(urlsafe=wsck).get()

        # check if session exists
        if not sess:
            raise endpoints.NotFoundException("No Session found with key: %s" % wsck)

        # check if user already registered otherwise add
        if wsck in prof.sessionsKeysToAttend:
            raise ConflictException("You have already registered for this session")

        # register user, take away one seat
        prof.sessionsKeysToAttend.append(wsck)

        prof.put()
        return self._copySessionToForm(sess)
Example #24
0
    def timeline_get(self, card):
        """Get card with ID for the current user"""

        if not card.from_datastore or card.user != endpoints.get_current_user():
            raise endpoints.NotFoundException("Card not found.")

        return card
Example #25
0
    def deleteSessionInWishlist(self, request):
        """Removes the session from the user's list of 
        sessions they are attending"""
        # boolean value
        retval = None
        # check if logged in
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException("Authorization required")

        # grab user profile
        prof = self._getProfileFromUser()

        # use webSafeSessionKey to grab session instance
        wsck = request.websafeSessionKey
        sess = ndb.Key(urlsafe=wsck).get()

        # check if session exists
        if not sess:
            raise endpoints.NotFoundException("No Session found with key: %s" % wsck)

        # Check if session is in user's wishlist then delete session from list
        if wsck in prof.sessionsKeysToAttend:
            prof.sessionsKeysToAttend.remove(wsck)
            retval = True

        prof.put()
        return BooleanMessage(data=retval)
Example #26
0
    def attachments_delete(self, request):
        """Remove single attachment for a timeline card"""

        current_user = endpoints.get_current_user()
        if current_user is None:
            raise endpoints.UnauthorizedException("Authentication required.")

        card = ndb.Key("TimelineItem", request.itemId).get()

        if card is None or card.user != current_user:
            raise endpoints.NotFoundException("Attachment not found.")

        if card.attachments is not None:
            for att in card.attachments:
                if att.id == request.attachmentId:
                    # Delete attachment from blobstore
                    try:
                        gcs.delete(bucket + "/" + att.id)
                    except gcs.NotFoundError:
                        pass

                    # Remove attachment from timeline card
                    card.attachments.remove(att)
                    card.put()

                    return AttachmentResponse(id=att.id)

        raise endpoints.NotFoundException("Attachment not found.")
Example #27
0
    def memes_create(self, request):
      current_user = endpoints.get_current_user()
      if current_user is None:
        raise endpoints.UnauthorizedException('Invalid token.')

      imageUrl = request.image_url
      text = request.text

      # Create the Meme
      meme = CloudMemeImage()
      mergedImage = meme.render_meme(imageUrl, 'impact', text,
                                     '', '')

      # Upload to Cloud Storage
      cloudMemeStorage = CloudMemeStorage()
      url = cloudMemeStorage.uploadFile(BUCKET, mergedImage)


      # Mongo: Create the meme meta data
      db = self.getMongo()
      meme = {"url": url,
              "text": text,
              "user": current_user.nickname(),
              "votes": 0}
      memes = db.memes
      memes.insert(meme)

      return Meme(image_url=url, text=text)
Example #28
0
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # TODO 1
        # step 1. copy utils.py from additions folder to this folder
        #         and import getUserId from it
        # step 2. get user id by calling getUserId(user)
        # step 3. create a new key of kind Profile from the id
        user_id = utils.getUserId(user)
        p_key = ndb.Key(Profile, user_id)
        logging.info("do we even generate a Key?")
        logging.info(pKey)
        print >> sys.stderr, "Something to log."
        # TODO 3
        # get the entity from datastore by using get() on the key
        profile = pKey.get()
        if not profile:
            profile = Profile(
                key = p_key,
                displayName = user.nickname(), 
                mainEmail= user.email(),
                teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED),
            )
            # TODO 2
            # save the profile to datastore
            profile.put()
        return profile      # return Profile
Example #29
0
 def _createWishlistObject(self, request):
     """add session into user profile"""
     # make sure user is authed
     user = endpoints.get_current_user()
     if not user:
         raise endpoints.UnauthorizedException('Authorization required')
     user_id = getUserId(user)
     
     #get user profile
     prof = ndb.Key(Profile, user_id).get()
     
     #get session
     session = ndb.Key(urlsafe=request.session_key).get()
     
     #raise exception if there is no session for the key
     if not session:
         raise endpoints.NotFoundException('No session found with key: %s' % request.session_key)
     
     #raise exception if the session is already added 
     if request.session_key in prof.wishlistSession:
         raise ConflictException("The session is already in your wishlist!")
     
     #add session wishlist to user profile
     prof.wishlistSession.append(request.session_key)
     prof.put()
     return BooleanMessage(data=True)
Example #30
0
    def contacts_get(self, contact):
        """Get contact with ID for the current user"""

        if not contact.from_datastore or contact.user != endpoints.get_current_user():
            raise endpoints.NotFoundException("Contact not found.")

        return contact
Example #31
0
File: api.py Project: jerrayl/Eduto
 def get_task_list(self, _):
     usr = endpoints.get_current_user()
     tasks = task.get_list(usr=usr)
     message = []
     for t in tasks:
         message.append(
             msg.TaskMessage(title=t.title,
                             time_added=t.time_added,
                             usr=user.get(t.usr).name,
                             subject=t.subject,
                             due_date=datetime.datetime.combine(
                                 t.due_date, datetime.datetime.min.time()),
                             url_id=t.key.urlsafe(),
                             cls=t.cls,
                             description=t.description,
                             school=t.school,
                             done=t.done,
                             is_owner=t.usr == usr))
     return msg.TasksMessage(tasks=message)
Example #32
0
    def deleteFromWishlist(self, request):
        """Remove session with given key from wishlist."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)
        profile = p_key.get()

        session = ndb.Key(urlsafe=request.sessionKey).get()
        if not session:
            raise endpoints.NotFoundException('No session found with key: %s' %
                                              request.sessionKey)
        if request.sessionKey in profile.SessionKeysInWishList:
            profile.SessionKeysInWishList.remove(request.sessionKey)

        profile.put()

        return BooleanMessage(data=True)
Example #33
0
    def sendMessage(self, request):
        user = endpoints.get_current_user()
        # If there's no user defined, the request was unauthenticated, so we
        # raise 401 Unauthorized.
        if not user:
            raise endpoints.UnauthorizedException

        query = ndb.Key(MessageMock, request.messageType).get()
        publisher = pubsub.Client()
        topic = publisher.topic(request.topic)

        for x in xrange(request.numberOfMessage):
            msg = self._processDinamycFields(query.jsonMsg)

            print  msg

            topic.publish(msg)

        return DefaultResponse(content="Published messages.")
 def giveRolesToUser(self, request):
     user = endpoints.get_current_user()
     user_id = helper.getUserId()
     registeredUser = helper.getRegisteredUser()
     if not registeredUser:
         raise endpoints.ForbiddenException("Not Allowed to update user")
     if not (registeredUser.isAdmin == True
             or registeredUser.isOwner == True):
         raise endpoints.ForbiddenException("Not Allowed to update user")
     userToUpdate = RegisteredUsers.query(RegisteredUsers.key == ndb.Key(
         urlsafe=request.registeredUserKey)).fetch()
     if not userToUpdate:
         raise endpoints.ForbiddenException("Enter Correct Key")
     userToUpdate = userToUpdate[0]
     userToUpdate.isAdmin = True if request.isAdmin == True else False
     userToUpdate.isTeacher = True if request.isTeacher == True else False
     userToUpdate.isStudent = True if request.isStudent == True else False
     userToUpdate.isPrincipal = True if request.isPrincipal == True else False
     userToUpdate.put()
    def _updateConferenceObject(self, request):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # copy ConferenceForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }

        # update existing conference
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)

        # check that user is owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')

        # Not getting all the fields, so don't create a new object; just
        # copy relevant fields from ConferenceForm to Conference object
        for field in request.all_fields():
            data = getattr(request, field.name)
            # only copy fields where we get data
            if data not in (None, []):
                # special handling for dates (convert string to Date)
                if field.name in ('startDate', 'endDate'):
                    data = datetime.strptime(data, "%Y-%m-%d").date()
                    if field.name == 'startDate':
                        conf.month = data.month
                # write to Conference object
                setattr(conf, field.name, data)
        conf.put()
        prof = ndb.Key(Profile, user_id).get()
        return self._copyConferenceToForm(
            conf,
            getattr(prof, 'displayName') if prof else None)
Example #36
0
    def breakMessage(self, request):
        user = endpoints.get_current_user()
        # If there's no user defined, the request was unauthenticated, so we
        # raise 401 Unauthorized.
        if not user:
            raise endpoints.UnauthorizedException

        query = ndb.Key(MessageMock, request.messageType).get()

        for x in xrange(request.numberOfMessage):
            xpto = query.jsonMsg

            print self._processDinamycFields(query.jsonMsg)





        return DefaultResponse(content="Done")
    def deleteSessionInWishlist(self, request):
        """Removes the session from the user's list of sessions they are
        interested in attending."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException(
                'You must be logged in to use this method.')

        user_id = getUserId(user)

        prof = ndb.Key(Profile, user_id).get()
        # verify that the session is in the user's wishlist.
        if request.websafeSessionKey not in prof.wishList:
            raise endpoints.NotFoundException('Session not on wishlist.')

        prof.wishList.remove(request.websafeSessionKey)
        prof.put()

        return self._copyProfileToForm(prof)
    def _createWishlistObject(self, request):
        """Create or update Wishlist object, returning WishlistForm/request."""

        # check auth
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # check sessionName exists
        if not request.sessionName:
            raise endpoints.UnauthorizedException('Name required')
        # get userId
        user_id = getUserId(user)

        # get session key
        this_session = Session.query(Session.name == request.sessionName).get()

        # populate dict
        data = {
            'userId': user_id,
            'sessionName': request.sessionName,
            'sessionKey': this_session.key,
            'typeOfSession': this_session.typeOfSession
        }

        # generate wishlist key from session key
        p_key = this_session.key
        c_id = Wishlist.allocate_ids(size=1, parent=p_key)[0]
        c_key = ndb.Key(Wishlist, c_id, parent=p_key)
        data['key'] = c_key

        # query wishlist, filter by userId and sessionName, then count
        q = Wishlist.query()
        q = q.filter(Wishlist.userId == user_id)

        # if this session already in user's wishlist, bounce
        for i in q:
            if i.sessionKey == this_session.key:
                raise endpoints.UnauthorizedException(
                    'Session already added to wishlist')

        # save to wishlist
        Wishlist(**data).put()
        return request
    def getSessionsInWishlist(self, request):
        """
        Get list of sessions that user has added to wishlist
        """

        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # get user profile & make profile key
        prof = self._getProfileFromUser()

        # get sessionsWishList from profile.
        sessions = ndb.get_multi(prof.sessionsWishList)

        # return set of SessionForm objects per Session
        return SessionForms(sessions=[
            self._copySessionToForm(session) for session in sessions
        ])
Example #40
0
 def _addSubmission(self, request):
     user = endpoints.get_current_user()
     if not user:
         raise endpoints.UnauthorizedException("Please login to continue")
     data = {
         field.name: getattr(request, field.name)
         for field in request.all_fields()
     }
     q_key = ndb.Key(urlsafe=request.websafekey)
     del data['websafekey']
     s_id = Submission.allocate_ids(size=1, parent=q_key)[0]
     s_key = ndb.Key(Submission, s_id, parent=q_key)
     data['key'] = s_key
     data['user'] = user
     data['subskey'] = s_key.urlsafe()
     Submission(**data).put()
     return SubmissionForm(code=data['code'],
                           score=data['score'],
                           language=data['language'])
    def getConferencesCreated(self, request):
        """Return conferences created by user."""
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # make profile key
        p_key = ndb.Key(Profile, getUserId(user))
        # create ancestor query for this user
        conferences = Conference.query(ancestor=p_key)
        # get the user profile and display name
        prof = p_key.get()
        displayName = getattr(prof, 'displayName')
        # return set of ConferenceForm objects per Conference
        return ConferenceForms(items=[
            self._copyConferenceToForm(conf, displayName)
            for conf in conferences
        ])
    def getConferencesCreated(self, request):
        """Return conferences created by user."""
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # create ancestor query for all key matches for this user
        confs = Conference.query(ancestor=ndb.Key(Profile, user_id))
        prof = ndb.Key(Profile, user_id).get()

        if not prof:
            prof = self._getProfileFromUser()

        # return set of ConferenceForm objects per Conference
        return ConferenceForms(
            items=[self._copyConferenceToForm(conf, getattr(prof, 'displayName')) for conf in confs]
        )
Example #43
0
    def filterPlayground(self, request):
        """Return conferences created by user."""
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

#delete everything in users wishlist
        prof = self._getProfileFromUser()  # get user Profile
        #print "******* %s" ,prof.wishListSessionKeys
        prof.wishListSessionKeys[:] = []

        conferences = Conference.query()
        conferences = conferences.filter(Conference.city == "London")

        # return set of ConferenceForm objects per Conference
        return ConferenceForms(items=[
            self._copyConferenceToForm(conf, "") for conf in conferences
        ])
Example #44
0
 def show(self, message):
     user = endpoints.get_current_user()
     if user is None:
         raise endpoints.UnauthorizedException()
     if message.whom_show == '' or message.whom_show is None:
         message.whom_show = user.email()
     #message.tmail_this = message.tmail
     message.tmail_this = user.email()
     if message.group_url is None:  #add g_auth and multiple groups
         e = Group.query(Group.name == message.group_name).fetch()
         #print 'aaaaaaaaa', e, message.group_name
         if len(e) != 1:
             raise Exception('Groups with this name more or less then 1')
         message.group_url = e[0].key.urlsafe()
     #print '##############', message.url, message.whom_show
     #ADD message.frame, message.top_rateRate(url=obj.key.id(), name=obj.name, avatar=obj.avatar,
     #		   kind=obj.is_group, rating=str(getattr(obj, url)[-1]))
     #    answer.rate_obj.append(rate_bl)
     return show.show_group(self, message)
  def play_song(self,request):
      """Set Play song Flag"""
      current_user = endpoints.get_current_user()
      user_query = User.query(User.user_id == current_user.user_id())
      user = user_query.get()
      song_query = Song.query(ndb.AND(Song.track_id == request.track_id,Song.party_key == user.party_key))

      if song_query.get():
          song = song_query.get()
          if not song.played:
              song.played = True;
              song.put()
          #delete all the activities for that song in that party
          activity_query = Activity.query(Activity.song == song.key,Activity.party_key == user.party_key).fetch(keys_only=True)
          ndb.delete_multi(activity_query)

          return add_response(response = 'Song has been updated')
      else:
          return add_response(response = 'song not found')
    def getSessionsInWishlist(self, request):
        """Return the sessions in the user's wishlist.
        """
        # make sure user is authed
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # get the user's profile
        profile = self._getProfileFromUser()
        sessionForms = []
        for websafe_key in profile.wishlistSessionKeys:
            key = ndb.Key(urlsafe=websafe_key)
            session = key.get()
            if session:
                sessionForms.append(self._copySessionToForm(session))

        # return set of ConferenceForm objects per Conference
        return SessionForms(items=sessionForms)
Example #47
0
def get_user_email():
    """Retrieves the currently logged in user email.

  Returns:
    A string of the email address of the current user.

  Raises:
    UserNotFound: Raised if a user is not currently logged in.
  """

    try:
        current_user = endpoints.get_current_user() or users.get_current_user()
    except endpoints.InvalidGetUserCall:
        current_user = users.get_current_user()

    if current_user:

        return current_user.email()
    raise UserNotFound('get_user_email failed: No user account detected.')
Example #48
0
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""
        ## TODO
        ## make sure user is authed
        ## uncomment the following lines:
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        profile = None
        if not profile:
            profile = Profile(
                key = None,
                displayName = user.nickname(),
                mainEmail= user.email(),
                teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED),
            )
            #TODO

        return profile      # return Profile
Example #49
0
    def deleteSessionInWishlist(self, request):
        """Delete a session from the user's wishlist."""
        wssk = request.websafeSessionKey
        retval = False

        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # Get the user profile and remove the session if it's there
        user_id = getUserId(user)
        profile = ndb.Key(Profile, user_id).get()
        if wssk in profile.sessionWishlist:
            profile.sessionWishlist.remove(wssk)
            retval = True

        # Update the profile
        profile.put()
        return BooleanMessage(data=retval)
Example #50
0
    def addSessionToWishlist(self, request):
        """Add a sessions to a profiles wish to attend wishlist."""
        retval = False
        wssk = request.websafeSessionKey
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        # Get the session
        session = ndb.Key(urlsafe=wssk).get()
        if not session:
            raise endpoints.NotFoundException(
                'No session found with key: {}'.format(wssk))

        # Get the profile
        user_id = getUserId(user)
        profile = ndb.Key(Profile, user_id).get()

        # Check that it's not already on the wishlist
        if wssk in profile.sessionWishlist:
            raise ConflictException(
                "This session is already in your wishlist.")

        # Check that the session is in a conference the user is registered in
        if profile.conferenceKeysToAttend:
            seshs = [
                Session.query(ancestor=ndb.Key(urlsafe=p_key))
                for p_key in profile.conferenceKeysToAttend
            ]
            if not seshs:
                raise endpoints.ForbiddenException(
                    "You are not attending the conference that this session is in."
                )
            profile.sessionWishlist.append(wssk)
            profile.put()
            retval = True
        else:
            raise endpoints.ForbiddenException(
                "You are not attending the conference that this session is in."
            )

        return BooleanMessage(data=retval)
    def _createSpeakerObject(self, request):
        """
        Creates a Speaker entity in datastore based on the information provided
        by client.
        Sends a confirmation email after adding the new Speaker
        """
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException("Speaker 'name' \
                field required")

        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        del data['websafeSpeakerKey']

        # create Speaker & return (modified) SpeakerForm
        speaker_key = Speaker(**data).put()
        taskqueue.add(params={
            'email': user.email(),
            'speakerInfo': repr(request)
        },
                      url='/tasks/send_speaker_confirmation_email')
        # Return data as SpeakerForm
        speakerform = SpeakerForm()

        for field in speakerform.all_fields():
            if data.has_key(field.name):
                setattr(speakerform, field.name, data[field.name])
            # Checks if the field is websafeSpeakerKey, then converts it into
            # urlsafe key
            elif field.name == "websafeSpeakerKey":
                setattr(speakerform, field.name, speaker_key.urlsafe())

        speakerform.check_initialized()
        return speakerform
Example #52
0
    def getUser(self, request):
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
            return getUserMSGout(msg='Not Logged In!',
                                 displayname='',
                                 email='',
                                 uv='',
                                 current_game_id=0,
                                 games_played=0,
                                 games_won=0,
                                 games_lost=0,
                                 created='',
                                 modified='')

        email = user.email()
        user2 = Users.query(Users.email == email).get()

        if user2:
            created = str(user2.created)
            modified = str(user2.modified)
            return getUserMSGout(msg='User Acount Info.',
                                 displayname=user2.displayname,
                                 email=user2.email,
                                 uv=user2.uv,
                                 current_game_id=user2.current_game_id,
                                 games_played=user2.games_played,
                                 games_won=user2.games_won,
                                 games_lost=user2.games_lost,
                                 created=created,
                                 modified=modified)
        else:
            return getUserMSGout(msg='Account Does Not Exists.',
                                 displayname='',
                                 email='',
                                 uv='',
                                 current_game_id=0,
                                 games_played=0,
                                 games_won=0,
                                 games_lost=0,
                                 created='',
                                 modified='')
Example #53
0
    def get(self, request):

        '''Authorization'''
        if config.VALID_AUTHENTICATION == True:
            user = endpoints.get_current_user()
            if user is None:        
                raise endpoints.UnauthorizedException

        try:                       
            from services import RouteService
            from models import Route

            #Pagination
            page = request.page
            page_size = request.page_size
  
             #Filters
            filters = {}
            filters["active"] = request.active
            filters["route_key"] = request.route_key
            filters["vehicle_key"] = request.vehicle_key
            filters["company_key"] = request.company_key
            filters["driver_key"] = request.driver_key
            filters["start_date"] = request.start_date
            filters["end_date"] = request.end_date
            filters["status"] = request.status

            entities, total = RouteService.RouteInstance.get_all(page, page_size, filters)

            response = {
                "total":  total,
                "records":
                  json.loads(json.dumps([entity.to_dict() for entity in entities]))
            }            

            return Response(
                status=SUCCESS,
                response=response
            )    
        except Exception, e:
            errors = str(e)
            return Response(status=FAIL, response=errors)
Example #54
0
    def _createSpeakerObject(self, request):
        """Create speaker object"""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException(
                "Speaker 'name' field required")

        # copy SpeakerForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }

        s_key = Speaker(**data).put()

        return request
Example #55
0
    def getSessionsByStartTimeAndDuration(self, request):
        """Get a Conference Session by time and duration"""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        qs = Session.query()

        data = {f.name: getattr(request, f.name) for f in request.all_fields()}
        # Filters the query by all sessions with the startTime and duration equal
        # to the values of the requested fields.
        time = data['startTime'].split(':')
        # Transform the string to the float value
        startTime = float(time[0]) + (float(time[1])) / 60.0
        qs = qs.filter(Session.startTime == startTime)
        qs = qs.filter(Session.duration == data['duration'])

        return SessionForms(
            items=[self._copySessionToForm(sess) for sess in qs]
        )
    def _getProfileFromUser(self):
        """Return user Profile from datastore, creating new one if non-existent."""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        user_id = getUserId(user)
        p_key = ndb.Key(Profile, user_id)
        profile = p_key.get()

        if not profile:
            profile = Profile(
                key=p_key,
                displayName=user.nickname(),
                mainEmail=user.email(),
                teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
            )
            profile.put()

        return profile      # return Profile
Example #57
0
    def pokemon_insert(self, pokemon):
        """ POKEMON-ADD: add a pokemon under the user's account """
        if pokemon.from_datastore:
            pokemon_with_parent = pokemon
            pokemon_with_parent.put()
        else:
            user = endpoints.get_current_user()
            pokemon_with_parent = Pokemon(parent=get_parent_key(user),
                                          given_name=pokemon.given_name,
                                          species_name=pokemon.species_name,
                                          species_id=pokemon.species_id,
                                          level=pokemon.level)

            this_key = pokemon_with_parent.put()
            this_instance = this_key.get()
            this_instance.pokemon_key = this_key.urlsafe()
            this_instance.put()
            pokemon_with_parent = this_instance

        return pokemon_with_parent
Example #58
0
    def GetShortSessions(self, request):
        """Get list of short (one hour or less) sessions in the conferences that the user is registered to. """
        
        # Get user
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        prof = self._getProfileFromUser() # get user Profile
        
        sessions = []
        for confKey in prof.conferenceKeysToAttend:
            q = Session.query(ancestor=ndb.Key(Conference, confKey))
            formatted_query = ndb.query.FilterNode("duration", "<=", 60)
            confsessions = q.filter(formatted_query).fetch()
            if confsessions is not None:
                sessions.extend(confsessions)

        # return set of SessionForm objects per Session
        return SessionForms(items=[self._copySessionToForm(session) for session in sessions])
    def deleteSessionInWishlist(self, request):
        """remove a session from users' wishlist."""
        #load currrent user
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization is requied')
        userProfile = self._getProfileFromUser()

        currentWishlist = userProfile.sessionsWishlist

        sessionToRemove = request.websafeSessionKey

        message = StringMessage(data="session does not exist")
        #if session is in wish list, remove it
        if sessionToRemove in userProfile.sessionsWishlist:
            userProfile.sessionsWishlist.remove(sessionToRemove)
            userProfile.put()
            message = StringMessage(data="Session removed")

        return message
    def getConferenceSessionsByType(self, request):
        """Return conferences created by user."""
        # make sure user is Authorized
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()

        # make Conference key
        parent_key = ndb.Key(Conference, conf.key.id())

        # Query all the Sessions in this Conference
        Sessions = Session.query(ancestor=parent_key)

        Sessions = Sessions.filter(
            Session.typeOfSession == request.typeOfSession)

        return SessionForms(
            items=[self._copySessionToForm(sess) for sess in Sessions])