def create(self): """Handles the POST data for creating a group. Form Variables: name: the name of the new group public: true if the group should be joinable by the public """ if auth.logged_in(): name = self.request.get('name') public = self.request.get('public') == 'public' owner = auth.current_user() if Group.exists(name): Messages.add('A group with that name already exists') return self.redirect('/groups/signup') Group(name=name, public=public, owner=owner, members=[owner]).put() return self.redirect('/groups') else: Messages.add('You must be logged in to create a group') return self.redirect('/groups/signup')
def stories(): # if the user is logged in, gets all of the stories if logged_in(): stories = get_stories() parsed_stories = {} # then parses through, choosing the ones that the user has not contributed to for story in stories: if not get_contribution(session['user_id'], story): parsed_stories[story] = stories[story] orig_cont = get_original_contribution(story) if orig_cont: creator = orig_cont['user_id'] parsed_stories[story]['creator'] = get_username(creator) rand_story_id = None if parsed_stories: rand_story_id = random.randint(0, len(stories)) while rand_story_id not in parsed_stories: rand_story_id = random.randint(0, len(stories)) return render_template('stories.html', title='Stories', stories=parsed_stories, rand_story_id=rand_story_id) # if they are not logged in, alerts the user and brings them to the login page else: flash('You need to log in or create an account.') return redirect(url_for('login'))
def render(self, template_name, data={}): """Renders the template in the site wide manner. Retrieves the template data needed for the base template (login URL and text, user information, etc.) and merges it with the data passed to the method. Templates are retrieved from the template directory specified in the settings and appended with the suffix ".html" Arguments: template_name: the name of the template. this is the file name of the template without the .html extension. data: a dictionary containing data to be passed to the template. """ (login_text, login_url) = auth.login_logout(self.request) if auth.logged_in(): data['user'] = auth.User(auth.current_user()) data['admin'] = auth.user_is_admin() data['login_url'] = login_url data['login_text'] = login_text data['messages'] = Messages.get() path = os.path.join(settings.BASE_DIR, settings.TEMPLATE_DIR, "%s.html" % template_name) return self.response.out.write(template.render(path, data))
def profile(): print session['user_id'] if logged_in(): # gets all of the info pertaining to the user's stats # user's name nameUser = get_username(session['user_id']) # their contributions conts = get_user_contributions(session['user_id']) # a count of their total contributions num_conts = len(conts) # stories, which is populated by the stories the user has contributed to in the past, so they can review them stories = {} for cont in conts: story_id = cont story = {} story['title'] = get_story_title(story_id) story['preview'] = get_story_body(story_id)[:200] + '...' story['complete'] = get_story_complete(story_id) stories[story_id] = story return render_template('profile.html', title='Profile', name=nameUser, stories=stories, num_conts=num_conts) # if they are not logged in, alerts the user and brings them to the login page else: flash('You need to log in or create an account.') return redirect(url_for('login'))
def GET(self, langcode=None, *compare_languages): if not auth.logged_in(): return web.seeother( '/login' ) if not self.authorized(langcode): return web.seeother('/edit/') return render( get_template( "edit", trans, langcode, compare_languages, settings.all_languages, auth.logged_in_user() ) )
def update_group(self, key): if not auth.logged_in(): return self.redirect('/groups') user = auth.current_user() group = Group.get(key) if group.owner.user_id() != user.user_id() and not auth.user_is_admin(): Messages.add('Only the owner of the group owner may modify it') return self.redirect('/groups') name = self.request.get('name') public = self.request.get('public') == 'public' abandon = self.request.get('abandon-project') sub_text = self.request.get('submission-text') sub_url = self.request.get('submission-url') remove_submission = self.request.get_all('remove-submission') remove = self.request.get_all('remove') owner = self.request.get('owner') delete = self.request.get('delete') if delete: group.delete() return self.redirect('/groups') group.name = name group.public = public if abandon: group.project = None if sub_text and sub_url: Submission(text=sub_text, url=sub_url, group=group).put() for sub in Submission.get(remove_submission): sub.delete() pending = list(group.pending_users) for user in pending: approve = self.request.get("approve-%s" % user) if approve == "approve": group.members.append(user) group.pending_users.remove(user) elif approve == "refuse": group.pending_users.remove(user) group.owner = auth.user_from_email(owner) for user in remove: if auth.user_from_email(user) == group.owner: Messages.add('Cannot remove the group owner') return self.redirect('/groups/%s/edit' % key) else: group.members.remove(auth.user_from_email(user)) group.put() return self.redirect('/groups/%s' % key)
def render(filename, page_title=None, vars={}): web.header('Content-Type', 'text/html; charset=utf-8') tmpl = env.get_template('%s.html' % filename) vars['csstime'] = os.stat("static/css-generated.css")[8] vars['jstime'] = os.stat("static/js-generated.js")[8] if jt.site: vars['pages'] = list(db.get_pages()) vars['logged_in'] = auth.logged_in() vars['design'] = db.get_design() print tmpl.render(vars)
def logout(): # checks to make sure the user is logged in if logged_in(): # if they are, then runs the logout function from auth.py and alerts the user to the success of the function auth.logout() flash('You have been logged out.') return redirect(url_for('index')) # if they are not logged in, alerts the user and brings them to the login page flash('You are not logged in!') return redirect(url_for('login'))
def comment(obsid): if not logged_in(False): return redirect('/login') check_csfr(request.form["csrf_token"]) # -- REQUEST VALUES -- # comment : string create_comment(obsid, request.form['comment']) return redirect(f'/observations/{obsid}')
def vote(self, key): if not auth.logged_in(): return self.redirect('/projects') project = Project.get(key) if project.has_voted(auth.current_user()): project.remove_vote(auth.current_user()) project.put() else: project.vote(auth.current_user()) project.put() return self.redirect('/projects')
def edit(self, key): if not auth.logged_in(): return self.redirect('/groups') user = auth.current_user() group = Group.get(key) if group.owner.user_id() == user.user_id() or auth.user_is_admin(): return self.render('groups_edit', { 'group': group }) else: Messages.add('Only the owner of this group may edit it') return self.redirect('/groups/%s' % key)
def edit(self, key): """Displays the group moderation form.""" if not auth.logged_in(): return self.redirect('/groups') user = auth.current_user() group = Group.get(key) if group.owner.user_id() == user.user_id() or auth.user_is_admin(): return self.render('groups_edit', {'group': group}) else: Messages.add('Only the owner of this group may edit it') return self.redirect('/groups/%s' % key)
def view_story(story_id=-1): # if they are not logged in, alerts the user and brings them to the login page if not logged_in(): flash('You need to log in or create an account.') return redirect(url_for('login')) # shows the story by retrieving its body and title from the database else: story = get_story_body(story_id) title = get_story_title(story_id) return render_template('view_story.html', story=story, title=title)
def login(self, **kwargs): if cherrypy.request.method.upper() == 'POST': cur = model.get_cursor() returnTo = kwargs.get('returnTo', cherrypy.url('/')) assertion = kwargs.pop('loginAssertion') if assertion == '': logged_out() raise cherrypy.HTTPRedirect(returnTo) try: result = browserid.verify(assertion, cherrypy.request.base) except browserid.ConnectionError: raise cherrypy.HTTPError(503, "Login connection error") except browserid.TrustError: raise cherrypy.HTTPError(409, "Invalid login") loginid = result['email'] cur.execute('''SELECT userid FROM users WHERE userid = ?''', (loginid)) if cur.fetchone() is None: cur.execute('''INSERT INTO users (userid, email) VALUES (?, ?)''', (loginid, loginid)) logged_in(loginid) raise cherrypy.HTTPRedirect(cherrypy.url('/preferences')) logged_in(loginid) raise cherrypy.HTTPRedirect(returnTo) if cherrypy.request.loginid is not None: raise cherrypy.HTTPRedirect(cherrypy.url('/')) return render('login.xhtml')
def login(self, **kwargs): if cherrypy.request.method.upper() == 'POST': cur = model.get_cursor() returnTo = kwargs.get('returnTo', cherrypy.url('/')) assertion = kwargs.pop('loginAssertion') if assertion == '': logged_out() raise cherrypy.HTTPRedirect(returnTo) try: result = browserid.verify(assertion, cherrypy.request.base) except browserid.ConnectionError: raise cherrypy.HTTPError(503, "Login connection error") except browserid.TrustError: raise cherrypy.HTTPError(409, "Invalid login") loginid = result['email'] cur.execute( '''SELECT userid FROM users WHERE userid = ?''', (loginid, )) if cur.fetchone() is None: cur.execute( '''INSERT INTO users (userid) VALUES (?)''', (loginid, )) logged_in(loginid) raise cherrypy.HTTPRedirect(cherrypy.url('/preferences')) logged_in(loginid) raise cherrypy.HTTPRedirect(returnTo) if cherrypy.request.loginid is not None: raise cherrypy.HTTPRedirect(cherrypy.url('/')) return render('login.xhtml')
def login(): if logged_in(False): return redirect('/') if request.method == 'POST': # -- REQUEST VALUES -- # username : string # password : string if start_session(request.form['username'], request.form['password']): return redirect('/observations/page/1') return redirect('/login') # ----- GET /login ----- return render_template('login.html', title='Kirjaudu')
def create_story(): if not logged_in(): flash('You need to log in or create an account.') return redirect(url_for('login')) # gets data from input boxes for creating a story if request.method == 'POST': title = request.form['title'] body = request.form['body'] # adds a story using the function below, then alerts the user that they were successful and brings them back to their profile story_id = add_story(title) add_cont(session['user_id'], story_id, body) flash('Story created successfully!') return redirect(url_for('profile')) else: return render_template('create_story.html', title='Create a Story')
def vote(self, key): """Votes for a project. This action removes the user's vote from the project if the user had already voted for it. """ if not auth.logged_in(): return self.redirect('/projects') project = Project.get(key) if project.has_voted(auth.current_user()): project.remove_vote(auth.current_user()) project.put() else: project.vote(auth.current_user()) project.put() return self.redirect('/projects')
def POST_edit(self, page_name=''): i = web.input('spinner', recaptcha=False) spinner, recaptcha_p = i.spinner, i.recaptcha error_to_use = None if recaptcha_p: c = recaptcha.submit(i.recaptcha_challenge_field, i.recaptcha_response_field, os.environ['RECAPTCHA_PRIVKEY'], web.ctx.ip) if not c.is_valid: error_to_use = c.error_code i = auth.unspuninput(page_name, 'content', 'scroll_pos', 'caret_pos', 'current_revision', save=False, delete=False) page = db.get_page(page_name) content = re.sub(r'(\r\n|\r)', '\n', i.content) if (jt.site.security == 'open' and not auth.logged_in()) and (not recaptcha_p or error_to_use): captcha = recaptcha.displayhtml(os.environ['RECAPTCHA_PUBKEY'], use_ssl=True, error=error_to_use) timestamp, spinner, spinfield = auth.spinner(page_name) return render('captcha', vars=locals()) if not page: db.new_page(page_name, content, i.scroll_pos, i.caret_pos) page = db.get_page(page_name) revision = db.get_revision(page.id) if i.current_revision and revision.revision != int( i.current_revision ) and not page.deleted and revision.content != content: timestamp, spinner, spinfield = auth.spinner(page_name) orig = db.get_revision(page.id, i.current_revision) diff = better_diff(orig.content, content) return render('edit_conflict', vars=locals()) if i.delete and page_name: db.delete_page(page.id) return web.seeother(page.url) db.update_page(page.id, content, i.scroll_pos, i.caret_pos) if page.deleted: db.undelete_page(page.id, page_name) web.seeother(page.url)
def register(): if logged_in(False): return redirect('/') if request.method == 'POST': # -- REQUEST VALUES -- # name : string # username : string # password : string # password_confirm : string if new_user(request.form['name'], request.form['username'], request.form['password']): return redirect('/login') return redirect('/register') # ----- GET /register ----- return render_template('register.html', title='Rekisteröidy')
def contribute(story_id=-1): # if they are not logged in, alerts the user and brings them to the login page if not logged_in(): flash('You need to log in or create an account.') return redirect(url_for('login')) # if they've contributed to this story before, alerts the user and brings them back to the stories page if get_contribution(session['user_id'], story_id): flash('You have already contributed to this story.') return redirect(url_for('stories')) # otherwise, accepts the contribution, alerts the user, and brings them back to their profile if request.method == 'POST': add_cont(session['user_id'], story_id, request.form['body']) flash('You have contributed to "' + get_story_title(story_id) + '"!') return redirect(url_for('profile')) else: # this is the page for editing the story story = get_story(story_id) conts_left = MAX_CONTRIBUTIONS - len(get_story_contributions(story_id)) return render_template('edit_story.html', title='Contribute', story=story, conts_left=conts_left)
def create_user(): # checks to make sure the user is logged in. If they are, alerts the user and brings them to their profile. if logged_in(): flash('You are already logged in!') return redirect(url_for('profile')) if request.method == 'POST': # if not, uses input data to create a new account result = auth.create(request.form['username'], request.form['password1'], request.form['password2']) # if succeeds, flash 0 if result == 0: flash('You have created an account!') return redirect(url_for('profile')) elif result == 1: flash('Your passwords do not match.') return redirect(url_for('create_user')) elif result == 2: flash('This username already exists.') return redirect(url_for('create_user')) else: return render_template('create_user.html', title='Create')
def new_observation(): if not logged_in(False): return redirect('/login') if request.method == 'POST': # -- REQUEST VALUES -- # bird : string # location : string # date : string (yyyy-mm-dd) # count-option : string ('one'/'many') # count : string/None # banded-option : string ('true'/'false'/'not_known') # band-serial : string/None # uploadImage : file/None (.apng/.avif/.gif/.jpg/.jpeg/.jfif/.pjpeg/.pjp/.png/.svg/.webp) check_csfr(request.form["csrf_token"]) observation_id = create_observation(request.form) if not observation_id: return redirect('/new-observation') if request.files['uploadImage']: create_image(observation_id, request.files) return redirect(f'/observations/{observation_id}') # ----- GET /new-observation ----- birds = get_birds() locations = get_locations() return render_template('new_observation.html', title='Uusi havainto', birdpattern=birds[1], birds=birds[0], locationpattern=locations[1], locations=locations[0], today=datetime.now().strftime('%Y-%m-%d'))
def login(): # uses helper method to see if the user is logged in if logged_in(): # if they are, alerts the user and brings them to their profile flash('You are already logged in!') return redirect(url_for('profile')) if request.method == 'POST': result = auth.login(request.form['username'], request.form['password']) if result == 0: # if login succeeds and 0 is returned, alerts the user and brings them to their profile flash('You have logged in!') return redirect(url_for('profile')) elif result == 1: # if login fails and 1 is returned, alerts the user that their password is wrong and prompts them to try again flash('Incorrect password.') return redirect(url_for('login')) elif result == 2: # if login fails and 2 is returned, alerts the user that their username is wrong and prompts them to try again flash('This username doesn\'t exist.') return redirect(url_for('login')) # if they are not logged in, alerts the user and brings them to the login page else: return render_template('login.html', title='Login')
def update_group(self, key): """Updates a group with information from the moderation form. Form Variables: name: the name of the group public: true if the group should be joinable by the public abandon-project: true if the group moderator wants to abandon the current project submission-text: the text to be displayed for the new submission submission-url: the URL of the new submission remove-submission: a list of submissions to be removed remove: a list of users to be removed from the group owner: the owner of the group delete: true if the group moderator wants to disband the group """ if not auth.logged_in(): return self.redirect('/groups') user = auth.current_user() group = Group.get(key) if (group.owner.user_id() != user.user_id() and not auth.user_is_admin()): Messages.add('Only the owner of the group owner may modify it') return self.redirect('/groups') name = self.request.get('name') public = self.request.get('public') == 'public' abandon = self.request.get('abandon-project') sub_text = self.request.get('submission-text') sub_url = self.request.get('submission-url') remove_submission = self.request.get_all('remove-submission') remove = self.request.get_all('remove') owner = self.request.get('owner') delete = self.request.get('delete') if delete: group.delete() return self.redirect('/groups') group.name = name group.public = public if abandon: group.project = None if sub_text and sub_url: Submission(text=sub_text, url=sub_url, group=group).put() for sub in Submission.get(remove_submission): sub.delete() pending = list(group.pending_users) for user in pending: approve = self.request.get("approve-%s" % user) if approve == "approve": group.members.append(user) group.pending_users.remove(user) elif approve == "refuse": group.pending_users.remove(user) group.owner = auth.user_from_email(owner) for user in remove: if auth.user_from_email(user) == group.owner: Messages.add('Cannot remove the group owner') return self.redirect('/groups/%s/edit' % key) else: group.members.remove(auth.user_from_email(user)) group.put() return self.redirect('/groups/%s' % key)
import methods from auth import logged_in, auth if __name__ == "__main__": while True: if not logged_in(): methods.login() else: while True: cmd = input('Enter command: ') if cmd == 'create': methods.create(auth["role"]) elif cmd == 'remove': methods.remove(auth["role"]) elif cmd == 'show': methods.show() elif cmd == 'showall': methods.showall() elif cmd == 'update': methods.update(auth["role"]) elif cmd == 'exit': exit() else: print('Command not found.') break
def GET(self): if not auth.logged_in(): return web.seeother( '/login' ) return web.seeother('/edit/%s/en/' % auth.logged_in_user().languages[0] )
def GET(self, error=None): if auth.logged_in(): return render( "Logged in" ) else: return render( get_template( "login", error ) )