Example #1
0
 def post(self, keg_id):
     keg = self.get_keg_or_bust(keg_id)
     keg.geo_location.lat = self.request.params.get('latitude',
                                                    keg.geo_location.lat)
     keg.geo_location.lon = self.request.params.get('longitude',
                                                    keg.geo_location.lon)
     keg.photo_url = self.request.params.get('photo_url', keg.photo_url)
     keg_id = self.request.params.get('keg')
     if keg_id:
         keg = Keg.get_by_key_name(keg_id)
         if not keg:
             raise InvalidParameterException(
                 param='keg',
                 value=keg_id,
                 description='The given keg could not be located')
         if keg.empty():
             raise InvalidParameterException(
                 param='keg',
                 value=keg_id,
                 description='The given keg is reported empty')
         query = Keg.all(keys_only=True).filter('keg =', keg)
         keys = [key for key in query]
         if keys and not keg.key() in keys:
             raise InvalidParameterException(
                 param='keg',
                 value=keg_id,
                 description=
                 'The given keg is already associated to another keg')
         keg.put()
         keg.keg = keg.key()
     keg.put()
     webapp2.redirect_to('keg', keg_id=keg_id)
Example #2
0
    def get(self, id=None):
        ''' Handle get request; increase "uses" if appropriate or re-direct
		or do nothing if not appropriate
		'''
        username = getUserFromSecureCookie(
            self.request.cookies.get("username"))
        users = User.all()
        user = users.filter("username ="******"signin")

        if user.key.id == gem.user.key.id:
            return redirect_to("home")

        gemfinders = pickle.loads(str(gem.gemfinders))
        gems = pickle.loads(str(user.gems))

        if (not user.key.id in gemfinders and not long(id) in gems):

            gem.numGemfinders += 1

            gemfinders[user.key.id] = True
            gem.gemfinders = pickle.dumps(gemfinders)
            gem.put()

            gems[long(id)] = True
            user.gems = pickle.dumps(gems)
            user.put()

        return redirect_to("home")
Example #3
0
	def get(self, id=None):
		''' Handle get request; increase "uses" if appropriate or re-direct
		or do nothing if not appropriate
		'''
		username = getUserFromSecureCookie(self.request.cookies.get("username"))
		users = User.all()
		user = users.filter("username ="******"signin")

		if user.key.id == gem.user.key.id:
			return redirect_to("home")

		gemfinders = pickle.loads(str(gem.gemfinders))
		gems = pickle.loads(str(user.gems))

		if (not user.key.id in gemfinders and 
			not long(id) in gems):

			gem.numGemfinders += 1

			gemfinders[user.key.id] = True
			gem.gemfinders = pickle.dumps(gemfinders)
			gem.put()

			gems[long(id)] = True
			user.gems = pickle.dumps(gems)
			user.put()

		return redirect_to("home")
Example #4
0
def ssh_keys_add(request, user_id):
    """Handles the form to allow adding SSH keys.
    """
    # normalize user ID
    ouid = user_id
    if not aeusers.is_current_user_admin() and not user_id == 'me':
        return webapp2.redirect_to('users-profile', user_id='me')
    if user_id == 'me':
        user_id = request.user.user_id()
    user = users.get(user_id)

    # if form validates then save the object to the datastore
    form = forms.SSHKeyForm(request.POST)
    if request.method == 'POST' and form.validate():
        _err = False

        # ensure this key doesn't already exist in the system
        if ssh_keys.check_exists(form.ssh_key.data):
            _err = True
            _msg = 'SSH key already exists in the system.'
            try:
                form.errors['ssh_key'].append(_msg)
            except KeyError:
                form.errors['ssh_key'] = [_msg]

        if not _err:
            ssh_keys.add_for_user(user, form.title.data, form.ssh_key.data)
            session = request.session()
            session.add_flash('SSH key added: {0}'.format(form.title.data), level='success')
            return webapp2.redirect_to('users-profile', user_id=ouid)

    # render template with the form in the context
    return {'form': form, 'cancel_url': webapp2.uri_for('users-profile', user_id=ouid), 'user': user}
