def emailResourceApproval(email, title): """ Email resource owner on approval. Using template: resource_approval @type email: string @param email: Email address to send to ... @rtype: Boolean @returns: Whether emailer was successful or not. """ # Create values for template. emailAccount = Config.get('email') subject = "Your resource has been approved" template_values = { 'link': Config.get('default_host'), 'title': title, 'config': Config.get_all() } # Render email body. body = Emailer.render('email/resource_approval', template_values, suffix = 'txt') # Send email. try: return Emailer.send(email, subject, body, from_name = emailAccount['from_name'], from_address = emailAccount['from_email']) except Exception, e: log.info("*** couldn't send resource approval email") log.error(e) return False
def emailTempPassword(email, password): """ Email temporary password. Using template: forgot_password @type email: string @param email: Email address to send to ... @rtype: Boolean @returns: Whether emailer was successful or not. """ # Create values for template. emailAccount = Config.get('email') subject = "Your password has been reset" link = "%slogin" % Config.get('default_host') link = "%stou" % Config.get('default_host') template_values = { 'password': password, 'link': link, 'config': Config.get_all() } # Render email body. body = Emailer.render('email/forgot_password', template_values, suffix = 'txt') # Send email. try: return Emailer.send(email, subject, body, from_name = emailAccount['from_name'], from_address = emailAccount['from_email']) except Exception, e: log.info("*** couldn't send forgot password email") log.error(e) return False
def send(phone, message): log.info("Sending sms...") message = clean(message) settings = Config.get('twilio') account = twilio.Account(settings['sid'], settings['token']) callback = Config.base_url() if not callback: callback = Config.get('default_host') data = { 'From': settings['phone'], 'To': phone, 'Body': message, 'StatusCallback': "%stwilio/status" % callback } log.debug(data) try: response = account.request('/%s/Accounts/%s/SMS/Messages.json' % (settings['api'], settings['sid']), 'POST', data) log.info("--> %s" % response) response = json.loads(response) smsid = response['TwilioResponse']['SMSMessage']['Sid'] status = "passed" except Exception, e: log.error(e) smsid = None status = "blocked"
def emailUnauthenticatedUser(email, authGuid): """ Send unauthenticated user a link to authenticate. Using template: auth_user @type email: string @param email: Email address to send to @rtype: * @returns: Emailer send response. """ # Create values for template. emailAccount = Config.get('email') subject = "Please authenticate your account" link = "%sjoin/auth/%s" % (Config.get('default_host'), authGuid) template_values = { 'link': link, 'config': Config.get_all() } # Render email body. body = Emailer.render('email/auth_user', template_values, suffix = 'txt') # Send email. try: return Emailer.send(email, subject, body, from_name = emailAccount['from_name'], from_address = emailAccount['from_email']) except Exception, e: log.info("*** couldn't send authenticate user email") log.error(e) return False
def showHome(self): """ Sets up template data and renders homepage template. """ homepage = Config.get('homepage') features = Config.get('features') locationData = mLocation.getSimpleLocationDictionary(self.db) allIdeasData = mIdea.getMostRecentIdeas(self.db, homepage['num_recent_ideas']); locations = dict(data = locationData, json = json.dumps(locationData)) allIdeas = dict(data = allIdeasData, json = json.dumps(allIdeasData)) news = self.getNewsItems() if (bool(features.get('is_display_leaderboard'))): leaderboardProjects = mProject.getLeaderboardProjects(self.db, 6) self.template_data['leaderboard'] = leaderboardProjects if (bool(features.get('is_display_featured_projects'))): featuredProjects = mProject.getFeaturedProjects(self.db, 6) self.template_data['featured_projects'] = featuredProjects if (bool(features.get('is_community_leaders_displayed'))): community_leaders = self.orm.query(models.CommunityLeader) \ .order_by('`order`') \ .all() self.template_data['community_leaders'] = community_leaders self.template_data['locations'] = locations self.template_data['all_ideas'] = allIdeas self.template_data['news'] = news return self.render('home', {'locations':locations, 'all_ideas':allIdeas})
def emailAccountDeactivation(email): """ Email deleted users. Using template: account_deactivation @type email: string @param email: Email address to send to ... @rtype: Boolean @returns: Whether emailer was successful or not. """ # Create values for template. emailAccount = Config.get('email') subject = "Your account has been deactivated" link = "%stou" % Config.get('default_host') template_values = { 'link': link, 'config': Config.get_all() } # Render email body. body = Emailer.render('email/account_deactivation', template_values, suffix = 'txt') # Send email. try: return Emailer.send(email, subject, body, from_name = emailAccount['from_name'], from_address = emailAccount['from_email']) except Exception, e: log.info("*** couldn't send account deactivation email") log.error(e) return False
def showHome(self): """ Sets up template data and renders homepage template. """ homepage = Config.get("homepage") features = Config.get("features") locationData = mLocation.getSimpleLocationDictionary(self.db) allIdeasData = mIdea.getMostRecentIdeas(self.db, homepage["num_recent_ideas"]) locations = dict(data=locationData, json=json.dumps(locationData)) allIdeas = dict(data=allIdeasData, json=json.dumps(allIdeasData)) news = self.getNewsItems() if bool(features.get("is_display_leaderboard")): leaderboardProjects = mProject.getLeaderboardProjects(self.db, 6) self.template_data["leaderboard"] = leaderboardProjects if bool(features.get("is_display_featured_projects")): featuredProjects = mProject.getFeaturedProjects(self.db, 6) self.template_data["featured_projects"] = featuredProjects if bool(features.get("is_community_leaders_displayed")): community_leaders = self.orm.query(models.CommunityLeader).order_by("`order`").all() self.template_data["community_leaders"] = community_leaders self.template_data["locations"] = locations self.template_data["all_ideas"] = allIdeas self.template_data["news"] = news return self.render("home", {"locations": locations, "all_ideas": allIdeas})
def getHomepageQuestion(self): q = None if (Config.get('homepage').get('is_question_from_cms')): sql = "select question from homepage_question where is_active = 1 and is_featured = 1" data = list(self.db.query(sql)) if (len(data) == 1): q = data[0].question if (not q): q = Config.get('homepage').get('question') return q
def newProject(self): if (self.request('main_text')): return False supported_features = Config.get('features') if (self.user): owner_user_id = self.user.id title = self.request('title') description = self.request('text') organization = self.request('organization') locationId = util.try_f(int, self.request('location_id'), -1) imageId = self.request('image') keywords = [word.strip() for word in self.request('keywords').split(',')] if not util.strNullOrEmpty(self.request('keywords')) else [] resourceIds = self.request('resources').split(',') isOfficial = self.user.isAdmin and supported_features.get('is_official_supported') projectId = mProject.createProject(self.db, owner_user_id, title, description, ' '.join(keywords), locationId, imageId, isOfficial, organization) for resourceId in resourceIds: log.info("*** insert resource id %s" % resourceId) mProject.addResourceToProject(self.db, projectId, resourceId) if (projectId): return projectId else: log.error("*** couldn't create project") return False else: log.error("*** only logged in users can create projects") return False
def getS3Path(self, fileid): """ Get the path to the file given by the fileid on the S3 server. """ return "%(file_path)s/%(file_id)s" % {'file_path': Config.get('media').get('file_path'), 'file_id': fileid}
def GET(self, action = None): """ Get for Blitz.io route """ response = Config.get('blitz_io').get('response') return response
def emailProjectEndorsement(email, title, leaderName): """ Email project admins about endorsements. Using template: project_endorsement @type email: string @param email: Email address to send to ... @rtype: Boolean @returns: Whether emailer was successful or not. """ # Create values for template. emailAccount = Config.get('email') subject = "%s liked your project!" % leaderName template_values = { 'title': title, 'leader_name': leaderName, 'config': Config.get_all() } # Render email body. body = Emailer.render('email/project_endorsement', template_values, suffix = 'txt') # Send email. try: return Emailer.send(email, subject, body, from_name = emailAccount['from_name'], from_address = emailAccount['from_email']) except Exception, e: log.info("*** couldn't send endorsement email") log.error(e) return False
def GET(self, action=None): """ Get for Blitz.io route """ response = Config.get('blitz_io').get('response') return response
def GET(self, action=None, param0=None): project_user = dict(is_member=True, is_project_admin=True) self.template_data['project_user'] = dict( data=project_user, json=json.dumps(project_user)) self.template_data['homepage_question'] = self.getHomepageQuestion() if (not action or action == 'home'): return self.showHome() elif (action == 'leaderboard'): return self.showLeaderboard() elif (action == 'mobile'): return self.showMobile() elif (action == 'bb'): return self.showMobile(isBlackBerry=True) # Main login page # TODO: This should be consolidated with the twitter & facebook actions elif (action == 'login'): return self.showLogin() # Twetter-related actions elif action == 'twitter': return self._twitter_action(action=param0) # The "correct" facebook URLs once we change them in the app(s) elif action == 'facebook': return self._facebook_action(action=param0) # Miscellaneous actions elif (action == 'nyc'): self.redirect('http://nyc.changeby.us/') elif (action == 'beta'): return self.showBeta() # About page can be city-specific elif (action == 'about'): for action in [ "%s_about" % Config.get("site").get("city_id"), "about" ]: template = os.path.dirname( __file__) + '/../templates/%s.html' % action if os.path.exists(template): return self.render(action) # If we got here, the template was not found return self.not_found() else: # This is the default for all pages. We should check # if there is a matching template, and if not, throw # a 404. template = os.path.dirname( __file__) + '/../templates/' + action + '.html' print template if not os.path.exists(template): return self.not_found() else: return self.render(action)
def directMessageUser(db, toUserId, toName, toEmail, fromUserId, fromName, message): """ Email user about direct message. Using template: direct_message @type email: string @param email: Email address to send to ... @rtype: Boolean @returns: Whether emailer was successful or not. """ # Create values for template. emailAccount = Config.get('email') #email = "%s <%s>" % (toName, toEmail) email = toEmail subject = "Change By Us message from %s" % fromName link = "%suseraccount/%s" % (Config.get('default_host'), fromUserId) template_values = { 'name': fromName, 'message': message, 'link': link, 'config': Config.get_all() } # Render email body. body = Emailer.render('email/direct_message', template_values, suffix = 'txt') # Send email. try: isSent = Emailer.send(email, subject, body, from_name = emailAccount['from_name'], from_address = emailAccount['from_email']) if (isSent): db.insert('direct_message', message = message, to_user_id = toUserId, from_user_id = fromUserId) return True else: log.info("*** couldn't log direct message") # Not sure if best to return False return False except Exception, e: log.info("*** couldn't send direct message email") log.error(e) return False
def db_connect(cls): settings = Config.get('database') cls._db = web.database(dbn=settings['dbn'], user=settings['user'], pw=settings['password'], db=settings['db'], host=settings['host']) log.info("Connected to db: %s" % cls._db)
def getLocalPath(self, fileid): """ Get the path to the file given by the fileid on the local file system. This is used only to temporarily save the file before uploading it to the S3 server. """ return "%(file_path)s/%(file_id)s" % {'file_path': Config.get('media').get('file_path'), 'file_id': fileid}
def validate(request): # this is just a cheap validate that depends on the attacker not knowing our AccountSid, it's not secure settings = Config.get('twilio') if request('AccountSid') != settings['sid']: log.error("Request from Twilio does not have correct sid! Possibly an attack! Blocking message.") log.error("--> was theirs [%s] vs ours [%s]" % (request('AccountSid'), settings['sid'])) return False return True
def getS3Path(self, fileid): """ Get the path to the file given by the fileid on the S3 server. """ return "%(file_path)s/%(file_id)s" % { 'file_path': Config.get('media').get('file_path'), 'file_id': fileid }
def GET(self, action=None, param0=None): project_user = dict(is_member = True, is_project_admin = True) self.template_data['project_user'] = dict(data = project_user, json = json.dumps(project_user)) self.template_data['homepage_question'] = self.getHomepageQuestion() if (not action or action == 'home'): return self.showHome() elif (action == 'leaderboard'): return self.showLeaderboard() elif (action == 'mobile'): return self.showMobile() elif (action == 'bb'): return self.showMobile(isBlackBerry = True) # Main login page # TODO: This should be consolidated with the twitter & facebook actions elif (action == 'login'): return self.showLogin() # Twetter-related actions elif action == 'twitter': return self._twitter_action(action=param0) # The "correct" facebook URLs once we change them in the app(s) elif action == 'facebook': return self._facebook_action(action=param0) # Miscellaneous actions elif (action == 'nyc'): self.redirect('http://nyc.changeby.us/') elif (action == 'beta'): return self.showBeta() # About page can be city-specific elif (action == 'about'): for action in ["%s_about" % Config.get("site").get("city_id"), "about"]: template = os.path.dirname(__file__) + '/../templates/%s.html' % action if os.path.exists(template): return self.render(action) # If we got here, the template was not found return self.not_found() else: # This is the default for all pages. We should check # if there is a matching template, and if not, throw # a 404. template = os.path.dirname(__file__) + '/../templates/' + action + '.html' print template if not os.path.exists(template): return self.not_found() else: return self.render(action)
def getLocalPath(self, fileid): """ Get the path to the file given by the fileid on the local file system. This is used only to temporarily save the file before uploading it to the S3 server. """ return "%(file_path)s/%(file_id)s" % { 'file_path': Config.get('media').get('file_path'), 'file_id': fileid }
def emailResourceNotification(email, projectId, title, description, resourceName): """ Email resource contacts on resource add. Using template: resource_notification @type email: string @param email: Email address to send to ... @rtype: Boolean @returns: Whether emailer was successful or not. """ # Create values for template. emailAccount = Config.get('email') subject = "A project on Changeby.us has added %s as a resource" % resourceName link = "%sproject/%s" % (Config.get('default_host'), str(projectId)) template_values = { 'title': title, 'description': description, 'resource_name': resourceName, 'link': link, 'config': Config.get_all() } # Render email body. body = Emailer.render('email/resource_notification', template_values, suffix = 'txt') # If dev, don't email resources if (Config.get('dev')): log.info("*** body = %s" % body) return True # Send email. try: return Emailer.send(email, subject, body, from_name = emailAccount['from_name'], from_address = emailAccount['from_email']) except Exception, e: log.info("*** couldn't send resource notification email") log.error(e) return False
def get_supported_languages(self): """ Find the language files available in the translations directory. Returns a dictionary which has language codes as keys, and human-readable language names as values. """ try: enabled_langs = Config.get('lang') except KeyError: enabled_langs = {} return enabled_langs
def getNewsItems(self): data = [] feedUrl = Config.get('blog_host_feed') if (feedUrl): try: # BUGFIX: couldn't parse json from production blog, hence the string conversion # eholda 2011-06-19 raw = urllib2.urlopen(feedUrl, timeout = 1) data = json.loads(raw.read()) raw.close() except Exception, e: log.info("*** couldn't get feed for news items at %s" % feedUrl) log.error(e)
def showHome(self): """ Sets up template data and renders homepage template. """ homepage = Config.get('homepage') features = Config.get('features') locationData = mLocation.getSimpleLocationDictionary(self.db) allIdeasData = mIdea.getMostRecentIdeas(self.db, homepage['num_recent_ideas']) locations = dict(data=locationData, json=json.dumps(locationData)) allIdeas = dict(data=allIdeasData, json=json.dumps(allIdeasData)) news = self.getNewsItems() if (bool(features.get('is_display_leaderboard'))): leaderboardProjects = mProject.getLeaderboardProjects(self.db, 6) self.template_data['leaderboard'] = leaderboardProjects if (bool(features.get('is_display_featured_projects'))): featuredProjects = mProject.getFeaturedProjects(self.db, 6) self.template_data['featured_projects'] = featuredProjects if (bool(features.get('is_community_leaders_displayed'))): community_leaders = self.orm.query(models.CommunityLeader) \ .order_by('`order`') \ .all() self.template_data['community_leaders'] = community_leaders self.template_data['locations'] = locations self.template_data['all_ideas'] = allIdeas self.template_data['news'] = news return self.render('home', { 'locations': locations, 'all_ideas': allIdeas })
def emailProjectJoin(email, projectId, title, userId, userName): """ Email project admins when new user joins. Using template: project_join @type email: string @param email: Email address to send to ... @rtype: Boolean @returns: Whether emailer was successful or not. """ # Create values for template. emailAccount = Config.get('email') defaultUrl = Config.get('default_host') subject = "A new member %s has joined your project %s" % (userName, title) userLink = "%suseraccount/%s" % (defaultUrl, str(userId)) memberLink = "%sproject/%s#show,members" % (defaultUrl, str(projectId)) template_values = { 'title': title, 'user_name': userName, 'user_link': userLink, 'member_link': memberLink, 'config': Config.get_all() } # Render email body. body = Emailer.render('email/project_join', template_values, suffix = 'txt') # Send email. try: return Emailer.send(email, subject, body, from_name = emailAccount['from_name'], from_address = emailAccount['from_email']) except Exception, e: log.info("*** couldn't send join email") log.error(e) return False
def getNewsItems(self): data = [] feedUrl = Config.get('blog_host_feed') if (feedUrl): try: # BUGFIX: couldn't parse json from production blog, hence the string conversion # eholda 2011-06-19 raw = urllib2.urlopen(feedUrl, timeout=1) data = json.loads(raw.read()) raw.close() except Exception, e: log.info("*** couldn't get feed for news items at %s" % feedUrl) log.error(e)
def sendSMSInvite(db, phone, projectId): log.info("*** sending invite to %s" % phone) try: if (not isPhoneStopped(db, phone)): link = "%sproject/%s" % (Config.get('default_host'), str(projectId)) message = "You've been invited to a project on changeby.us. Visit %s to see the project. Reply 'STOP' to stop changeby.us messages." % link return helpers.sms.send(phone, message) else: return False except Exception, e: log.info("*** something failed in sending sms invite") log.error(e) return False
def emailIdeaConfirmation(email, responseEmail, locationId): """ Email upon idea submission. Using template: idea_confirmation @type email: string @param email: Email address to send to ... @rtype: Boolean @returns: Whether emailer was successful or not. """ # Create values for template. emailAccount = Config.get('email') host = Config.get('default_host') subject = "Thanks for submitting an idea to Change by Us!" searchLink = "%ssearch?location_id=%s" % (host, locationId) createLink = "%screate" % host template_values = { 'search_link': searchLink, 'create_link': createLink, 'response_email': emailAccount['from_email'], 'config': Config.get_all() } # Render email body. body = Emailer.render('email/idea_confirmation', template_values, suffix = 'txt') # Send email. try: return Emailer.send(email, subject, body, from_name = emailAccount['from_name'], from_address = emailAccount['from_email']) except Exception, e: log.info("*** couldn't send authenticate user email") log.error(e) return False
def emailInvite(email, inviterName, projectId, title, description, message = None): """ Send invitation email. Using template: project_invite @type email: string @param email: Email address to send to ... @rtype: Boolean @returns: Whether emailer was successful or not. """ # Create values for template. emailAccount = Config.get('email') subject = "You've been invited by %s to join a project" % inviterName link = "%sproject/%s" % (Config.get('default_host'), str(projectId)) template_values = { 'inviter': inviterName, 'title':title, 'description':description, 'link': link, 'message': message, 'config': Config.get_all() } # Render email body. body = Emailer.render('email/project_invite', template_values, suffix = 'txt') # Send email. try: return Emailer.send(email, subject, body, from_name = emailAccount['from_name'], from_address = emailAccount['from_email']) except Exception, e: log.info("*** couldn't send invite email") log.error(e) return False
def setUp(self): Config.load() # Use the test_db, so that you don't blow stuff away. db_config = Config.get('database') if 'test_db' in db_config and db_config['test_db']: db_config['db'] = db_config['test_db'] # Grab a database connection self.db = main.sessionDB() self.install_db_structure(self.db) self.load_db_fixtures(self.db, *self.fixtures) # HACK: We kept getting db.printing inexplicably set to True, so patch # it to be False here. _real_db_execute = web.db.DB._db_execute def _db_execute(self, cur, sql_query): self.printing = False return _real_db_execute(self, cur, sql_query) web.db.DB._db_execute = _db_execute super(DbFixturesMixin, self).setUp()
def GET(self, action=None, param0=None, param1=None, param2=None): if (Config.get('features').get('is_calendar_enabled')): if (action == 'show' or action == 'get'): if (not param0 or not param1): year, month = self.getCurrentYearMonth() else: year, month = (param0, param1) d = datetime(int(year), int(month), 1) start = "%s-%s" % (year, month) end = (d + timedelta(days = 32)).strftime('%Y-%m') events = self.getEvents(start, end) if (action == 'show'): return self.showCalendar(events, start, end, d) elif (action == 'get'): return self.getCalendar(events) else: return self.not_found() else: return self.not_found()
def __init__(self): log.info( "---------- %s %s --------------------------------------------------------------------------" % (web.ctx.method, web.ctx.path)) # database self.db = Controller.get_db() # memcache self.cache = memcache.Client([ Config.get('memcache')['address'] + ":" + str(Config.get('memcache')['port']) ]) # session self.session = SessionHolder.get_session() log.info("SESSION: %s " % self.session) # template data self.template_data = {} # set mode self.template_data['app_mode'] = self.appMode = Config.get('app_mode') self.template_data['app_env'] = self.appEnv = Config.get('app_env') #set media root self.template_data['media_root'] = Config.get('media')['root'] #set city-specific map options self.template_data['map'] = Config.get('map') #set the supported features self.template_data['features'] = Config.get('features') # user self.setUserObject() # beta redirect if (self.appMode == 'beta' and not self.user): path = web.ctx.path.split('/') allowed = [ 'beta', 'login', 'join', 'tou', 'logout', # Twitter related paths 'twitter', # 'twitter/login', 'twitter/create', 'twitter/callback', 'twitter/disconnect' # Facebook paths - not relevant until FB app is updated 'facebook', # 'facebook/login', 'facebook/create', 'facebook/callback', 'facebook/disconnect' # Remove the following facebook paths once app is updated # 'login_facebook', # 'login_facebook_create', # 'disconnect_facebook', ] if (path[1] not in allowed): self.redirect('/beta')
def login_facebook(self): fb_settings = Config.get('facebook') #cookiename = "fbs_%s" % fb_settings['app_id'] #fbcookie = web.cookies().get(cookiename) #entries = fbcookie.split("&") #dc = {} #for e in entries: # es = e.split("=") # dc[es[0]] = es[1] url = "https://graph.facebook.com/%s" % self.request('uid') # Facebook does not like POST requests, but when they do, we can # enable the following # params = {'access_token':self.request('access_token')} # resp = urllib2.urlopen(url, urllib.urlencode(dict(params))) resp = urllib2.urlopen("%s?access_token=%s" % (url, self.request('access_token'))) profile = json.loads(resp.read()) resp.close() sql = "select * from facebook_user where facebook_id = $id" res = list(self.db.query(sql, { 'id':profile['id'] })) associated_user = -1 created_user = False created_facebook_user = False # do we already have fb data for this user? -> log them in if len(res) == 1: facebook_user = res[0] self.session.user_id = facebook_user.user_id self.session.invalidate() else: email = profile["email"] check_if_email_exists = "select * from user where email = $email" users_with_this_email = list(self.db.query(check_if_email_exists, {'email':email})) email_exists = len(users_with_this_email) # see if we have a user with this email on a regular account if email_exists == 1: uid = users_with_this_email[0].user_id else: # no regular account with this email # see if the user is logged in s = SessionHolder.get_session() make_new_user = True try: uid = s.user_id if uid is not None: make_new_user = False # user is logged in except AttributeError: pass #uid = mUser.createUser(self.db, profile["email"], passw, profile["first_name"], profile["last_name"]) # not logged in, so make a new user if make_new_user: created_user = True self.session.profile = profile self.session._changed = True SessionHolder.set(self.session) if not created_user: # we can associate an existing account with this data try: self.db.insert('facebook_user', user_id = uid, facebook_id = profile['id']) except MySQLdb.IntegrityError: # Means that we already have a record for this user # Check if the facebook user id is the same as what's in the database # If not, check if graph.facebook.com gives us the correct user for the existing id # otherwise add the new facebook uid log.info("Got IntegrityError inserting fbid %s for uid %s" % (profile['id'], uid)) query = "select facebook_id from facebook_user where user_id = $uid" res = self.db.query(query, {'uid':uid}) fbid = None if len(res) > 0: fbid = res[0].facebook_id if fbid is not None and fbid != profile['id']: log.info("Stored fbid (%s) does not match provided fbid (%s). Updating facebook_user for uid %s" % (fbid, profile['id'], uid)) # Check if the existing id is correct or not # If it's not correct, update the record self.db.update('facebook_user', where='user_id=%s' % uid, facebook_id=profile['id']) associated_user = uid created_facebook_user = True self.session.user_id = associated_user self.session.invalidate() if created_user: return self.render('join', {'new_account_via_facebook': True, 'facebook_data': profile}) # go to TOS else: raise self.redirect('/') # user had already signed up with us before
import framework.util as util import lib.web #temp from framework.image_server import * import giveaminute.projectResource as mResource import cgi import oauth2 as oauth import urllib import urllib2 import json import hashlib import MySQLdb # for exceptions tw_settings = Config.get('twitter') tw_consumer = oauth.Consumer(tw_settings['consumer_key'], tw_settings['consumer_secret']) tw_client = oauth.Client(tw_consumer) class Home(Controller): def GET(self, action=None, param0=None): project_user = dict(is_member = True, is_project_admin = True) self.template_data['project_user'] = dict(data = project_user, json = json.dumps(project_user)) if (not action or action == 'home'): return self.showHome() elif (action == 'leaderboard'): return self.showLeaderboard() elif (action == 'mobile'): return self.showMobile()
def __init__(self): log.info("---------- %s %s --------------------------------------------------------------------------" % (web.ctx.method, web.ctx.path)) # database self.db = Controller.get_db() # memcache self.cache = memcache.Client([Config.get('memcache')['address'] + ":" + str(Config.get('memcache')['port'])]) # session self.session = SessionHolder.get_session() log.info("SESSION: %s " % self.session) # template data self.template_data = {} # set mode self.template_data['app_mode'] = self.appMode = Config.get('app_mode') self.template_data['app_env'] = self.appEnv = Config.get('app_env') #set media root self.template_data['media_root'] = Config.get('media')['root'] #set city-specific map options self.template_data['map'] = Config.get('map') #set the supported features self.template_data['features'] = Config.get('features') # user self.setUserObject() # beta redirect if (self.appMode == 'beta' and not self.user): path = web.ctx.path.split('/') allowed = ['beta', 'login', 'join', 'tou', 'logout', # Twitter related paths 'twitter', # 'twitter/login', 'twitter/create', 'twitter/callback', 'twitter/disconnect' # Facebook paths - not relevant until FB app is updated 'facebook', # 'facebook/login', 'facebook/create', 'facebook/callback', 'facebook/disconnect' # Remove the following facebook paths once app is updated # 'login_facebook', # 'login_facebook_create', # 'disconnect_facebook', ] if (path[1] not in allowed): self.redirect('/beta')
def get_db_config(self): """Pulls the database config information from the config.yaml file.""" return Config.get('database')
def login_facebook(self): fb_settings = Config.get('facebook') #cookiename = "fbs_%s" % fb_settings['app_id'] #fbcookie = web.cookies().get(cookiename) #entries = fbcookie.split("&") #dc = {} #for e in entries: # es = e.split("=") # dc[es[0]] = es[1] url = "https://graph.facebook.com/%s" % self.request('uid') # Facebook does not like POST requests, but when they do, we can # enable the following # params = {'access_token':self.request('access_token')} # resp = urllib2.urlopen(url, urllib.urlencode(dict(params))) resp = urllib2.urlopen("%s?access_token=%s" % (url, self.request('access_token'))) profile = json.loads(resp.read()) resp.close() sql = "select * from facebook_user where facebook_id = $id" res = list(self.db.query(sql, {'id': profile['id']})) associated_user = -1 created_user = False created_facebook_user = False # do we already have fb data for this user? -> log them in if len(res) == 1: facebook_user = res[0] self.session.user_id = facebook_user.user_id self.session.invalidate() else: email = profile["email"] check_if_email_exists = "select * from user where email = $email" users_with_this_email = list( self.db.query(check_if_email_exists, {'email': email})) email_exists = len(users_with_this_email) # see if we have a user with this email on a regular account if email_exists == 1: uid = users_with_this_email[0].user_id else: # no regular account with this email # see if the user is logged in s = SessionHolder.get_session() make_new_user = True try: uid = s.user_id if uid is not None: make_new_user = False # user is logged in except AttributeError: pass #uid = mUser.createUser(self.db, profile["email"], passw, profile["first_name"], profile["last_name"]) # not logged in, so make a new user if make_new_user: created_user = True self.session.profile = profile self.session._changed = True SessionHolder.set(self.session) if not created_user: # we can associate an existing account with this data try: self.db.insert('facebook_user', user_id=uid, facebook_id=profile['id']) except MySQLdb.IntegrityError: # Means that we already have a record for this user # Check if the facebook user id is the same as what's in the database # If not, check if graph.facebook.com gives us the correct user for the existing id # otherwise add the new facebook uid log.info( "Got IntegrityError inserting fbid %s for uid %s" % (profile['id'], uid)) query = "select facebook_id from facebook_user where user_id = $uid" res = self.db.query(query, {'uid': uid}) fbid = None if len(res) > 0: fbid = res[0].facebook_id if fbid is not None and fbid != profile['id']: log.info( "Stored fbid (%s) does not match provided fbid (%s). Updating facebook_user for uid %s" % (fbid, profile['id'], uid)) # Check if the existing id is correct or not # If it's not correct, update the record self.db.update('facebook_user', where='user_id=%s' % uid, facebook_id=profile['id']) associated_user = uid created_facebook_user = True self.session.user_id = associated_user self.session.invalidate() if created_user: return self.render('join', { 'new_account_via_facebook': True, 'facebook_data': profile }) # go to TOS else: raise self.redirect( '/') # user had already signed up with us before
def getConfigVar(self, var_name): return Config.get(var_name)
import framework.util as util import lib.web #temp from framework.image_server import * import giveaminute.projectResource as mResource import cgi import oauth2 as oauth import urllib import urllib2 import json import hashlib import MySQLdb # for exceptions tw_settings = Config.get('twitter') tw_consumer = oauth.Consumer(tw_settings['consumer_key'], tw_settings['consumer_secret']) tw_client = oauth.Client(tw_consumer) class Home(Controller): def GET(self, action=None, param0=None): project_user = dict(is_member=True, is_project_admin=True) self.template_data['project_user'] = dict( data=project_user, json=json.dumps(project_user)) self.template_data['homepage_question'] = self.getHomepageQuestion() if (not action or action == 'home'): return self.showHome() elif (action == 'leaderboard'):