def post(self): jsonOutput = {'result': False} user = self.current_user linkType = self.request.get('linkType') sourcesURLs=json.loads(self.request.get('sourcesURLs')) sourcesNames=json.loads(self.request.get('sourcesNames')) parentNewScore = None if user: try: parentPointURL = self.request.get('pointUrl') oldPoint, oldPointRoot = Point.getCurrentByUrl(parentPointURL) if oldPointRoot: newPoint, newLinkPoint = Point.addSupportingPoint( oldPointRoot=oldPointRoot, title=self.request.get('title'), content=self.request.get('content'), summaryText=self.request.get('plainText'), user=user, # backlink=oldPoint.key.parent(), linkType = linkType, imageURL=self.request.get('imageURL'), imageAuthor=self.request.get('imageAuthor'), imageDescription=self.request.get('imageDescription'), sourcesURLs=sourcesURLs, sourcesNames=sourcesNames ) # TODO: Gene: Probably have a more efficient retrieval here no? oldPoint, oldPointRoot = Point.getCurrentByUrl(parentPointURL) if oldPoint: parentNewScore = oldPoint.pointValue() else: raise WhysaurusException('Point with URL %s not found' % parentPointURL) except WhysaurusException as e: jsonOutput = { 'result': False, 'errMessage': str(e) } else: ReportEvent.queueEventRecord(user.key.urlsafe(), newLinkPoint.key.urlsafe(), newPoint.key.urlsafe(), "Create Point") newLinkPointHTML = self.template_render('linkPoint.html', { 'point': newLinkPoint, 'linkType': linkType }) jsonOutput = { 'result': True, 'version': newPoint.version, 'author': newPoint.authorName, 'dateEdited': newPoint.PSTdateEdited.strftime('%b. %d, %Y, %I:%M %p'), 'numLinkPoints': newPoint.linkCount(linkType), 'newLinkPoint': newLinkPointHTML, 'authorURL': self.current_user.url, 'parentNewScore': parentNewScore } self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(json.dumps(jsonOutput)) else: self.response.out.write('Need to be logged in')
def post(self): user = self.current_user if user: resultJSON = json.dumps({"result": False}) oldPoint, oldPointRoot = Point.getCurrentByUrl(self.request.get("urlToEdit")) sourcesURLs = json.loads(self.request.get("sourcesURLs")) if self.request.get("sourcesURLs") else None sourcesNames = json.loads(self.request.get("sourcesNames")) if self.request.get("sourcesNames") else None sourcesToRemove = ( json.loads(self.request.get("sourcesToRemove")) if self.request.get("sourcesToRemove") else None ) if oldPoint == None: resultJSON = json.dumps( {"result": False, "error": "Unable to edit point. Please refresh the page and try again."} ) elif user.isLimited: resultJSON = json.dumps({"result": False, "error": "This account cannot edit points."}) else: sources = Source.constructFromArrays(sourcesURLs, sourcesNames, oldPoint.key) newVersion = oldPoint.update( newTitle=self.request.get("title"), newContent=self.request.get("content"), newSummaryText=self.request.get("plainText"), user=self.current_user, imageURL=self.request.get("imageURL"), imageAuthor=self.request.get("imageAuthor"), imageDescription=self.request.get("imageDescription"), sourcesToAdd=sources, sourceKeysToRemove=sourcesToRemove, ) if newVersion: sources = newVersion.getSources() sourcesHTML = self.template_render("sources.html", {"sources": sources}) resultJSON = json.dumps( { "result": True, "version": newVersion.version, "author": newVersion.authorName, "authorURL": self.current_user.url, "dateEdited": newVersion.PSTdateEdited.strftime("%b. %d, %Y, %I:%M %p"), "pointURL": newVersion.url, "imageURL": newVersion.imageURL, "imageAuthor": newVersion.imageAuthor, "imageDescription": newVersion.imageDescription, "sourcesHTML": sourcesHTML, } ) ReportEvent.queueEventRecord(user.key.urlsafe(), newVersion.key.urlsafe(), None, "Edit Point") else: # This is the only way newVersion will fail resultJSON = json.dumps({"result": False, "error": "You appear not to be logged in."}) self.response.headers["Content-Type"] = "application/json; charset=utf-8" self.response.out.write(resultJSON)
def login(self): # Update last login time self.lastLogin = datetime.datetime.now() now = datetime.datetime.now() # Create And Store Token if not self.token or self.tokenExpires < now: self.createChannel() self.put() ReportEvent.queueEventRecord(self.key.urlsafe(), None, None, "Login") return
def post(self): user = self.current_user if user: resultJSON = json.dumps({'result': False}) oldPoint, oldPointRoot = Point.getCurrentByUrl(self.request.get('urlToEdit')) sourcesURLs=json.loads(self.request.get('sourcesURLs')) \ if self.request.get('sourcesURLs') else None sourcesNames=json.loads(self.request.get('sourcesNames')) \ if self.request.get('sourcesNames') else None sourcesToRemove=json.loads(self.request.get('sourcesToRemove')) \ if self.request.get('sourcesToRemove') else None if oldPoint == None: resultJSON = json.dumps({'result': False, 'error': 'Unable to edit point. Please refresh the page and try again.'}) elif user.isLimited: resultJSON = json.dumps({'result': False, 'error': 'This account cannot edit points.'}) else: sources = Source.constructFromArrays(sourcesURLs, sourcesNames, oldPoint.key) newVersion = oldPoint.update( newTitle=self.request.get('title'), newContent=self.request.get('content'), newSummaryText=self.request.get('plainText'), user=self.current_user, imageURL=self.request.get('imageURL'), imageAuthor=self.request.get('imageAuthor'), imageDescription=self.request.get('imageDescription'), sourcesToAdd=sources, sourceKeysToRemove= sourcesToRemove ) if newVersion: sources = newVersion.getSources() sourcesHTML = self.template_render('sources.html', {'sources':sources}) resultJSON = json.dumps({ 'result': True, 'version': newVersion.version, 'author': newVersion.authorName, 'authorURL': self.current_user.url, 'dateEdited': newVersion.PSTdateEdited.strftime('%b. %d, %Y, %I:%M %p'), 'pointURL':newVersion.url, 'imageURL': newVersion.imageURL, 'imageAuthor': newVersion.imageAuthor, 'imageDescription': newVersion.imageDescription, 'sourcesHTML': sourcesHTML }) ReportEvent.queueEventRecord(user.key.urlsafe(), newVersion.key.urlsafe(), None, "Edit Point") else: # This is the only way newVersion will fail resultJSON = json.dumps({'result': False, 'error': 'You appear not to be logged in.'}) self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)
def post(self): jsonOutput = {'result': False} user = self.current_user linkType = self.request.get('linkType') sourcesURLs=json.loads(self.request.get('sourcesURLs')) sourcesNames=json.loads(self.request.get('sourcesNames')) if user: try: parentPointURL = self.request.get('pointUrl') oldPoint, oldPointRoot = Point.getCurrentByUrl(parentPointURL) if oldPointRoot: newPoint, newLinkPoint = Point.addSupportingPoint( oldPointRoot=oldPointRoot, title=self.request.get('title'), content=self.request.get('content'), summaryText=self.request.get('plainText'), user=user, # backlink=oldPoint.key.parent(), linkType = linkType, imageURL=self.request.get('imageURL'), imageAuthor=self.request.get('imageAuthor'), imageDescription=self.request.get('imageDescription'), sourcesURLs=sourcesURLs, sourcesNames=sourcesNames ) else: raise WhysaurusException('Point with URL %s not found' % parentPointURL) except WhysaurusException as e: jsonOutput = { 'result': False, 'errMessage': str(e) } else: ReportEvent.queueEventRecord(user.key.urlsafe(), newLinkPoint.key.urlsafe(), newPoint.key.urlsafe(), "Create Point") newLinkPointHTML = self.template_render('linkPoint.html', { 'point': newLinkPoint, 'linkType': linkType }) jsonOutput = { 'result': True, 'version': newPoint.version, 'author': newPoint.authorName, 'dateEdited': newPoint.PSTdateEdited.strftime('%b. %d, %Y, %I:%M %p'), 'numLinkPoints': newPoint.linkCount(linkType), 'newLinkPoint': newLinkPointHTML, 'authorURL': self.current_user.url } self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(json.dumps(jsonOutput)) else: self.response.out.write('Need to be logged in')
def signup(cls, handler, email, name, password, website, areas, profession, bio): auth_id = '%s: %s' % ('name', name) url = WhysaurusUser.constructURL(name) gaid = WhysaurusUser.generateUniqueUserGaid(True) unique_properties = ['email', 'url', 'name'] if email else ['url', 'name'] if password is None: raise WhysaurusException('Unable to create user. No password supplied.') privateAreas = [] existingPrivateArea = handler.session.get('currentArea') if existingPrivateArea: privateAreas = [existingPrivateArea] result, creationData = WhysaurusUser.create_user(auth_id, unique_properties, url=url, email=email, name=name, password_raw=password, gaId=gaid, websiteURL=website, areasOfExpertise=areas, currentProfession=profession, bio=bio, verified=False, privateAreas=privateAreas) if not result: #user_data is a tuple if 'name' in creationData: raise WhysaurusException('Unable to create user because the username %s is already in use' % name) elif 'email' in creationData: raise WhysaurusException('Unable to create user because the email %s is already in use' % email) else: raise WhysaurusException('Unable to create user for email %s because of \ duplicate keys %s' % (auth_id, user_data[1])) else: user = creationData if email: user_id = user.get_id() user.auth_ids.append('%s: %s' % ('email', email)) user.put() WhysaurusUser.send_verification_email(handler, user_id, email, "signing up for Whysaurus") else: logging.info('Created a username only user. Name: %s.' % name) if existingPrivateArea: areaUser = AreaUser(userKey=user.key.urlsafe(), privateArea=existingPrivateArea) areaUser.putUnique() ReportEvent.queueEventRecord(user.key.urlsafe(), None, None, "New User") user.addToSearchIndex() return user # SUCCESS
def login(self): now = datetime.datetime.now() if self.lastLogin: daysSinceLastLogin = (now - self.lastLogin).days self.loginAvgIntervalDays = (daysSinceLastLogin + self.loginAvgIntervalDays * self.loginCount)/(self.loginCount + 1) self.loginCount += 1 # Update last login time self.lastLogin = now # Create And Store Token # if not self.token or self.tokenExpires < now: # self.createChannel() self.put() ReportEvent.queueEventRecord(self.key.urlsafe(), None, None, "Login") return
def login(self): now = datetime.datetime.now() if self.lastLogin: daysSinceLastLogin = (now - self.lastLogin).days self.loginAvgIntervalDays = (daysSinceLastLogin + self.loginAvgIntervalDays * self.loginCount)/(self.loginCount + 1) self.loginCount += 1 # Update last login time self.lastLogin = now # Create And Store Token if not self.token or self.tokenExpires < now: self.createChannel() self.put() ReportEvent.queueEventRecord(self.key.urlsafe(), None, None, "Login") return
def doPostLoginAction(self, postLoginAction, sessionData): if postLoginAction == "createFromMain": user = self.current_user pointText = str(sessionData['pointtext']) if user: newPoint, newPointRoot = Point.create(title=pointText, content="", summaryText="", user=user, imageURL=None, imageAuthor=None, imageDescription=None, sourceURLs=[], sourceNames=[]) if newPoint: template_values = { 'user': user, 'currentArea': self.session.get('currentArea'), 'currentAreaDisplayName': self.session.get('currentAreaDisplayName'), 'pointURL': newPoint.url } html = self.template_render('waitingPage.html', template_values) self.session['postloginaction'] = None self.session['pointText'] = None self.response.out.write(html) ReportEvent.queueEventRecord(user.key.urlsafe(), newPoint.key.urlsafe(), None, "Create Point") else: logging.error("Was not able to create point with title: " + pointText) self.redirect(str(sessionData['original_url'])) else: logging.error( "User was not available, and so could not create point with title: " + pointText) self.redirect(str(sessionData['original_url'])) else: logging.info("Unknown Post Login action " + postLoginAction) self.redirect(str(sessionData['original_url']))
def doPostLoginAction(self, postLoginAction, sessionData ): if postLoginAction == "createFromMain": user = self.current_user pointText = str(sessionData['pointtext']) if user: newPoint, newPointRoot = Point.create( title=pointText, content="", summaryText="", user=user, imageURL=None, imageAuthor=None, imageDescription=None, sourceURLs=[], sourceNames=[]) if newPoint: template_values = { 'user': user, 'currentArea':self.session.get('currentArea'), 'currentAreaDisplayName':self.session.get('currentAreaDisplayName'), 'pointURL':newPoint.url } html = self.template_render('waitingPage.html', template_values) self.session['postloginaction'] = None self.session['pointText'] = None self.response.out.write(html) ReportEvent.queueEventRecord(user.key.urlsafe(), newPoint.key.urlsafe(), None, "Create Point") else: logging.error("Was not able to create point with title: " + pointText) self.redirect(str(sessionData['original_url'])) else: logging.error("User was not available, and so could not create point with title: " + pointText) self.redirect(str(sessionData['original_url'])) else: logging.info("Unknown Post Login action " + postLoginAction) self.redirect(str(sessionData['original_url']))
def post(self): user = self.current_user if user: resultJSON = json.dumps({'result': False}) oldPoint, oldPointRoot = Point.getCurrentByUrl( self.request.get('urlToEdit')) sourcesURLs=json.loads(self.request.get('sourcesURLs')) \ if self.request.get('sourcesURLs') else None sourcesNames=json.loads(self.request.get('sourcesNames')) \ if self.request.get('sourcesNames') else None sourcesToRemove=json.loads(self.request.get('sourcesToRemove')) \ if self.request.get('sourcesToRemove') else None if oldPoint == None: resultJSON = json.dumps({ 'result': False, 'error': 'Unable to edit point. Please refresh the page and try again.' }) elif user.isLimited: resultJSON = json.dumps({ 'result': False, 'error': 'This account cannot edit points.' }) else: sources = Source.constructFromArrays(sourcesURLs, sourcesNames, oldPoint.key) newVersion = oldPoint.update( newTitle=self.request.get('title'), newContent=self.request.get('content'), newSummaryText=self.request.get('plainText'), user=self.current_user, imageURL=self.request.get('imageURL'), imageAuthor=self.request.get('imageAuthor'), imageDescription=self.request.get('imageDescription'), sourcesToAdd=sources, sourceKeysToRemove=sourcesToRemove) if newVersion: sources = newVersion.getSources() sourcesHTML = self.template_render('sources.html', {'sources': sources}) resultJSON = json.dumps({ 'result': True, 'version': newVersion.version, 'author': newVersion.authorName, 'authorURL': self.current_user.url, 'dateEdited': newVersion.PSTdateEdited.strftime( '%b. %d, %Y, %I:%M %p'), 'pointURL': newVersion.url, 'imageURL': newVersion.imageURL, 'imageAuthor': newVersion.imageAuthor, 'imageDescription': newVersion.imageDescription, 'sourcesHTML': sourcesHTML }) ReportEvent.queueEventRecord(user.key.urlsafe(), newVersion.key.urlsafe(), None, "Edit Point") else: # This is the only way newVersion will fail resultJSON = json.dumps({ 'result': False, 'error': 'You appear not to be logged in.' }) self.response.headers[ "Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)
def _on_signin(self, data, auth_info, provider): auth_id = '%s: %s' % (provider, data['id']) logging.info('Looking for a user with id %s', auth_id) user = self.auth.store.user_model.get_by_auth_id(auth_id) _attrs = self._to_user_model_attrs(data, self.USER_ATTRS[provider]) if user: logging.info('Found existing user to log in: ' + str(_attrs)) # Existing users might've changed their profile data so we update our # local model anyway. This might result in quite inefficient usage # of the Datastore, but we do this anyway for demo purposes. # # In a real app you could compare _attrs with user's properties fetched # from the datastore and update local user in case something's changed. self.auth.set_session(self.auth.store.user_to_dict(user)) self.current_user = user user.login() if 'postloginaction' in self.session: logging.info('There was a post login action, so the user is not logged into the private area.') elif len(user.privateAreas) > 0: self.setUserArea(user.privateAreas[0]) else: # check whether there's a user currently logged in # then, create a new user if nobody's signed in, # otherwise add this auth_id to currently logged in user. if self.logged_in and self.current_user: # This code is currently not triggered, # there is no way to log in again once logged in logging.info('Updating currently logged in user') u = self.current_user u.populate(**_attrs) # The following will also do u.put(). Though, in a real app # you might want to check the result, which is # (boolean, info) tuple where boolean == True indicates success # See webapp2_extras.appengine.auth.models.User for details. u.add_auth_id(auth_id) u.login() else: logging.info('Creating a brand new user. Auth_id: %s ', str(auth_id)) _attrs['url'] = WhysaurusUser.constructURL(_attrs['name']) currentArea = self.session.get('currentArea') currentAreaDisplayName = self.session.get('currentAreaDisplayName') if currentArea: _attrs['privateAreas'] = [currentArea] ok, user = self.auth.store.user_model.create_user(auth_id, **_attrs) if ok: if currentArea: areaUser = AreaUser(userKey=user.key.urlsafe(), privateArea=currentArea) areaUser.putUnique() user.login() self.current_user = user self.auth.set_session(self.auth.store.user_to_dict(user)) ReportEvent.queueEventRecord(user.key.urlsafe(), None, None, "New User") user.addToSearchIndex() else: logging.info('Creation failed: ' + str(ok)) # Remember auth data during redirect, just for this demo. You wouldn't # normally do this. # self.session.add_flash(data, 'data - from _on_signin(...)') # self.session.add_flash(auth_info, 'auth_info - from _on_signin(...)') if 'postloginaction' in self.session: postLoginAction = str(self.session['postloginaction']) logging.info('Doing post login action: ' + postLoginAction) self.doPostLoginAction(postLoginAction, self.session) else: target = str(self.session['original_url']) currentArea = self.session.get('currentArea') currentAreaDisplayName = self.session.get('currentAreaDisplayName') if target.find("/login") != -1 or currentArea: target = "/" logging.info('_ON_SIGNIN: Redirecting to %s' % target) self.redirect(target)
def _on_signin(self, data, auth_info, provider): auth_id = '%s: %s' % (provider, data['id']) logging.info('Looking for a user with id %s', auth_id) user = self.auth.store.user_model.get_by_auth_id(auth_id) _attrs = self._to_user_model_attrs(data, self.USER_ATTRS[provider]) if user: logging.info('Found existing user to log in: ' + str(_attrs)) # Existing users might've changed their profile data so we update our # local model anyway. This might result in quite inefficient usage # of the Datastore, but we do this anyway for demo purposes. # # In a real app you could compare _attrs with user's properties fetched # from the datastore and update local user in case something's changed. self.auth.set_session(self.auth.store.user_to_dict(user)) self.current_user = user user.login() if 'postloginaction' in self.session: logging.info( 'There was a post login action, so the user is not logged into the private area.' ) elif len(user.privateAreas) > 0 and not user.admin: self.setUserArea(user.privateAreas[0]) else: # check whether there's a user currently logged in # then, create a new user if nobody's signed in, # otherwise add this auth_id to currently logged in user. if self.logged_in and self.current_user: # This code is currently not triggered, # there is no way to log in again once logged in logging.info('Updating currently logged in user') u = self.current_user u.populate(**_attrs) # The following will also do u.put(). Though, in a real app # you might want to check the result, which is # (boolean, info) tuple where boolean == True indicates success # See webapp2_extras.appengine.auth.models.User for details. u.add_auth_id(auth_id) u.login() else: logging.info('Creating a brand new user. Auth_id: %s ', str(auth_id)) _attrs['url'] = WhysaurusUser.constructURL(_attrs['name']) _attrs['gaId'] = WhysaurusUser.generateUniqueUserGaid(True) currentArea = self.session.get('currentArea') currentAreaDisplayName = self.session.get( 'currentAreaDisplayName') if currentArea: _attrs['privateAreas'] = [currentArea] ok, user = self.auth.store.user_model.create_user( auth_id, **_attrs) if ok: if currentArea: areaUser = AreaUser(userKey=user.key.urlsafe(), privateArea=currentArea) areaUser.putUnique() user.login() self.current_user = user self.auth.set_session(self.auth.store.user_to_dict(user)) ReportEvent.queueEventRecord(user.key.urlsafe(), None, None, "New User") user.addToSearchIndex() else: logging.info('Creation failed: ' + str(ok)) # Remember auth data during redirect, just for this demo. You wouldn't # normally do this. # self.session.add_flash(data, 'data - from _on_signin(...)') # self.session.add_flash(auth_info, 'auth_info - from _on_signin(...)') if 'postloginaction' in self.session: postLoginAction = str(self.session['postloginaction']) logging.info('Doing post login action: ' + postLoginAction) self.doPostLoginAction(postLoginAction, self.session) else: target = str(self.session['original_url']) currentArea = self.session.get('currentArea') currentAreaDisplayName = self.session.get('currentAreaDisplayName') if target.find("/login") != -1 or currentArea: target = "/" logging.info('_ON_SIGNIN: Redirecting to %s' % target) self.redirect(target)
def newPoint(self): user = self.current_user resultJSON = json.dumps({'result': False, 'error': 'Not authorized'}) secretKey = self.request.get('secret') if not user: if (secretKey == 'myballotsecret'): self.loginBySecretKey(secretKey) user = self.current_user if user: self.response.headers['Access-Control-Allow-Origin'] = '*' if user: if not self.request.get('title'): resultJSON = json.dumps({'result': False, 'error': 'Your point must have a title'}) else: sourcesURLs=json.loads(self.request.get('sourcesURLs')) if self.request.get('sourcesURLs') else None sourcesNames=json.loads(self.request.get('sourcesNames')) if self.request.get('sourcesNames') else None newPoint, newPointRoot = Point.create( title=self.request.get('title'), content=self.request.get('content'), summaryText=self.request.get('plainText'), user=user, imageURL=self.request.get('imageURL'), imageAuthor=self.request.get('imageAuthor'), imageDescription=self.request.get('imageDescription'), sourceURLs=sourcesURLs, sourceNames=sourcesNames) if newPoint: recentlyViewed, sources = yield user.getRecentlyViewed_async( \ excludeList=[newPoint.key.parent()] + \ newPoint.getLinkedPointsRootKeys("supporting") + \ newPoint.getLinkedPointsRootKeys("counter")), \ newPoint.getSources_async() templateValues = { 'point': newPoint, 'pointRoot': newPointRoot, 'recentlyViewedPoints': recentlyViewed, 'supportingPoints': None, 'counterPoints': None, 'supportedPoints':newPointRoot.getBacklinkPoints("supporting"), 'counteredPoints':newPointRoot.getBacklinkPoints("counter"), 'sources': sources, 'user': user, 'voteValue': 0, 'ribbonValue': False, 'currentArea':self.session.get('currentArea'), 'currentAreaDisplayName':self.session.get('currentAreaDisplayName') } html = self.template_render('pointContent.html', templateValues) templateValues = { 'user': self.current_user, 'pointRoot': newPointRoot, 'comments': None } commentHTML = self.template_render('pointComments.html', templateValues) resultJSON = json.dumps({'result': True, 'pointURL': newPoint.url, 'title':newPoint.title, 'html': html, 'commentHTML': commentHTML, 'rootKey': newPointRoot.key.urlsafe() }) ReportEvent.queueEventRecord(user.key.urlsafe(), newPoint.key.urlsafe(), None, "Create Point") else: resultJSON = json.dumps({'result': False, 'error': 'Failed to create point.'}) else: resultJSON = json.dumps({'result': False, 'error': 'You appear not to be logged in.'}) self.response.headers["Pragma"]="no-cache" self.response.headers["Cache-Control"]="no-cache, no-store, must-revalidate, pre-check=0, post-check=0" self.response.headers["Expires"]="Thu, 01 Dec 1994 16:00:00" self.response.headers["Content-Type"] = 'application/json; charset=utf-8' self.response.out.write(resultJSON)