Example #5
0
    def _arguments_wrapper(request, *args, **kwargs):

        # store current url in the session so we can redirect back to the
        # current url if required
        session = request.session()
        session['next_url'] = request.path_qs

        # ensure user is logged in via appengine user's service
        request.user = aeusers.get_current_user()
        if request.user is None:
            logging.info('User not logged in')
            return webapp2.redirect_to(LOGGEDIN_UNAUTHED_URL)

        # fetch datastore record for user if one already exists
        request.beardo_user = users.get(request.user.user_id())

        # create a datastore record if user is not stored but is on the invite list
        if settings.INVITE_ONLY and request.beardo_user is None and request.user.email() in settings.INVITE_LIST:
            request.beardo_user = users.get_or_create(request.user)

        # create a datastore record if registration is open to the public
        if aeusers.is_current_user_admin() or not settings.INVITE_ONLY:
            request.beardo_user = users.get_or_create(request.user)

        # if we still don't have a datastore record then user should not be allowed access
        if request.beardo_user is None:
            logging.info('User record not found')
            return webapp2.redirect_to(LOGGEDIN_UNAUTHED_URL)

        # call the view function
        return view_method(request, *args, **kwargs)
Example #6
0
 def post(self):
     beer_id = self.request.params['beer']
     if Keg.get_by_key_name(name):
         raise Conflict(name, webapp2.uri_for('keg', keg_id=name))
     latitude = self.request.params['latitude']
     longitude = self.request.params['longitude']
     a_keg = Keg(key_name=name, geo_location=db.GeoPt(latitude, longitude))
     a_keg.put()
     webapp2.redirect_to('keg', keg_id=name)
Example #7
0
 def post(self):
    name = self.request.params['name']
    if Tap.get_by_key_name(name):
       raise Conflict(name, webapp2.uri_for('tap', tap_id=name))
    latitude = self.request.params['latitude']
    longitude = self.request.params['longitude']
    a_tap = Tap(key_name=name, geo_location=db.GeoPt(latitude, longitude))
    a_tap.put()
    webapp2.redirect_to('tap', tap_id=name)
Example #8
0
 def check_login(self, *args, **kwargs):
     user = users.get_current_user()
     if user:
         email = user.email()
         if email in ADMINS:
             return handler(self, *args, **kwargs)
         else:
             return redirect_to("forbidden")
     else:
         return redirect_to("login")
Example #9
0
 def check_login(self, *args, **kwargs):
     user = users.get_current_user()
     if user:
         email = user.email()
         if email in ADMINS:
             return handler(self, *args, **kwargs)
         else:
             return redirect_to("forbidden")
     else:
         return redirect_to("login")
Example #10
0
			def attempt_login(self):
				lauth = self.auth
				if not lauth.get_user_by_session():
					#check to see if requiredlevel is valid
					# If handler has no login_url specified invoke a 403 error
					try:
						webapp2.redirect_to('login', abort=True,request=request,response=response,referrer_uri=base64.urlsafe_b64encode(self.request.uri))
					except (AttributeError, KeyError), e:
						webapp2.abort(403)
					return False
Example #11
0
 def func_wrapper(self, *args, **kwargs):
     user = users.get_current_user()
     if user:
         email = user.email()
         logging.info('email = {}'.format(email))
         admins = ["*****@*****.**", "*****@*****.**"]
         if email in admins:
             return func(self, *args, **kwargs)
         else:
             return webapp2.redirect_to("403")
     else:
         return webapp2.redirect_to("login")
Example #12
0
	def get(self, id=None):
		''' Handle get request; render form.
		'''
		username = getUserFromSecureCookie(self.request.cookies.get("username"))
		gem = Gem.get_by_id(int(id))

		if not username:
			return redirect_to("signin")
		elif username != dream.user.username:
			return redirect_to("home")

		self.render("editgem.html", gem=gem, Dict=None, 
			username=username)
Example #13
0
    def get(self, id=None):
        ''' Handle get request; render form.
		'''
        username = getUserFromSecureCookie(
            self.request.cookies.get("username"))
        gem = Gem.get_by_id(int(id))

        if not username:
            return redirect_to("signin")
        elif username != dream.user.username:
            return redirect_to("home")

        self.render("editgem.html", gem=gem, Dict=None, username=username)
