def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" ## TODO 2 ## step 1: make sure user is authed ## uncomment the following lines: user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # get Profile from datastore print "***********" print user logging.info('**1**** %s',user) user_id = getUserId(user) print "**********" print user_id logging.info('**2**** %s',user_id) p_key = ndb.Key(Profile, user_id) print "*********" print p_key logging.info('***3**** %s',p_key) profile = p_key.get() print "*********" print profile logging.info('****4**** %s',profile) ## step 2: create a new Profile from logged in user data ## you can use user.nickname() to get displayName ## and user.email() to get mainEmail if not profile: profile = Profile( # userId = None, key = p_key, displayName = user.nickname, mainEmail= user.email, teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED), ) profile.put() return profile # return Profile
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'))
def _getAuthorFromUser(self): """Return user Author from datastore, creating new one if non-existent.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # get Author from datastore or create new Author if not there user_id = getUserId(user) a_key = ndb.Key(Author, user_id) author = a_key.get() # create new Author if not there if not author: author = Author( key=a_key, authorID=str(Author.allocate_ids(size=1)[0]), displayName=user.nickname(), mainEmail=user.email(), ) author.put() return author
def create_user(self, request): """ create a new user """ if User.query(User.name == request.user_name).get(): raise endpoints.ConflictException( 'A User with that name already exists!') # returns a User, otherwise it returns None. g_user = endpoints.get_current_user() if not g_user: raise endpoints.UnauthorizedException('Authorization required') # get email from user user_id = getUserId(g_user) # create ndb key of kind User from user email u_key = ndb.Key(User, user_id) user = User(name=request.user_name, email=request.email, key=u_key) user.put() return StringMessage( message='User {} created!'.format(request.user_name))
def _getInfoFromUser(self): """Return user Profile from datastore, creating new one if non-existent. """ # make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # get User from datastore user_email = user.email() current_user = User.query(User.email == user_email).get() # create new User if not there if not current_user: current_user = User( name=user.nickname(), email=user.email(), ) current_user.put() return current_user # return User
def addSessionToWishlist(self, request): """Add Session to Wishlist""" # preload necessary data items user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) # get Session object from request; bail if not found try: sess = ndb.Key(urlsafe=request.websafeSessionKey) kind = sess.kind() sess = sess.get() # check if the key is a Session Kind if not sess or kind != 'Session': raise endpoints.NotFoundException( 'No session found with key: %s' % request.websafeSessionKey) except Exception, e: raise endpoints.NotFoundException( 'No session found with key: %s' % request.websafeSessionKey)
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" ## Make sure user is authed ## uncomment the following lines: user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') profile = None ## Create a new Profile from logged in user data ## you can use user.nickname() to get displayName ## and user.email() to get mainEmail if not profile: profile = Profile( userId=None, key=None, displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED), ) return profile # return Profile
def _updateSpeakerObject(self, request): user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # update existing conference speaker = ndb.Key(urlsafe=request.websafeSpeakerKey).get() # check that conference exists if not speaker: raise endpoints.NotFoundException('No speaker found with key: %s' % request.websafeSpeakerKey) # Not getting all the fields, so don't create a new object; just # copy relevant fields from SpeakerForm to Speaker object for field in request.all_fields(): data = getattr(request, field.name) # only copy fields where we get data if data is not None: setattr(speaker, field.name, data) speaker.put() return self._copySpeakerToForm(speaker)
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') # get Profile from datastore user_id = getUserId(user) p_key = ndb.Key(Profile, user_id) profile = p_key.get() # create new Profile if not there 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
def cancel_game(self, request): """Cancel and delete the current game state.""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if game: # game exits # check if user is a player in this game if request.user_name not in (game.player1.get().name, game.player2.get().name): raise endpoints.UnauthorizedException( 'You are not a player of this game') if game.game_over: user = game.whose_turn.get() message = """This game has ended. It was won by {user_name} and cannot be cancelled""".format(user_name=user.name) return StringMessage(message=message) else: game.key.delete() return StringMessage(message='Game cancelled and deleted.') else: raise endpoints.NotFoundException('No game exists with that key!')
def deleteSessionInWishList(self, request): """Remove requested wishlist by user.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) wishlists = WishList.query(ancestor=ndb.Key(Profile, user_id)) ws = wishlists.filter(WishList.session_key == request.session_key) wrpt = WishListReport() if ws.count(): for w in ws: w.key.delete() setattr(wrpt, 'rpt', 'OK') else: setattr(wrpt, 'rpt', 'Not Found') wrpt.check_initialized() return wrpt
def grant_user_access_from_code(redirect_url, **kwargs): """ Untested code. """ code = kwargs['code'] login = FacebookLogin(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET, redirect_url) try: login.retrieve_access_token(code) except: raise endpoints.UnauthorizedException( "Unorthorised access to Facebook.") profile = login.get_profile() account = models.FacebookAccount.get_by_facebook_id(profile['id']) if account is None: account = _create_new_user(profile, login.access_token) return account
def attachments_get(self, request): """Retrieve metainfo for a single attachments 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: return AttachmentResponse(id=att.id, contentType=att.contentType, contentUrl=att.contentUrl, isProcessingContent=att.isProcessingContent) raise endpoints.NotFoundException("Attachment not found.")
def invite_to_group(self, message): user = endpoints.get_current_user() if user is None: raise endpoints.UnauthorizedException() entity = ndb.Key(Group, message.group_name).get() #print '$', entity.invite for obj, r in zip(*split_message(message.child_object, message.role)): #print 'sddd' #print 'sddd2', entity.invite, entity.ban, entity.joined if obj not in entity.invite or obj not in entity.ban or obj not in entity.joined: if obj in entity.ask_join: self.put_object_to_group( PutObjectTo(child_object=message.child_object, group_name=message.group_name, role=r)) else: entity.invite[obj] = r #print '$', entity.invite entity.put() return Answer()
def _updateSessionWishlist(self, request, add=True): """Add or remove session from user wishlist""" # make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') retval = None # value to return indicating success prof = self._getProfileFromUser() # get user Profile # check if session exists given key wssk = request.websafeSessionKey sess = ndb.Key(urlsafe=wssk).get() if not sess: raise endpoints.NotFoundException( 'No sesssion found with key: %s ' % wssk) # check if this is to add or remove if add: # check if user already added session if wssk in prof.sessionKeysInWishlist: raise ConflictException( "You have already added this session to your wishlist.") # add session to user profile prof.sessionKeysInWishlist.append(wssk) retval = True # session found and added prof.put() # remove session from user wishlist else: # check if session is in wishlist if wssk in prof.sessionKeysInWishlist: # remove the session from user wishlist prof.sessionKeysInWishlist.remove(wssk) retval = True # session found and removed prof.put() else: retval = False # session not in wishlist; not removed # no change. do not put. return BooleanMessage(data=retval)
def getSessionsInWishlist(self, request): """Get list of Sessions that user wish to attend 1)return a wishlist of sessions for a specific conference if with key = {websafeConferenceKey} 2) return a wishlist of all sessions over all conferences use added to a whishlist if {websafeConferenceKey} is None """ # get user Profile user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') prof = self._getProfileFromUser() # show all sessions for all conferences to attend session_wishlist_keys = [ ndb.Key(urlsafe=session_key) for session_key in prof.sessionKeysInWishlist ] sessions_wishlist = ndb.get_multi(session_wishlist_keys) # if user wants to see selected session for a specific conference # use {websafeConferenceKey} to select them if request.websafeConferenceKey is not None: output = [] conference_key = ndb.Key(urlsafe=request.websafeConferenceKey) for item in session_wishlist_keys: if item.parent() == conference_key: print("item.parent: ", item.parent()) output.append(item) sessions_wishlist = ndb.get_multi(output) return SessionForms(items=[ self._copySessionToForm(sess) for sess in sessions_wishlist ]) # return set of SessionForm objects return SessionForms(items=[ self._copySessionToForm(sess) for sess in sessions_wishlist ])
def getCurrentGame(self, request): user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') return newGameMSGout(msg='Not Logged In!', uv='', game_id=0, hint_one='', hint_two='', hint_three='') email = user.email() user2 = Users.query(Users.email == email).get() user_id = user2.key.id() if not user2: return newGameMSGout(msg='Account Does Not Exist!', uv='', game_id=0, hint_one='', hint_two='', hint_three='') checkGame = Games \ .query(ndb.AND(Games.user_id == user_id, Games.active == True)).get() if checkGame: game_id = checkGame.key.id() return newGameMSGout(msg='Current Game.', uv=checkGame.uv, game_id=game_id, hint_one=checkGame.hint_one, hint_two=checkGame.hint_two, hint_three=checkGame.hint_three) else: return newGameMSGout(msg='No Current Game.', uv='', game_id=0, hint_one='', hint_two='', hint_three='')
def getWishlistBySpeaker(self, request): """Get wishlist by speaker.""" # check auth user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # get userId user_id = getUserId(user) # query session, filter by speaker q = Session.query().filter(Session.speaker == request.speaker) # query wishlist, filter by userId p = Wishlist.query().filter(Wishlist.userId == user_id) a = [] for s in q: for w in p: if s.key == w.sessionKey: a.append(w) return WishlistForms( items=[self._copyWishlistToForm(wish) for wish in a])
def get_created(self, request): """ Return Conferences created by the requesting User :param request: Void RPC Message :return: ConferenceForms containing user-created ConferenceForm's """ if not isinstance(request, message_types.VoidMessage): raise endpoints.BadRequestException() # make sure user is auth'd user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = get_user_id(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() # return set of ConferenceForm objects per Conference return ConferenceForms( items=[conf.to_form(getattr(prof, 'displayName')) for conf in confs] )
def getSessionsAfter7NoWorkshop(self, request): """Return sessions after 7 pm that are not workshops""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization is requied') sevenPM = '19:00:00' timeToFilter = datetime.strptime(sevenPM, '%H:%M:%S').time() sessions = Session.query(Session.startTime < timeToFilter) #create a list to store properties to complete 2nd part of inequality filter filterSessions = [] #loop over items that are not workshops for session in sessions: if session.typeOfSession != "WORKSHOP": filterSessions.append(session) return SessionForms(items=[ self._copySessionToForm(session) for session in filterSessions ])
def getSessionsInWishlist(self, request): """Get a list of sessions that a user has registered for.""" user = endpoints.get_current_user() #check if logged in if not user: raise endpoints.UnauthorizedException('Authorization required') #get profile from user prof = self._getProfileFromUser() #grab session keys that a user has registered for sess_keys = [ ndb.Key(urlsafe=wsck) for wsck in prof.sessionsKeysToAttend ] #turn keys into instances sessions = ndb.get_multi(sess_keys) #return all sessions on the user's wishlist return SessionForms( items=[self._copySessionToForm(s) for s in sessions])
def compute_nero(self, message): user = endpoints.get_current_user() if user is None: raise endpoints.UnauthorizedException() #role=ObjectToGroup.query(ObjectToGroup.key_value==user.email(), ObjectToGroup.group_name==message.group_name).get().role # itr?? entity = ndb.Key(ObjectToGroup, message.valued_object, ObjectToGroup, message.group_name).get() #print entity itr = getattr(entity, message.st_name + '__I') evs = NeroStat.query( ancestor=ndb.Key(NeroStat, str(itr), NeroStat, message.st_name + '__A', NeroStat, entity.key.urlsafe())).fetch() #print " 1", evs #T = message.val w = [] A = [] mult = [] Q = {} ref_profile = [] for ref in evs: #print ref.key, ref.key.id(),w ref_profile.append( ndb.Key(ObjectToGroup, ref.key.id(), ObjectToGroup, message.group_name).get()) A.append(ref.val) w.append(getattr(ref_profile[-1], message.st_name + '__W')) #print getattr(ref_profile[-1], message.st_name+'__W') #print '----', A, w, message.teacher_val data = compute_nero(A, w, message.teacher_val) for i, users in enumerate(ref_profile): setattr(users, message.st_name + '__W', data[2][i]) #print '==', users, data[2] users.put() setattr(entity, message.st_name, '(T:' + str(message.teacher_val) + ' m:' + str(data[1]) + ')') entity.put() return Answer()
def FindSessionByDatewithStartTimeRange(self, request): """Find Sessions By Date with Start Time Range""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # user_id = getUserId(user) sessions = Session.query() theStartTime = datetime.strptime( request.startTimeRangeBeginning, "%H:%M").time() theEndTime = datetime.strptime( request.startTimeRangeEnding, "%H:%M").time() theDate = datetime.strptime(request.conferenceDate, "%Y-%m-%d").date() sessions = sessions.filter(Session.startTime >= theStartTime) sessions = sessions.filter(Session.startTime <= theEndTime) sessions = sessions.filter(Session.date == theDate) return SessionForms( items=[self._copySessionToForm(session) for session in sessions] )
def requestResponse(self, request): user = self.get_user_from_token(request.token) if not user: raise endpoints.UnauthorizedException('UNAUTHORIZED') key = ndb.Key(Account, int(request.uid)) friend = key.get() if friend is None: raise endpoints.NotFoundException('FRIEND_NOT_FOUND') user.requestedFriends.remove(key) friend.requestingFriends.remove(user.key) if request.action == 'accept': user.friends.append(key) friend.friends.append(user.key) user.put() friend.put() return message_types.VoidMessage()
def getSessionsInWishlist(self, request): """Get the sessions that are in the users wishlist, for the given conference key.""" wsck = request.websafeConferenceKey user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # Get the profile user_id = getUserId(user) profile = ndb.Key(Profile, user_id).get() sessions = [ ndb.Key(urlsafe=wssk).get() for wssk in profile.sessionWishlist ] # If the session's parent key doesn't match the conference key # remove it from the list of sessions to display. for session in sessions: if session.key.parent().urlsafe() != wsck: sessions.remove(session) return SessionForms( sessions=[self._copySessionToForm(sesh) for sesh in sessions])
def attachments_list(self, request): """Retrieve attachments 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("Card not found.") attachments = [] if card.attachments is not None: for att in card.attachments: attachments.append(AttachmentResponse(id=att.id, contentType=att.contentType, contentUrl=att.contentUrl, isProcessingContent=att.isProcessingContent)) return AttachmentList(items=attachments)
def insert_folder(cls, user, folder_name, kind): try: credentials = user.google_credentials http = credentials.authorize(httplib2.Http(memcache)) service = build('drive', 'v2', http=http) organization = user.organization.get() # prepare params to insert folder_params = { 'title': folder_name, 'mimeType': 'application/vnd.google-apps.folder' } # get the accounts_folder or contacts_folder or .. parent_folder = eval('organization.' + FOLDERS[kind]) if parent_folder: folder_params['parents'] = [{'id': parent_folder}] # execute files.insert and get resource_id created_folder = service.files().insert(body=folder_params, fields='id').execute() except: raise endpoints.UnauthorizedException(cls.INVALID_GRANT) return created_folder
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") # create the profile key p_key = ndb.Key(Profile, getUserId(user, id_type="oauth")) # 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 update_user(self, request): if endpoints.get_current_user() is None: raise endpoints.UnauthorizedException('Authorization required') user_key_id = request.id user_key = ndb.Key(urlsafe=str(user_key_id)) userDb = user_key.get() user = None if userDb is not None: userDb.user_id = str(request.user_id) userDb.strava_id = str(request.strava_id) userDb.strava_token = str(request.strava_token) userDb.put() user = User(user_id=userDb.user_id, email=userDb.email, key=str(userDb.key.id()), strava_id=userDb.strava_id, strava_token=userDb.strava_token) else: message = 'No user with key "%s" exists.' % str(user_key_id) raise endpoints.NotFoundException(message) return user
def _createSessionObject(self, request): """Create or update Session object, returning SessionForm/request.""" user_id = check_auth() organizer = Conference.query( Conference.organizerUserId == request.organizer_id) if not organizer: raise endpoints.UnauthorizedException( 'Must be conference organizer to create session') if not request.title: raise endpoints.BadRequestException( "Session 'title' field required") data = { field.name: getattr(request, field.name) for field in request.all_fields() } data['start_time'] = datetime.strptime(data['start_time'], '%H:%M').time() p_key = ndb.Key(Profile, user_id) s_id = Session.allocate_ids(size=1, parent=p_key)[0] s_key = ndb.Key(Session, s_id, parent=p_key) data['key'] = s_key data['organizer_id'] = request.organizer_id = user_id data['speaker_id'] = ndb.Key(Speaker, request.speaker_id) data['speaker_name'] = ndb.Key(Speaker, request.speaker_id).get().name Session(**data).put() key = 'speaker_id' if self._checkFeaturedSpeaker(request.conference_key, data[key]): taskqueue.add(params={ 'speaker_id': request.speaker_id, 'conf': request.conference_key }, url='/tasks/set_featured_speaker') return request