def create(self,name=None,description=None,image=None, image_url=None,action=None): if action: if not name: raise e.Validation('Name must be defined') if image is not None and len(image.filename): cherrypy.log('has image: %s' % image.filename) image_path = save_form_data(image, cherrypy.config.get('image_root'), 'character_') elif image_url: cherrypy.log('has image url') try: image_path = _save_form_data(urlopen(image_url).read(), cherrypy.config.get('image_root'), image_url.rsplit('.',1)[-1], 'character_') except: cherrypy.log('bad download') image_path = None show = m.Show(name=name, description=description, picture_path=os.path.basename(image_path)) m.session.add(show) m.session.commit() redirect('/show/%s'%show.id)
def pretend(user, url='/'): if is_logged_in() and is_admin(): session['user'] = user.id session['username'] = user.username session.save() if url: h.redirect(url)
def post(self): user = users.get_current_user() person = login.is_roommate_account_initialized(user) home = Home.query(Home.key == person.home_key).fetch()[0] home_key = home.key chore_name = self.request.get('chore_name') duration = int(self.request.get('days')) cur_time = time.time() duration = duration * 24 * 60 * 60 end_time = cur_time + duration workers = [] workers_names = [] for p in home.occupants: if self.request.get(p) == 'on': workers.append(p) per = Person.query().filter( Person.user_id == p).fetch()[0].name workers_names.append(per) chore = Chore(home_key=home_key, workers_names=workers_names, chore_name=chore_name, duration=duration, end_time=end_time, workers=workers) chore.put() render.render_page(self, 'choreCreated.html', 'Chore Created') helpers.redirect(self, '/dashboard', 1000)
def post(self): user = users.get_current_user() if user: # Retrieve data from form title = self.request.get('title') content = self.request.get('content') days = int(self.request.get('days')) hours = int(self.request.get('hours')) # Convert 'on' or 'off' from checkbox to True or False important_original = self.request.get('important') if important_original == 'on': important = True else: important = False # Retrieve person and home objects person = login.is_roommate_account_initialized(user) person_name = Person.query().filter( Person.user_id == person.user_id).fetch()[0].name home = Home.query().filter(Home.key == person.home_key).fetch() # Calculate expiration time cur_time = time.time() expir_time = cur_time + days * 24 * 60 * 60 + hours * 60 * 60 # Create and put new sticky new_sticky = Sticky(title=title, content=content, important=important, author=person_name, home_key=person.home_key, expiration=expir_time) new_sticky.put() render.render_page(self, 'stickyCreated.html', "Sticky Created") helpers.redirect(self, '/dashboard', 1000)
def check_active_login(skip=False,login=True): """ checks that there is an active user or sends back a 403 """ cherrypy.log('checking active login %s %s' % (skip,login)) try: if skip: return True # make sure there is a handle if not cherrypy.session.get('user_handle'): error(403) # make sure there's a hash in the session if not cherrypy.session.get('user_hash'): error(403) # find the user and check the hash against his password user = m.User.get_by(handle=cherrypy.session.get('user_handle')) if not user: error(403) if hash_password(user.password) != cherrypy.session.get('user_hash'): error(403) except HTTPError: if login: redirect('/login') else: raise return user
def stop_pretending(url='/'): if is_logged_in(): session['user'] = session['real_user'] session['username'] = session['real_username'] session.save() if url: h.redirect(url)
def remove_utility(self) -> None: """Remove a utility and all associated bills.""" print("What utility would you like to remove?") for utility in self.utilities(): print(f"{utility[0].upper() + utility[1:]}") intent = input_handler( self, prompt=( "WARNING: removing a utility " "will also remove all bills associated with that utility!" ), ) removal_intent = input_handler( self, prompt=f"Are you sure you want to remove {intent}?", boolean=True, ) if removal_intent: self.db.remove_utility(intent) redirect(self, message=f"{intent} has been removed.") else: redirect(self, message=None)
def check_unpaid_bills(self, utility: str) -> None: """Print all unpaid bills under a given utility.""" records = self.db.get_utility_record(utility) if not records: redirect( self, message=f"There are no bills in {utility}.", destination=Destinations.UTILITY_MENU, utility=utility, ) checker = False for entry in records: if not entry.paid: checker = True print(entry) if not checker: redirect( self, message=f"You have no unpaid bills in {utility}.", destination=Destinations.UTILITY_MENU, utility=utility, ) self.utility_menu(utility, display=False)
def createGenDescVal(request, rxn_id, descValClass, descValFormClass, infoHeader, createNext): """A generic view function to create descriptor values for reactions.""" descVals = descValClass.objects.filter(reaction__id=rxn_id).filter( descriptor__calculatorSoftware="manual") initialDescriptors = descValClass.descriptorClass.objects.filter( calculatorSoftware='manual').exclude(id__in=set(descVal.descriptor.id for descVal in descVals)) descValFormset = modelformset_factory(model=descValClass, form=descValFormClass( rxn_id), can_delete=('creating' not in request.GET), extra=initialDescriptors.count()) if descValClass.descriptorClass.objects.filter(calculatorSoftware="manual").exists(): if request.method == "POST": formset = descValFormset( queryset=descVals, data=request.POST, prefix=request.resolver_match.url_name) # this weird prefix is caused by the generic nature of this function and the neccessity to namespace # the different form elements in the formsets used in the edit # reaction view. if formset.is_valid(): descVals = formset.save() descValClass.objects.filter( id__in=[dv.id for dv in formset.deleted_objects]).delete() messages.success( request, 'Reaction descriptor details successfully updated') if createNext is None or 'creating' not in request.GET: return redirect('editReaction', rxn_id) else: return redirect(createNext, rxn_id, params={'creating': True}) else: formset = descValFormset(queryset=descVals, initial=[ {'descriptor': descriptor.id} for descriptor in initialDescriptors], prefix=request.resolver_match.url_name) return render(request, 'reaction_detail_add.html', {'formset': formset, 'rxn_id': rxn_id, 'info_header': infoHeader}) elif createNext is None or 'creating' not in request.GET: return redirect('editReaction', rxn_id) else: return redirect(createNext, rxn_id, params={'creating': True})
def banner_delete(banner_id): try: banner = Banner.get(Banner.banner_id == banner_id) banner.delete_instance() redirect('/banners') except DoesNotExist: abort(404)
def update(self,handle=None,email=None,password1=None, password2=None,action=None,user_id=None): """ users can only edit themselves """ # if they don't supply the user id, we are editing current user if user_id: user = m.User.get(user_id) else: user = cherrypy.request.user try: if action: # update what we were passed if handle and user.handle != handle: if m.User.get_by(handle=handle): raise e.ValidationException('Handle taken') user.handle = handle if email: cherrypy.log('email:%s' % email) user.email_address = email if password1: if password1 != password2: raise e.ValidationException('Passwords do not match') user.password = password1 # save our changes m.session.commit() # take a look redirect('/user/%s' % user.id) except e.ValidationException, ex: add_flash('error','%s' % ex)
def login(self, username=None, password=None, action=None, endpoint=None, new_user=None): """ prompts the user to login, creates the user if it doesn't exist """ # see if they are trying to login / create user if action or username or password: # if they didn't provide both username and password bounch them if not password or not username: error(403) add_flash("error", "Your missing something!") # if they gave us a username and a password then they are # trying to login if not login_user(username, password): # fail ! error(403) add_flash("error", "Your login has failed!") else: # yay, success. push them to their next point if endpoint: redirect(endpoint) # or home else: redirect("/") return render("/login_front.html", username=username)
def login(): if 'back' in request.query: back = request.query['back'] else: back = '/' if app.current_user is not None: app.flash(u'Вийдіть з поточної сесії, щоб увійти під іншим акаунтом') redirect(back) if request.method == 'POST': try: user = User.get(User.mail == post_get('email')) except DoesNotExist: app.flash(u'Немає такого користувача') else: if user.user_password == User.encode_password( post_get('password')): app.flash(u'Ви успішно увійшли') app.login(user) redirect(back) else: app.flash(u'Невірний пароль') template = env.get_template('user/login.html') return template.render()
def post_edit(post_id): if request.method == 'GET': try: post = Post.get(Post.post_id == post_id) # todo: get not deleted except Post.DoesNotExist: abort(404) all_categories = Category.select() template = env.get_template('post/edit.html') return template.render(item=post, categories=all_categories, submit_button=u'Оновити') elif request.method == 'POST': post = Post.get(Post.post_id == post_id) post.category = post_get('category_id') post.post_text = post_get('text') post.title = post_get('title') post.draft = bool(int(post_get('draft'))) # zero int is False post.language = post_get('language') new_tags = post_get('tags') old_tags = Tag.select().join(Tag_to_Post)\ .where(Tag_to_Post.post_id == post_id) remove_tags(old_tags, new_tags, post_id) add_new_tags(new_tags, post_id) post.save() app.flash(u'Статтю успішно оновлено') redirect('/post/' + str(post_id))
def banners(): template = env.get_template('banners.html') if request.method == 'GET': all_banners = Banner.select() return template.render({'banners': all_banners}) elif request.method == 'POST': banner_img = request.files.get('banner_img') banners_folder = static_path('img/banners/') file_path = os.path.join(banners_folder, banner_img.filename) # photo_file.save('/img/gallery/') # new Bottle with open(file_path, 'wb') as open_file: open_file.write(banner_img.file.read()) link = post_get('link') parsed_link = urlparse(link) if parsed_link.scheme == '': link = 'http://{0}'.format(link) if not parsed_link.path or parsed_link.path == '#': link = '#' banner = Banner.create(desc=post_get('desc'), link=link, img=banner_img.filename) app.flash(u'+1 новий банер') redirect('/banners')
def photo_delete(photo_id): try: photo = Photo.get(Photo.photo_id == photo_id) photo.delete_instance() redirect('/gallery_add') except DoesNotExist: abort(404)
def quote_delete(quote_id): try: quote = Quote.get(Quote.quote_id == quote_id) quote.delete_instance() app.flash(u'Цитата видалена', 'success') redirect('/quote/add') except DoesNotExist: abort(404)
def sp_delete(sp_id): try: sp = StaticPage.get(StaticPage.id == sp_id) sp.delete_instance() app.flash(u'Сторінка видалена', 'success') redirect('/sp/add') except DoesNotExist: abort(404)
def category_add(): if request.method == 'GET': all_categories = Category.select() template = env.get_template('post/category_add.html') return template.render(categories=all_categories) if request.method == 'POST': new_category = Category.create(category_name=post_get('category_name')) app.flash(u'Нова категорія була успішно додана') redirect('/category/add')
def post_renew(post_id): try: post = Post.get(Post.post_id == post_id) post.date_updated = datetime.now() post.save() app.flash(u'Стаття актуалізована') redirect('/post/%s' % post_id) except DoesNotExist: abort(404)
def wrapper(*args, **kwargs): if app.current_user is not None: r = Role.get(Role.role == role) if app.current_user.role.level >= r.level: return func(*args, **kwargs) app.flash(u'У Вас недостатньо прав для перегляду') redirect() app.flash(u'Увійдіть, щоб переглянути дану сторінку') redirect('/login?back=' + request.path)
def post_delete(post_id): try: post = Post.get(Post.post_id == post_id) post.deleted = True post.save() app.flash(u'Статтю видалено', 'success') redirect() except Post.DoesNotExist: abort(404)
def category_delete(category_id): try: category = Category.get(Category.category_id == category_id) except DoesNotExist: abort(404) try: category.delete_instance() except IntegrityError as e: app.flash(u'Категорія містить статті. Неможливо видалити', 'error') redirect('/category/add')
def get(self): user = users.get_current_user() if user: person = login.is_roommate_account_initialized(user) if person: render.render_page(self, 'createSticky.html', "Create a Sticky") else: helpers.redirect(self, '/', 0) else: helpers.redirect(self, '/', 0)
def get(self): user = users.get_current_user() if user: try: #Add mini-form to ask if stickies should be deleted, replace True with var name helpers.removeFromRoom( self, user) #Add confirmation for leaving room logging.info("No Exception Thrown") except AttributeError: logging.info("AttributeError thrown") helpers.redirect(self, '/newJoinHome', 1000) else: helpers.redirect(self, '/', 0)
def post(self): user = users.get_current_user() if user: person = login.is_roommate_account_initialized(user) sticky_title = self.request.get('sticky_title') sticky_content = self.request.get('sticky_content') sticky = Sticky.query().filter( Sticky.content == sticky_content, Sticky.title == sticky_title, Sticky.author == person.user_id).fetch() sticky = sticky[0] sticky.key.delete() render.render_page(self, "stickyDeleted.html", "Sticky Deleted!") helpers.redirect(self, '/dashboard', 1000)
def vote(self,id,direction): character = m.Character.get(id) if not character: raise e.Validation('Could not find character') if direction.lower() == 'liberal': character.liberal_vote_count += 1 elif direction.lower() == 'conservative': character.conservative_vote_count += 1 else: raise e.Validation('What is %s?' % direction) character.total_vote_count += 1 m.session.commit() redirect('/character/%s' % character.id)
def get(self): user = users.get_current_user() if user: person = login.is_roommate_account_initialized(user) if person: render_data = helpers.getDashData(self, person) render.render_page_with_data(self, 'dashboard.html', person.name + "'s Dashboard", render_data) else: helpers.redirect(self, '/', 0) else: helpers.redirect(self, '/', 0)
def update_account(): user = app.current_user update_form = UserEditForm(request.POST, user) if update_form.validate(): # user.update(**update_form.data).execute() update_form.populate_obj(user) print(update_form.data) user.save() print(user.picture) app.flash(u'Дані успішно оновлено') else: app.flash(u'Incorrect somtethisd') redirect('/account') # without return redirect because of raise inside
def get(self): # Get current google account that is signed in user = users.get_current_user() # Check if there is a user signed in if user: person = login.is_roommate_account_initialized(user) if person: if person.home_key: helpers.redirect(self, '/', 0) render.render_page_without_header(self, 'newJoinHome.html', 'Join a Room') # If there is no user, prompt client to login else: helpers.redirect(self, '/', 0)
def get(self): # Get current google account that is signed in user = users.get_current_user() # Check if there is a user signed in if user: person = login.is_roommate_account_initialized(user) if person: None # If there is no user, prompt client to login else: helpers.redirect(self, '/', 0)
def create(self,content=None,title=None,rating=None,media_id=None, tags=[], action=None): """ create a new comment """ try: if action: media = m.Media.get(media_id) # must have something if not content and not title and not rating: add_flash('error', 'Must have @ least a comment / title or rating') # rating must be between 1 and 5 elif rating and not rating.isdigit() or 0> int(rating) >5: add_flash('error','invalid rating!') # make sure our media is good elif media_id and not media: add_flash('error',"Sry, I can't find the media!") else: # create our new comment comment = m.Comment(title=title, rating=rating, content=content, media=media, user=cherrypy.request.user) # add our tags for tag in tags: comment.add_tag_by_name(tag) # add the comment to the db m.session.add(comment) m.session.commit() # let the user know it worked add_flash('info','Comment successfully added!') # send them to the page for the media they # commented on if media: redirect('/media/%s' % media.id) else: redirect('/comment/%s' % comment.id) except Exception, ex: raise # woops, let the user know we had an error add_flash('error','%s' % ex)
def post(self): user = users.get_current_user() person = login.is_roommate_account_initialized(user) home = Home.query(Home.key == person.home_key).fetch()[0] bill_name = self.request.get('bill_name') payer_id = self.request.get('payer') payer_name = Person.query().filter( Person.user_id == payer_id).fetch()[0].name home_key = home.key bill = Bills(bill_name=bill_name, home_key=home_key, payer_id=payer_id, payer_name=payer_name) bill.put() render.render_page(self, 'billsCreated.html', 'Bill Created') helpers.redirect(self, '/dashboard', 1000)
def graph(self,id,**kwargs): cherrypy.log('graph: %s' % id) character = m.Character.get(id) if not character: raise e.Validation('Could not find character') src = render('/characters/graph.html',character=character).strip() return redirect(src)
def login_action(req): # get form fields challenge = req.form.get('challenge') uid = req.form.get('uid') response = req.form.get('response') # validate the response auth = h.auth(req) v = auth.validate(challenge, uid, response) if v: # find the user in the user base (not the same as the credential store) userbase = h.userbase(req) user = userbase.getuser(uid) # user does not exist yet, create it if user is None: user = userbase.newuser(uid) # set the user session if user is not None: usersession = h.usersession(req) usersession.setuser(user) return h.redirect('/')
def create(self,name=None,show_id=None,description=None, image=None,image_url=None,action=None): if action: if not name: raise e.Validation('Name required') if not show_id: raise e.Validation('Show required') if not description: raise e.Validation('Description required') show = m.Show.get(show_id) if not show: raise e.Validation('Show not found') if image is not None and len(image.filename): cherrypy.log('has image: %s' % image.filename) image_path = save_form_data(image, cherrypy.config.get('image_root'), 'character_') elif image_url: cherrypy.log('has image url') try: image_path = _save_form_data(urlopen(image_url).read(), cherrypy.config.get('image_root'), image_url.rsplit('.',1)[-1], 'character_') except: cherrypy.log('bad download') image_path = None else: image_path = None cherrypy.log("image_path: %s" % image_path) character = m.Character(name=name, show=show, description=description, picture_path=os.path.basename(image_path)) m.session.add(character) m.session.commit() redirect('/character/%s' % character.id) return targs(shows=m.Show.query.all())
def get(self): user = users.get_current_user() if user: person = login.is_roommate_account_initialized(user) if person: home = Home.query(Home.key == person.home_key).fetch()[0] rotation_list = [] for user_id in home.occupants: p = Person.query().filter( Person.user_id == user_id).fetch()[0] rotation_list.append(p) data = {'rotation_list': rotation_list} render.render_page_with_data(self, 'chores.html', 'Create a Chore', data) else: helpers.redirect(self, '/', 0) else: helpers.redirect(self, '/', 0)
def create(self,handle=None,email=None,password=None,action=None): """ create a new user """ try: if action: # user has got to have a password + handle if not password or not handle: raise e.ValidationException('Must supply password and handle') # create our user user = m.User(handle=handle,email=email,password=password) # add it to the db and push the user to it's page m.session.add(user) m.session.commit() redirect('/user/%s' % user.id) except e.ValidationException, ex: add_flash('error','%s' % ex)
def post(self): user = users.get_current_user() if user: person = login.is_roommate_account_initialized(user) chore_home_key = person.home_key chore_name = self.request.get('chore_name') chore_end_time = float(self.request.get('chore_end_time')) chore = Chore.query().filter( Chore.chore_name == chore_name, Chore.home_key == chore_home_key).fetch() chore = chore[0] if chore.completed: chore.completed = False else: chore.completed = True chore.put() render.render_page(self, "choreCompleted.html", "Chore Completed") helpers.redirect(self, '/dashboard', 1000)
def get(self): user = users.get_current_user() if user: person = login.is_roommate_account_initialized(user) if person: home = Home.query(Home.key == person.home_key).fetch()[0] possible_payers = [] for user_id in home.occupants: p = Person.query().filter( Person.user_id == user_id).fetch()[0] possible_payers.append(p) data = {'payers': possible_payers} render.render_page_with_data(self, 'bills.html', 'Assign a Bill', data) else: helpers.redirect(self, '/', 0) else: helpers.redirect(self, '/', 0)
def post(self): user = users.get_current_user() if user: person = login.is_roommate_account_initialized(user) sticky_title = self.request.get('sticky_title') sticky_content = self.request.get('sticky_content') sticky_author = self.request.get('sticky_author') sticky = Sticky.query().filter( Sticky.content == sticky_content, Sticky.title == sticky_title).fetch() sticky = sticky[0] if sticky.completed: sticky.completed = False else: sticky.completed = True sticky.put() render.render_page(self, "stickyToggle.html", "Sticky Completed Toggled") helpers.redirect(self, '/dashboard', 1000)
def post_add(): if request.method == 'GET': all_categories = Category.select() template = env.get_template('post/add.html') return template.render(categories=all_categories) if request.method == 'POST': post = Post.create( category=post_get('category_id'), post_text=post_get('text'), title=post_get('title'), user=app.current_user.user_id, date_posted=datetime.now(), draft=int(post_get('draft')) == 1, language=post_get('language') ) post_id = post.post_id post.save() add_new_tags(post_get('tags'), post_id) redirect('/post/' + str(post_id))
def login(self,username=None,password=None,action=None,endpoint=None, new_user=None): """ prompts the user to login, creates the user if it doesn't exist """ # see if they are trying to login / create user if action or username or password: # if they didn't provide a password than we need to # either create a new user or prompt them for pass if one exists if not password: user = m.User.get_by(handle=username) if user: return render('/login_password.html',username=username) else: return render('/login_new_user.html',username=username) # if we are creating a new user, do so if new_user == 'true': user = m.User(handle=username) user.password = password m.session.commit() # if they gave us a username and a password then they are # trying to login if not login_user(username,password): # fail ! add_flash('error','Your login has failed!') else: # yay, success. push them to their next point if endpoint: redirect(endpoint) # or home else: redirect('/') return render('/login_front.html',username=username)
def createReaction(request): """A view designed to create performed reaction instances.""" if request.method == "POST": perfRxnForm = PerformedRxnForm(request.user, data=request.POST) if perfRxnForm.is_valid(): rxn = perfRxnForm.save() messages.success(request, "Reaction Created Successfully") return redirect('addCompoundDetails', rxn.id, params={'creating': True}) else: perfRxnForm = PerformedRxnForm(request.user) return render(request, 'reaction_create.html', {'reaction_form': perfRxnForm})
def gallery(): template = env.get_template('gallery_add.html') if request.method == 'GET': photos = Photo.select() return template.render(photos=photos) elif request.method == 'POST': photo_file = request.files.get('photo') file_ext = os.path.splitext(photo_file.filename)[1] gallery_folder = static_path('img/gallery/') f_name = generate_filename(prefix='photo', suffix=file_ext) file_path = os.path.join(gallery_folder, f_name) # photo_file.save('/img/gallery/') # new Bottle with open(file_path, 'wb') as open_file: open_file.write(photo_file.file.read()) photo = Photo.create(desc=post_get('desc'), photo=f_name) app.flash(u'Фото успішно додане') redirect('/gallery_add')
def get(self): user = users.get_current_user() if user: person = login.is_roommate_account_initialized(user) if person: if (person.do_not_disturb): person.do_not_disturb = False data = {'dnd_state': 'Do not disturb is off.'} person.put() else: person.do_not_disturb = True data = {'dnd_state': 'DO NOT DISTURB!'} person.put() sender_address = 'Roommates <*****@*****.**>' occupants = Home.query().filter( Home.key == person.home_key).fetch()[0].occupants for occupant in occupants: receipient = Person.query().filter( Person.user_id == occupant).fetch()[0] receipient = receipient.email_address if receipient == person.email_address: logging.info(occupant) else: helpers.send_dnd_mail(sender_address, person.name, receipient) render.render_page_with_data(self, 'doNotDisturb.html', "Do Not Disturb Toggle", data) helpers.redirect(self, '/dashboard', 1000) else: helpers.redirect(self, '/', 0) else: helpers.redirect(self, '/', 0)
def process(self): username = self.username # Need to access before using in filter logout(self.request) try: userAccount = models.UserAccount.objects.get(username=username) except models.UserAccount.DoesNotExist: pass else: userAccount.lastLogout = datetime.datetime.now() userAccount.save() return helpers.redirect(request=self.request, currentPage=self.currentPage, destinationPage=self.destinationPage)
def get(self): # Get current google account that is signed in user = users.get_current_user() # Check if there is a user signed in if user: person = login.is_roommate_account_initialized(user) if person: # Get the authorized Http object created by the decorator. http = decorator.http() # Call the service using the authorized Http object. now = datetime.datetime.utcnow().isoformat( ) + 'Z' # 'Z' indicates UTC time requestResults = service.events().list( calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute(http=http) else: helpers.redirect(self, '/', 0) # If there is no user, prompt client to login else: helpers.redirect(self, '/', 0)
def remove_bill(self, utility: str) -> None: """Remove a bill from the database.""" records = self.db.get_utility_record(utility) if not records: redirect( self, message=f"There are no bills in {utility}.", destination=Destinations.UTILITY_MENU, utility=utility, ) for record in records: print(record) intent = input_handler( self, prompt=("Which bill would you like to remove?\n" "Input bill ID:"), destination=Destinations.BILL_REMOVAL, integer=True, utility=utility, ) for entry in records: if entry.id == intent: print(entry) intent = input_handler( self, prompt=f"Will you remove this bill?", destination=Destinations.BILL_REMOVAL, boolean=True, utility=utility, ) if intent == "yes": self.db.remove_bill(entry) redirect(self, message=None) else: redirect(self, message="Returning to main menu.") redirect( self, message="The input bill ID could not be found.", destination=Destinations.BILL_REMOVAL, utility=utility, )
def process(self): if self.request.method == "POST" and self.checkFormValidity(): return helpers.redirect(request=self.request, currentPage=self.currentPage, destinationPage=self.destinationPage) # Need to access pageContext before setting variables # !!!!!!!!!! Don't delete self.pageContext # !!!!!!!!!! if self.pageErrors: self._pageContext["errors"] = self.pageErrors print "source :{0}, current: {1}, dest: {2}".format( self.sourcePage, self.currentPage, self.destinationPage) return render(self.request, self.currentPageHtml, self.pageContext)
def process(self): if self.request.method == "POST": if self.formSubmitted: if self.form.is_valid(): messages.add_message(self.request, messages.INFO, "destination:{0}".format(constants.PROFILE)) return helpers.redirect(request=self.request, currentPage=self.currentPage, destinationPage=self.destinationPage) # Need to access pageContext before setting variables # !!!!!!!!!! Don't delete self.pageContext # !!!!!!!!!! if self._pageErrors: self._pageContext["errors"] = self.pageErrors return render(self.request, constants.HTML_MAP.get(self.currentPage), self.pageContext)
def get(self): # Get current google account that is signed in user = users.get_current_user() # Check if there is a user signed in if user: # Check if user has an account set up person = login.is_roommate_account_initialized( user) #Change to check if in home if person: if login.is_in_room(self, person): helpers.redirect(self, '/dashboard', 0) # Otherwise, prompt user to create account else: helpers.redirect(self, '/newJoinHome', 0) #/new_join_home else: #redirect to create account page helpers.redirect(self, '/newJoinHome', 0) #/new_join_home # If there is no user, prompt client to login else: login.render_login_page(self)
def get(self): user = users.get_current_user() if user: person = login.is_roommate_account_initialized(user) if person: if (person.location): person.location = False person.put() else: person.location = True person.put() if (person.location): data = {'check_in_state': 'Checked In!'} else: data = {'check_in_state': 'Checked Out!'} render.render_page_with_data(self, 'checkInState.html', "Check In or Out", data) helpers.redirect(self, '/dashboard', 1000) else: helpers.redirect(self, '/', 0) else: helpers.redirect(self, '/', 0)
def process_view(self, request, view_func, view_args, view_kwargs): """ This function uses the contents of view_kwargs['meta'] determine access rights. The rules are: meta['requires_account'] == False: show view only if account is not present meta['requires_login'] == True: show view only if person is logged in meta['requires_logout'] == True: show view only if person is not logged in meta['requires_resource'] == 'widget': show view only if account has 'widget' resources. Redirects to upgrade screen if not. meta['roles'] == 'role1 & (role2 | role 3)': Show view if person is logged in & has role1 and either role2 or role3 meta['roles'] == None or '' or <not set> Show view without checking roles. """ if 'meta' not in view_kwargs: return None meta = view_kwargs.pop('meta') # SSL if meta.get('ssl') and not request.is_secure(): if request.method == 'GET': return self._redirect(request, True) else: return HttpResponseForbidden() # Requires account account = getattr(request, 'account', None) if meta.get('requires_account', True): if not account: raise Http404 else: if account: raise Http404 else: return None # Requires account to be active if not account.active: if not meta.get('inactive_account_ok'): return HttpResponseRedirect('/account/inactive/') # Requires login if 'roles' in meta: meta['requires_login'] = True person = getattr(request, 'person', None) if meta.get('requires_logout') and person: return HttpResponseForbidden() if meta.get('requires_login') and not person: return helpers.redirect( views.authentication.login ) # Requires reource if not account.has_resource(meta.get('requires_resource')): return helpers.redirect( views.subscription.upgrade ) if not person: return None # Requires role if person.has_roles(meta.get('roles')): return None else: return HttpResponseForbidden()
def post(self): #retrieve data from form name = self.request.get('name_b') phone_number = int( self.request.get('phone_number1_b') + self.request.get('phone_number2_b') + self.request.get('phone_number3_b')) color = self.request.get('color') #create new person object user = users.get_current_user() person = Person(name=name, color=color, phone_number=phone_number, user_id=user.user_id(), email_address=user.email(), calendar_id=user.email()) home_name = self.request.get('home_name_b') homes_with_same_name = Home.query().filter( Home.name == home_name).fetch() logging.info(self.request.get('password_a')) logging.info(self.request.get('password_b')) if len(homes_with_same_name ) > 0: #If home with same name already exists data = {'error': 'This home name is already taken'} render.render_page_with_data_no_header(self, 'newJoinHome.html', 'Error: Home Name Taken', data) elif not (self.request.get('password_b') == self.request.get('password_a')): data = {'error': 'Error: Passwords do not match'} render.render_page_with_data_no_header(self, 'newJoinHome.html', 'Join a Room', data) else: password = helpers.hashPass(self.request.get('password_b')) #Creates a calendar to be shared (on service account) calID = helpers.createNewCal(self, home_name) new_home = Home(name=home_name, password=password, calendar_id=calID, occupants=[user.user_id()]) person.home_key = new_home.put() person.put() #Share calendar with user scopes = ['https://www.googleapis.com/auth/calendar'] credentials = ServiceAccountCredentials.from_json_keyfile_name( 'service_account.json', scopes=scopes) http_auth = credentials.authorize(Http()) rule = { 'scope': { 'type': 'user', 'value': user.email() }, 'role': 'reader' } created_rule = service.acl().insert( calendarId=calID, body=rule).execute(http=http_auth) logging.info(calID) #Update new calendar with events of person who just joined #Gets primary calendary ID http = decorator.http() #Call the service using the authorized Http object. now = datetime.datetime.utcnow().isoformat( ) + 'Z' # 'Z' indicates UTC time requestResults = service.events().list( calendarId='primary', timeMin=now, singleEvents=True, orderBy='startTime').execute(http=http) for event in requestResults['items']: helpers.addEventToCal(self, event, calID) #redirect to create a calendar helpers.redirect(self, '/dashboard', 1000)
def get(self): helpers.redirect(self, '/dashboard', 1000)
def post(self): name = self.request.get('name') phone_number = int( self.request.get('phone_number1') + self.request.get('phone_number2') + self.request.get('phone_number3')) #create new person object user = users.get_current_user() color = self.request.get('color') person = Person(name=name, color=color, phone_number=phone_number, user_id=user.user_id(), email_address=user.email(), calendar_id=user.email()) #retrieve data from form home_name = self.request.get('home_name') password = helpers.hashPass(self.request.get('password')) # Query for home object potential_home = Home.query().filter( Home.name == home_name, Home.password == password).fetch() if potential_home: potential_home[0].occupants.append(user.user_id()) home_key = potential_home[0].put() person.put() person.home_key = home_key #Share Calendar calID = potential_home[0].calendar_id #Share calendar with user scopes = ['https://www.googleapis.com/auth/calendar'] credentials = ServiceAccountCredentials.from_json_keyfile_name( 'service_account.json', scopes=scopes) http_auth = credentials.authorize(Http()) rule = { 'scope': { 'type': 'user', 'value': user.email() }, 'role': 'reader' } created_rule = service.acl().insert( calendarId=calID, body=rule).execute(http=http_auth) logging.info(calID) #Update new calendar with events of person who just joined #Gets primary calendary ID http = decorator.http() #Call the service using the authorized Http object. now = datetime.datetime.utcnow().isoformat( ) + 'Z' # 'Z' indicates UTC time requestResults = service.events().list( calendarId='primary', timeMin=now, singleEvents=True, orderBy='startTime').execute(http=http) for event in requestResults['items']: helpers.addEventToCal(self, event, calID) # requestResults = service.events().list(calendarId='primary', timeMin=now, singleEvents=True, orderBy='startTime').execute(http=http) # for event in requestResults['items']: # helpers.addEventToCal(self, event, calID) #DONE WITH PASTED CODE person.put() data = {'home_name': home_name} render.render_page_with_data(self, 'successfullyJoinedHome.html', 'Successfully Joined Home', data) helpers.redirect(self, '/dashboard', 1000) else: # REPORT to client to try again. wrong name or password data = { 'error': 'You have entered an incorrect home name or password' } render.render_page_with_data_no_header( self, 'newJoinHome.html', 'Error: Wrong Name or Password', data)
def pay_bill(self, utility: str) -> None: """Pay a bill.""" def payment(bill: Bill, user: str) -> None: """Write information to bill object and send it to the database.""" if user == self.user1: bill.user1_paid = True bill.note += ( f"\n{self.user1_upper} paid {bill.owed_amount} " f"for bill (ID {bill.id}) " f"on {formatted_today()}, " "paying off their portion of the bill." ) else: bill.user2_paid = True bill.note += ( f"\n{self.user2_upper} paid {bill.owed_amount} " f"for bill (ID {bill.id}) " f"on {formatted_today()}, " "paying off their portion of the bill." ) if bill.user1_paid is True and bill.user2_paid is True: bill.paid = True self.db.pay_bill(bill) print(f"Bill ID {bill.id} has been completely paid off!") else: self.db.pay_bill(bill) print("You successfully paid your bill!") records = self.db.get_utility_record(utility) if not records: redirect( self, message=f"There are no bills in {utility}.", destination=Destinations.UTILITY_MENU, utility=utility, ) identity = input_handler( self, prompt=( "Who are you?\n" f"Enter '{self.user1_upper}' or '{self.user2_upper}'." ), destination=Destinations.BILL_PAYMENT, acceptable_inputs={self.user1, self.user2}, utility=utility, ) if identity == self.user1: collector = [] for entry in records: if not entry.user1_paid: collector.append(entry) if len(collector) == 0: print("You don't have any bills to pay.") redirect(self, message=None) for entry in collector: print(entry) else: collector = [] for entry in records: if not entry.user2_paid: collector.append(entry) if len(collector) == 0: print("You don't have any bills to pay.") redirect(self, message=None) for entry in collector: print(entry) intent = input_handler( self, prompt=( "Which bill would you like to pay?\n" "You can pay multiple bills at once " "by entering multiple IDs separated by a space.\n" "Enter the ID:" ), destination=Destinations.BILL_PAYMENT, utility=utility, ) intent_list = intent.split(" ") # Paying by a single ID if len(intent_list) == 1: for entry in records: if entry.id == int(intent): intent = input_handler( self, prompt=( f"{entry}\nYou owe {entry.owed_amount} yen\n" "Will you pay your bill?" ), destination=Destinations.BILL_PAYMENT, utility=utility, boolean=True, ) match intent: case "yes": payment(entry, identity) redirect(self, message=None) case "no": redirect(self, message=None) case _: redirect( self, destination=Destinations.BILL_PAYMENT, utility=utility ) redirect( self, message="The inputted bill ID could not be found.", destination=Destinations.BILL_PAYMENT, utility=utility, ) # Paying by multiple IDs elif len(intent_list) > 1: for id_intent in intent_list: for entry in records: if int(id_intent) == entry.id: payment(entry, identity) redirect(self, message=None) else: redirect(self, destination=Destinations.BILL_PAYMENT, utility=utility)