Example #14
0
 def post(self, beer_id):
     beer = self.get_beer_or_bust(beer_id)
     beer.brewery = self.request.params.get('brewery', beer.brewery)
     beer.description = self.request.params.get('description', beer.description)
     beer.photo_url = self.request.params.get('photo_url', beer.photo_url)
     beer.style = self.request.params.get('style', beer.style)
     if 'abv' in self.request.params:
        beer.abv = float(self.request.get('abv'))
     if 'vintage' in self.request.params:
        beer.vintage = int(self.request.get('vintage'))
     if 'house_rating' in self.request.params and 'force' in self.request.GET:
         beer.house_rating = self.request.params['house_rating']
     beer.put()
     webapp2.redirect_to('beer', beer_id=beer_id)
Example #15
0
	def post(self):
		''' Respond to post request and either create a gem and redirect
		to view the gem, or, if there is a problem, re-render the
		form with all input still in place and messages indicating 
		if the input is valid or not
		'''
		username = getUserFromSecureCookie(self.request.cookies.get("username"))

		if not username:
			return redirect_to("signin")

		users = User.all()
		users.filter("username ="******"user"] = user
		messages["user"] = {"message": "User OK",
						    "validity": "valid"}

		'''
		gemDict["value"] = bleach.clean(self.request.get("value"))

		if gemDict["value"]:

			validate
		else:
			messages["value"] = {"message": 
				"Please provide value",
				"validity": "invalid"}		

		for attr in gemDict:
			if attr in messages:
				if messages[attr]["validity"] == "invalid":
					return self.render("newdream.html", gemDict=gemDict, 
						messages=messages, username=username)
		
		# set values for datastore (some cannot be string)

		# set the "point in time" user variables for this dream
		gemDict["user_property"] = user.property
		'''

		gem = Gem(**gemDict)
		gem.put()

		return redirect_to("home")
Example #16
0
    def post(self):
        ''' Respond to post request and either create a gem and redirect
		to view the gem, or, if there is a problem, re-render the
		form with all input still in place and messages indicating 
		if the input is valid or not
		'''
        username = getUserFromSecureCookie(
            self.request.cookies.get("username"))

        if not username:
            return redirect_to("signin")

        users = User.all()
        users.filter("username ="******"user"] = user
        messages["user"] = {"message": "User OK", "validity": "valid"}
        '''
		gemDict["value"] = bleach.clean(self.request.get("value"))

		if gemDict["value"]:

			validate
		else:
			messages["value"] = {"message": 
				"Please provide value",
				"validity": "invalid"}		

		for attr in gemDict:
			if attr in messages:
				if messages[attr]["validity"] == "invalid":
					return self.render("newdream.html", gemDict=gemDict, 
						messages=messages, username=username)
		
		# set values for datastore (some cannot be string)

		# set the "point in time" user variables for this dream
		gemDict["user_property"] = user.property
		'''

        gem = Gem(**gemDict)
        gem.put()

        return redirect_to("home")
Example #17
0
    def post(self):
       name = self.request.params['name']
       description = self.request.params['description']
       style = self.request.params['style']
       abv = float(self.request.params['abv'])
       brewery = self.request.params['brewery']
       if Beer.get_by_key_name(name):
          raise Conflict(name, webapp2.uri_for('beer', beer_id=name))
       new_beer = Beer(key_name=name, style=style, abv=abv, description=description,
				brewery=brewery)
       if 'vintage' in self.request.params:
          new_beer.vintage = int(self.request.get('vintage'))
       if 'photo_url' in self.request.params:
          new_beer.photo_url = photo_url
       new_beer.put()
       webapp2.redirect_to('beer', beer_id=name)
 def check_login(self, *args, **kwargs):
     if not self.request.user:
         # If handler has no login_url specified invoke a 403 error
         try:
             return redirect_to('home')
         except (AttributeError, KeyError), e:
             abort(403)
 def add_owner(self, card_id):
     if AppUser.for_user(users.get_current_user()).is_admin:
         card = ReportCard.find_by_id(int(card_id))
         card.owner_user_id.append(self.request.get('new_owner_id'))
         card.put()
         ReportCard.create(self.request.get('name'))
         return webapp2.redirect_to('card-list')
    def create(self):
        """
        Create method

        Create a new resource using posted data

        """
        # create form instance from the ResourceModel
        resource_model_form = model_form(ResourceModel)
        form = resource_model_form(self.request.POST)

        context = {
            'action': 'New',
            'form': form,
            'submit_routename': 'resource.create'
        }

        # since this method is only called from a post,
        # we do not need to check for request.method == "POST"
        # if self.form.validate() returns true, then save
        # the data
        if form.validate():
            logging.debug('Form Validated!')
            entity = ResourceModel()
            # push form values into model
            form.populate_obj(entity)
            # save to data store
            key = entity.put()
            # redirect to index and/or edit form with new id
            logging.debug('key={0}'.format(key))
            # redirect to the edit page for the created id
            return webapp2.redirect_to('resource.edit', id=key.id())

        # the form did not validate, redisplay with errors
        return self.render_response('resource.html', context)
Example #21
0
def users_delete(request, user_id):
    """Delete user from datastore
    """
    user = users.get(user_id)
    if user is not None:
        user_email = user.email
        user.key.delete()
        request.session().add_flash('User deleted: {0}.'.format(user_email), level='danger')
    return webapp2.redirect_to('users-list')
Example #22
0
	def get(self):
		''' Handle get request and render form to sign in
		'''
		username = getUserFromSecureCookie(self.request.cookies.get("username"))

		if username:
			return redirect_to("home")

		self.render("signin.html", values=None, messages=None, username=None)
Example #23
0
    def get(self):
        ''' Handle get request and render form to sign in
		'''
        username = getUserFromSecureCookie(
            self.request.cookies.get("username"))

        if username:
            return redirect_to("home")

        self.render("signin.html", values=None, messages=None, username=None)
Example #24
0
    def post(self, id=None):
        ''' Handle post request; redirect to view the dream with changes if 
		successful, re-render form with validity messages if unsuccessful.
		'''
        username = getUserFromSecureCookie(
            self.request.cookies.get("username"))
        dream = Dream.get_by_id(int(id))

        if not username:
            return redirect_to("signin")
        elif username != dream.user.username:
            return redirect_to("home", page=1)
        '''
		Same validation as new gem except for only editable parts
		gem.edited_property = gemDict["edited_property"]
		gem.put()
		'''

        return redirect_to("home")
Example #25
0
    def _arguments_wrapper(request, *args, **kwargs):

        # fail fast if the user's not an admin
        request.user = aeusers.get_current_user()
        if not aeusers.is_current_user_admin():
            return webapp2.redirect_to(ADMIN_UNAUTHED_URL)

        # get a user record from the datastore, creating one if necessary
        request.beardo_user = users.get_or_create(request.user)
        return view_method(request, *args, **kwargs)
Example #26
0
 def check_login(self, *args, **kwargs):
     user = users.get_current_user()
     if user:
         email = user.email()
         if email in emails:
             return handler(self, *args, **kwargs)
         else:
             return redirect_to("forbidden")
     else:
         return redirect(users.create_login_url("/"))
Example #27
0
	def post(self, id=None):
		''' Handle post request; redirect to view the dream with changes if 
		successful, re-render form with validity messages if unsuccessful.
		'''
		username = getUserFromSecureCookie(self.request.cookies.get("username"))
		dream = Dream.get_by_id(int(id))

		if not username:
			return redirect_to("signin")
		elif username != dream.user.username:
			return redirect_to("home", page=1)

		'''
		Same validation as new gem except for only editable parts
		gem.edited_property = gemDict["edited_property"]
		gem.put()
		'''

		return redirect_to("home")
Example #28
0
	def get(self):
		''' Respond to get request and render the new Gem form
		'''
		username = getUserFromSecureCookie(self.request.cookies.get("username"))

		if not username:
			return redirect_to("signin")

		user = User.all().filter("username ="******"newgem.html", username=username)
 def test_redirect_to(self):
     app = webapp2.WSGIApplication([
         webapp2.Route('/home', handler='', name='home'),
     ])
     req = webapp2.Request.blank('/')
     req.app = app
     app.set_globals(app=app, request=req)
     rsp = webapp2.redirect_to('home', _code=301, _body='Weee')
     self.assertEqual(rsp.status_int, 301)
     self.assertEqual(rsp.body, 'Weee')
     self.assertEqual(rsp.headers.get('Location'), 'http://localhost/home')
Example #30
0
    def post(self):
        task_count = self.request.POST.get("task_count")
        batch_size = int(self.request.POST.get("batch_size", 0) or 0)
        task_run_time = self.request.POST.get("task_run_time")
        use_batcher = self.request.POST.get("use_batcher")
        queue = self.request.POST.get("queue_name")

        if not task_count:
            return webapp2.redirect_to('home', message="No tasks inserted.")

        task_count = int(task_count)

        job_id = uuid.uuid4().hex
        job = Job(id=job_id, task_count=task_count, queue=queue or "")
        job.put()

        Async(insert_tasks,
              args=(job_id, batch_size, task_count, task_run_time, use_batcher,
                    queue)).start()

        return webapp2.redirect_to('job_detail', job_id=job_id)
Example #31
0
    def test_redirect_to(self):
        app = webapp2.WSGIApplication([
            webapp2.Route("/home", handler="", name="home"),
        ])
        req = webapp2.Request.blank("/")
        req.app = app
        app.set_globals(app=app, request=req)

        rsp = webapp2.redirect_to("home", _code=301, _body="Weee")
        self.assertEqual(rsp.status_int, 301)
        self.assertEqual(rsp.body, b"Weee")
        self.assertEqual(rsp.headers.get("Location"), "http://localhost/home")
Example #32
0
    def test_redirect_to(self):
        app = webapp2.WSGIApplication([
            webapp2.Route('/home', handler='', name='home'),
        ])
        req = webapp2.Request.blank('/')
        req.app = app
        app.set_globals(app=app, request=req)

        rsp = webapp2.redirect_to('home', _code=301, _body='Weee')
        self.assertEqual(rsp.status_int, 301)
        self.assertEqual(rsp.body, 'Weee')
        self.assertEqual(rsp.headers.get('Location'), 'http://localhost/home')
Example #33
0
    def get(self):
        ''' Respond to get request and render the new Gem form
		'''
        username = getUserFromSecureCookie(
            self.request.cookies.get("username"))

        if not username:
            return redirect_to("signin")

        user = User.all().filter("username ="******"newgem.html", username=username)
Example #34
0
    def get(self):
        user = UserProfile.get_current_user()

        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return

        now = datetime.datetime.now().date();
        instance = OxInstance(state = 'open',
                              created = now,
                              players = [user.key()])
        instance.put()
        return webapp2.redirect_to('lobby')
Example #35
0
 def post(self, user_id):
     a_user = User.get_by_key_name(user_id)
     if not a_user:
        print 'OMG'
        return # raise webob.exc.HTTPNotFound()
     type = self.request.GET.get('account_type')
     id = self.request.GET.get('account_id')
     persona = Persona(key_name='%s-%s' % (a_user.key(), type), id=id, type=type, parent=a_user)
     persona.put()
     if not type in a_user.personas:
        a_user.personas.append(type)
        a_user.put()
     return webapp2.redirect_to('personas', user_id=user_id)
Example #36
0
def users_profile(request, user_id):
    """User profile page. Non-admin users can only view their own profile.
    """
    # normalize user ID
    ouid = user_id
    if not aeusers.is_current_user_admin() and not user_id == 'me':
        return webapp2.redirect_to('users-profile', user_id='me')
    if user_id == 'me':
        user_id = request.user.user_id()

    user = users.get(user_id)
    keys = ssh_keys.get_all_for_user(user.key.id())
    return {'user_id': ouid, 'user': user, 'ssh_keys': keys}
Example #37
0
def ssh_keys_delete(request, user_id, ssh_key_id):
    """Allow users to delete SSH keys.
    """
    # normalize user ID
    ouid = user_id
    if not aeusers.is_current_user_admin() and not user_id == 'me':
        return webapp2.redirect_to('users-profile', user_id='me')
    if user_id == 'me':
        user_id = request.user.user_id()
    user = users.get(user_id)

    # fetch key from datastore
    ssh_key = ssh_keys.get(ssh_key_id)

    # check if the user has permission to delete this key
    if not aeusers.is_current_user_admin() and not ssh_key.user == user.key:
        return webapp2.redirect_to('users-profile', user_id=ouid)

    # delete the key from the datastore
    ssh_keys.delete(ssh_key_id)
    session = request.session()
    session.add_flash('SSH key deleted: {0}'.format(ssh_key.title), level='success')
    return webapp2.redirect_to('users-profile', user_id=ouid)
Example #38
0
	def get(self):
		''' Handle get request and render register form
		'''
		'''
		redirect to homepage if signed in
		'''
		# countries = sorted(COUNTRIES, key=lambda s: s.lower())
		username = getUserFromSecureCookie(self.request.cookies.get("username"))

		if username:
			return redirect_to("home")

		self.render("register.html", countries=countries, 
			values=None, messages=None)
Example #39
0
    def get(self):
        gtoken = self.request.cookies.get('gtoken')
        if gtoken:
            gitkit_user = gitkit_instance.VerifyGitkitToken(gtoken)
        else:
            return webapp2.redirect_to('widget', mode='select')
        i = Identity()
        i = i.get_or_insert(gitkit_user.user_id, name=gitkit_user.name,
                            email=gitkit_user.email, provider_id=gitkit_user.provider_id)
        template_values = {'i': i}

        template = jinja_environment.get_template('submit_key.htm')

        self.response.out.write(template.render(template_values))
Example #40
0
    def post(self):
        task_count = self.request.POST.get("task_count")
        batch_size = int(self.request.POST.get("batch_size", 0) or 0)
        task_run_time = self.request.POST.get("task_run_time")
        use_batcher = self.request.POST.get("use_batcher")
        queue = self.request.POST.get("queue_name")

        if not task_count:
            return webapp2.redirect_to(
                'home', message="No tasks inserted.")

        task_count = int(task_count)

        job_id = uuid.uuid4().hex
        job = Job(id=job_id, task_count=task_count, queue=queue or "")
        job.put()

        Async(
            insert_tasks,
            args=(job_id, batch_size, task_count, task_run_time, use_batcher,
                  queue)
        ).start()

        return webapp2.redirect_to('job_detail', job_id=job_id)
 def save(self, eval_id):
     eval = Evaluation.find_by_id(int(eval_id))
     if eval.card.is_authorized():
         for cat in eval.card.categories():
             for item in cat.items():
                 val = self.request.get('item_%s_score' % item.key().id())
                 if val is not None:
                     EvalItemData.create_or_update(item.key().id(), int(eval_id), val)
         for line in eval.card.text_lines():
             val = self.request.get('text_%s_value' % line.key().id())
             if val is not None:
                 TextLineData.create_or_update(line.key().id(), int(eval_id), val)
         val = self.request.get('comments')
         if val is not None:
             CommentData.create_or_update(int(eval_id), val)
         return webapp2.redirect_to('eval-fill', eval_id=int(eval_id))
Example #42
0
    def get(self):
        ''' Handle get request and render register form
		'''
        '''
		redirect to homepage if signed in
		'''
        # countries = sorted(COUNTRIES, key=lambda s: s.lower())
        username = getUserFromSecureCookie(
            self.request.cookies.get("username"))

        if username:
            return redirect_to("home")

        self.render("register.html",
                    countries=countries,
                    values=None,
                    messages=None)
Example #43
0
    def post(self):

        email = cgi.escape(self.request.get('email'))

        if email is None or email == '':
            return self.error(message="Valid email not provided")

        # Check for wild card
        if '*' in email:
            wild_card = email.replace('*', '')
            site_config = models.SiteConfig.get_or_create(get_release_name(self.request))
            if wild_card not in site_config.wild_card_domains:
                site_config.wild_card_domains.append(wild_card)
                site_config.put()
        else:
            # Add user
            new_user = models.AuthorizedUser.create(email, get_release_name(self.request))

        return webapp2.redirect_to('admin-index')
Example #44
0
 def post(self):
     event_name = self.request.get('name')
     if event_name:
         event = model.Event(name=event_name)
         event.put()
         return webapp2.redirect_to('event', event_id=event.key().id())
Example #45
0
 def get(self):
     return webapp2.redirect_to("settings_config")
Example #46
0
    def post(self):
        ''' Handle post request and create new user, redirecting to home page.
		If there is a problem, re-render form with all input still in place
		and messages to user about input validity.
		'''
        username = getUserFromSecureCookie(
            self.request.cookies.get("username"))

        if username:
            return redirect_to("home")

        userDict = {}
        messages = {}
        '''
		userDict["value"] = bleach.clean(self.request.get("value"))

		if userDict["value"]:

			validate
		else:
			messages["value"] = {"message": 
				"Please provide value",
				"validity": "invalid"}		

		for attr in userDict:
			if attr in messages:
				if messages[attr]["validity"] == "invalid":
					return self.render("newdream.html", userDict=userDict, 
						messages=messages, username=username)
		
		# set values for datastore (some cannot be string)

		# set the "point in time" user variables for this dream
		userDict["user_property"] = user.property

		if hasInvalid:

			# countries = sorted(COUNTRIES, key=lambda s: s.lower())

			return self.render("register.html", countries=countries,
				userDict=userDict, messages=messages)

		# prepare arguments for User constructor
		userDict.pop("verifypassword", None)
		userDict["password"] = saltedpasshash

		userDict["lc_username"] = userDict["username"].lower()

		user = User(**userDict)
		user.put()

		# if more than one with this email or user name, delete this one
		# and return invalid.  datastore support for unique entity values 
		# is not intuitive
		duplicate = False

		users = User.all()
		users.filter("username ="******"username"] = {"message": "Name already taken",
									"validity": "invalid"}
				user.delete()
				duplicate = True
				break

		users = User.all()
		users.filter("email =", user.email)
		numSameEmail = 0
		for u in users.run():
			numSameEmail += 1
			if numSameEmail > 1:
				messages["email"] = {"message": "Email already in use",
									 "validity": "invalid"}
				user.delete()
				duplicate = True
				break

		if duplicate:

			# countries = sorted(COUNTRIES, key=lambda s: s.lower())

			return self.render("register.html", countries=countries,
				userDict=userDict, messages=messages)

		username_cookie_val = make_secure_val(user.username)
		'''

        response = redirect_to("home")
        '''
		response.set_cookie("username", username_cookie_val)
		'''
        return response
Example #47
0
    def get(self):
        ''' Handle get request; redirect to signin page, delete signin cookie
		'''
        response = redirect_to("signin")
        response.set_cookie("username", "")
        return response
Example #48
0
    def post(self):
        ''' Handle post request, signing user in and redirecting to homepage
		if successful and re-rendering sign-in page with validitiy messages
		if unsuccessful.
		'''
        username = getUserFromSecureCookie(
            self.request.cookies.get("username"))

        if username:
            return redirect_to("home")

        name = bleach.clean(self.request.get("name"))
        password = bleach.clean(self.request.get("password"))

        # holds message for user about input and
        # whether input is valid or invalid
        messages = {}

        if name:
            users = User.all()
            users.filter("username ="******"name"] = {"message": "", "validity": "valid"}
                if password:
                    saltedpasshash = user.password
                    if correct_pw(user.username, password, saltedpasshash):
                        messages["password"] = {
                            "message": "",
                            "validity": "valid"
                        }
                    else:
                        messages["password"] = {
                            "message": "Password incorrect",
                            "validity": "invalid"
                        }
                else:
                    messages["password"] = {
                        "message": "Enter password",
                        "validity": "invalid"
                    }
            else:
                messages["name"] = {
                    "message": "Username does not exist",
                    "validity": "invalid"
                }
                messages["password"] = {"message": "", "validity": "invalid"}
        else:
            messages["name"] = {
                "message": "Please provide a name",
                "validity": "invalid"
            }
            messages["password"] = {"message": "", "validity": "invalid"}

        values = {}
        values["name"] = name
        values["password"] = password

        for field in messages:
            if messages[field]["validity"] == "invalid":
                return self.render("signin.html",
                                   values=values,
                                   messages=messages,
                                   username=None)

        username_cookie_val = make_secure_val(user.username)

        response = redirect_to("home")
        response.set_cookie("username", username_cookie_val)
        return response