def get_file(request): current_time = datetime.datetime.now().replace(tzinfo=None) fileName = request.GET.get('fileName') fileMap = FileLink.objects.get(linkSuffix=fileName) if fileMap.password_protected: if request.POST.get('password'): if request.POST.get('password') != fileMap.password: context = {"error": "Incorrect Password"} return render_response('password.html', request, context) else: return render_response('password.html', request) seconds_since_upload = ( current_time - fileMap.created_on.replace(tzinfo=None)).total_seconds() if seconds_since_upload >= 24 * 60 * 60: return HttpResponse("Link is more than 24 hours old hence expired") password = '******' if not fileMap.password_protected else fileMap.password.encode( 'ascii', 'ignore') abspath = location % fileName ufile = open(abspath, 'r') outfile = StringIO.StringIO() outfile = decrypt(ufile, outfile, password) response = HttpResponse(content=outfile.getvalue()) response['Content-Type'] = 'mimetype/submimetype' response[ 'Content-Disposition'] = 'attachment; filename=%s' % fileMap.externalName return response
def get_file(request): current_time = datetime.datetime.now().replace(tzinfo=None) fileName = request.GET.get('fileName') fileMap = FileLink.objects.get(linkSuffix=fileName) if fileMap.password_protected: if request.POST.get('password'): if request.POST.get('password') != fileMap.password: context = {"error": "Incorrect Password"} return render_response('password.html',request,context) else: return render_response('password.html',request) seconds_since_upload = (current_time - fileMap.created_on.replace(tzinfo=None)).total_seconds() if seconds_since_upload >= 24 * 60 * 60: return HttpResponse("Link is more than 24 hours old hence expired") password = '******' if not fileMap.password_protected else fileMap.password.encode('ascii','ignore') abspath = location % fileName ufile = open(abspath,'r') outfile = StringIO.StringIO() outfile = decrypt(ufile,outfile,password) response = HttpResponse(content=outfile.getvalue()) response['Content-Type'] = 'mimetype/submimetype' response['Content-Disposition'] = 'attachment; filename=%s' % fileMap.externalName return response
def item_detail(request, name='', object_id = None, ajax = False): if ajax: item = Item.objects.get(id=object_id) return item_detail_render(request, item, ajax) if request.method == 'POST': form = ItemForm(request.POST) if form.is_valid(): item = form.cleaned_data['item'] country = form.cleaned_data['country'] items = countries = [] if item or country: qset = (Q(name__icontains=item) | Q(country__name__icontains=country)) items = Item.objects.filter(qset) if country: qset = (Q(name__icontains=country)) countries = Country.objects.filter(qset) return render_response(request, 'items.html', {'form': form, 'items': items, 'countries': countries, 'title': u'Cities'}) else: return render_response(request, 'items/item_search.html', {'form': form, 'title': u'Cities'}) elif name: items = Item.objects.filter(name__icontains=name) if items.count() == 1: return item_detail_render(request, items[0], ajax) else: return HttpResponseRedirect("/items/") else: form = ItemForm() return render_response(request, 'items/item_search.html', {'form': form, 'title': u'Cities'})
def game(request): """Game Page.""" if request.method == 'POST': try: lang = request.POST['selCombo'] team1 = request.POST['first_team'] team2 = request.POST['second_team'] players = int(request.POST['players']) rounds = int(request.POST['rounds']) if not team1 or not team2 or players < 2 or rounds < 1: raise Exception() cards = list(models.get_cards(lang)) random.shuffle(cards) data = {"team1": team1, "team2": team2, "players": players, "rounds": rounds, "cards": cards} return render_response(request, 'tabu/game_page.html', data) except: langs = models.get_languages() data = {"langs": langs, 'error': "Missing or Invalid data."} return render_response(request, 'tabu/setup_page.html', data) else: langs = models.get_languages() data = {"langs": langs} return render_response(request, 'tabu/setup_page.html', data)
def game(request): """Game Page.""" if request.method == 'POST': try: lang = request.POST['selCombo'] team1 = request.POST['first_team'] team2 = request.POST['second_team'] players = int(request.POST['players']) rounds = int(request.POST['rounds']) if not team1 or not team2 or players < 2 or rounds < 1: raise Exception() cards = list(models.get_cards(lang)) random.shuffle(cards) data = { "team1": team1, "team2": team2, "players": players, "rounds": rounds, "cards": cards } return render_response(request, 'tabu/game_page.html', data) except: langs = models.get_languages() data = {"langs": langs, 'error': "Missing or Invalid data."} return render_response(request, 'tabu/setup_page.html', data) else: langs = models.get_languages() data = {"langs": langs} return render_response(request, 'tabu/setup_page.html', data)
def edit_profile(): """edit_profile() Serves the edit profile page or updates the profile, depending on the request method Accessed at '/logout' via a GET or POST request Requires that the user is logged in """ # If the request is a POST request, updates the user based on the form input if request.method == 'POST': # Updates values of the current user's profile from the form current_user.first_name = request.form['first-name'] current_user.last_name = request.form['last-name'] # Updates the email only if a new one is provided if request.form['email'] != current_user.email: # Stores old user_id old_user_id = current_user.email # Updates the user's email current_user.update_email(request.form['email']) # Updates the session key with the new user_id session = Session.get_session(user_id=old_user_id) session.user_id = current_user.email session.save() # Removes the user at the old user_id from memory __users.pop(old_user_id, None) # Updates the password only if a new one is provided if request.form['password'] != '': # Creates the salt used in hashing the password salt = str(uuid.uuid4()) # Hashes the password and stores the new hashed password and salt current_user.password = hashlib.sha512( (request.form['password'] + salt).encode('utf-8')).hexdigest() current_user.salt = salt # Saves the changes to the user current_user.save() return render_response( redirect(url + url_for('user_blueprint.profile'))) # Returns the edit profile page for admins if current_user.admin: return render_response( render_template('admin_pages/edit_profile.html', email=current_user.email, first_name=current_user.first_name, last_name=current_user.last_name)) # Returns the edit profile page for users return render_response( render_template('user_pages/edit_profile.html', email=current_user.email, first_name=current_user.first_name, last_name=current_user.last_name))
def item_redirect(request, object_id=None): if object_id: try: item = Item.objects.get(id=object_id) return HttpResponsePermanentRedirect('/items/' + item.name) except Item.DoesNotExist: form = ItemForm() return render_response(request, 'items/item_search.html', {'form': form, 'title': u'Cities'}) else: form = ItemForm() return render_response(request, 'items/item_search.html', {'form': form, 'title': u'Cities'})
def decorated_function(*args, **kwargs): # Checks if the user is anonymous if not current_user: return render_response( redirect(url + url_for('user_blueprint.login'))) # Checks if the user is an admin if not current_user.admin: return render_response( render_template('error_pages/admin_access_denied.html')) return f(*args, **kwargs)
def aggregator_submit(request): if not request.user.is_authenticated(): request.session['anonymous_submit'] = True return HttpResponseRedirect('/accounts/login/?next=%s' % request.path) if request.session.get('recent_submission', False): request.user.message_set.create(message=u'You just shared this ranking. In order to share another ranking you will need to <a href="/ranking/">change the weighting</a> or <a href="/indicators/">add or remove</a> different rankings.') request.session['anonymous_submit'] = False # THIS ISN'T working, how come? return HttpResponseRedirect('/accounts/profile') class UserRankingForm(forms.ModelForm): name = forms.CharField(label="Title of Ranking") class Meta: model = UserRanking fields = ('name', 'description') sources_to_aggregate = request.session.get('sources_to_aggregate', DefaultSources) source_weights = request.session.get('source_weights', DefaultWeights) print "here", request.method if request.method == 'POST': print "foo" form = UserRankingForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.creator = request.user instance.json = request.session['current_aggregation_json'] instance.save() for weight in request.session['weights_to_submit']: weight.save() instance.weights.add(weight) instance.save() request.session['recent_submission'] = True make_ranking_icon(request, instance.id) ranking_id = request.session.get('ranking_id', 100) + 1 request.session['ranking_id'] = ranking_id return render_response(request, 'items/aggregator_submit_final.html', {'sources': sources_to_aggregate, 'weights': source_weights, 'id': instance.id, 'ranking_id': ranking_id }) else: weights = [Weighting(source=source, weight=source_weights.get(source, 10)) for source in sources_to_aggregate] request.session['weights_to_submit'] = weights else: print "bar" form = UserRankingForm() weights = [Weighting(source=source, weight=source_weights.get(source, 10)) for source in sources_to_aggregate] request.session['weights_to_submit'] = weights return render_response(request, 'items/aggregator_submit.html', {'weighting': weights, 'form': form, 'ranking_id': request.session.get('ranking_id', 100) })
def profile(): """profile() Serves the profile page Accessed at '/profile' via a GET request Requires that the user is logged in """ # Returns the profile page for admins if current_user.admin: return render_response(render_template('admin_pages/profile.html')) # Returns the profile page for users return render_response(render_template('user_pages/profile.html'))
def reset_password(): """reset_password() Verifies the temporary password used by the user or resets the user's password, depending on the state of the application Accessed at '/reset_password' via a POST request """ # Gets the user by email user = get_user(request.form['email']) # Checks that the user exists if user: # Checks that the temporary password exists, has not expired, and matches the password provided by the user if user.temp_password and user.temp_password_expire > datetime.now( user.temp_password_expire.tzinfo ) and user.temp_password == request.form['password']: # Sets the user's password to None so it can be reset user.password = None # Sets the temporary password and expiration to None so it cannot be used again user.temp_password = None user.temp_password_expire = None user.save() # Returns the next page where the user can reset their password return render_response( render_template('user_pages/reset_password_2.html', email=user.email)) # Checks that the user's password is None and therefore ready to be reset if user.password is None: # Creates the salt used in hashing the password salt = str(uuid.uuid4()) # Hashes the password # (?) TODO: Switch hashing to key derivation function hashed_password = hashlib.sha512( (request.form['password'] + salt).encode('utf-8')).hexdigest() # Stores the updated hashed password and salt user.password = hashed_password user.salt = salt user.save() # Redirects to the login page return render_response( redirect(url + url_for('user_blueprint.login'))) # If the user does not exists, redirects to the login page # The email is passed by the system, not user input, so this shouldn't happen unless the user mistakenly navigates here with an out of context POST request return render_response(redirect(url + url_for('user_blueprint.login')))
def index(): """index() Serves the home page Accessed at '/' via a GET request """ # Checks if the user is logged in if current_user: # Checks if the user is an admin if current_user.admin: # Returns the admin homepage return render_response( render_template('admin_pages/homepage.html', first_name=current_user.first_name)) # Gets the active engine to link to with the 'Begin Story' button begin_story = db.collection('application_states').document( 'application_state').get().get('active_story_id') # Gets the most recent story to link to with the 'Continue Story' button most_recent_history = None continue_story = None # Loops over the stories in the user's history for index, history in enumerate(current_user.history): # Sets the continue_story to the first story in the user's history if most_recent_history is None: most_recent_history = index continue_story = current_user.history[most_recent_history][ 'story'] + '/' + current_user.history[most_recent_history][ 'pages'][-1] # Checks if each story was more recently accessed than the current_story; if so, updates the current_story elif history['last_updated'].replace( tzinfo=None) > current_user.history[most_recent_history][ 'last_updated'].replace(tzinfo=None): most_recent_history = index continue_story = current_user.history[most_recent_history][ 'story'] + '/' + current_user.history[most_recent_history][ 'pages'][-1] # Returns the user homepage return render_response( render_template('user_pages/homepage.html', first_name=current_user.first_name, begin_story=begin_story, continue_story=continue_story, history=most_recent_history)) # Returns the homepage return render_response(render_template('home.html'))
def media(): """media() Serves the media manager page Accessed at '/media' via a GET request Requires that the user is logged in as an admin """ # The file names files = [] # Gets the names of all files in the file_uploads folder for file in os.listdir('file_uploads'): seconds = os.path.getmtime('file_uploads/' + file) timestamp = time.ctime(seconds) sizeb = os.stat('file_uploads/' + file).st_size sizek = sizeb/1024 sizeg = round(sizek/1024, 2) sizek = round(sizek, 2) size = sizek sizetype = 'KB' if sizeg > 2: size = sizeg sizetype = 'GB' files.append([file, timestamp, size, sizetype]) # Returns the files page with the files return render_response(render_template('admin_pages/media_manager.html', files=files, url_root=url))
def details(request): """Details Page.""" showid = request.GET.get('show', False) if not showid or not showid.isdigit(): return HttpResponseRedirect("/") data = shows.get_show_info(showid) if 'unfollow' in request.GET: showid = request.GET['unfollow'] shows.unfollow_show(showid, request.user) elif 'follow' in request.GET: showid = request.GET['follow'] shows.follow_show(showid, request.user) data['following'] = shows.user_is_following(showid, request.user) if 'season' in request.GET: season = request.GET['season'] episode = request.GET['episode'] if not season.isdigit() or not episode.isdigit(): season = 1 episode = 1 info = shows.get_episodes_for_season(showid, season, episode) data['episode_info'] = info else: seasons = shows.get_seasons(showid, request.user) data['seasons'] = seasons most_rated = shows.get_most_rated_shows(request.user) data['recommended'] = most_rated return render_response(request, 'details.html', data)
def update(request): """Update Page.""" showid = request.GET.get('showid', '') if showid: shows.update_show(showid) data = shows.get_shows_to_update() return render_response(request, 'update.html', data)
def css_test(request): cookies = False if 'foobarval' in request.session: cookies = True val = request.session.get('foobarval', -1) request.session['foobarval'] = val + 1 return render_response(request, 'css_test.html', {'cookies': cookies, 'val': val, 'foo': 23189.321839 })
def favorites(): """favorites() Serves the favorites page with the user's favorites Accessed at '/favorites' via a GET request Requires that the user is logged in """ # Creates an array of the user's favorites with information about each page favorites = [] for favorite in current_user.favorites: # Gets the story the favorite belongs to story_ref = db.collection('stories').document(favorite['story']) story_doc = story_ref.get() # Gets the page data for the favorite page = story_doc.get('page_nodes.`' + favorite['page_id'] + '`') # Adds the favorite's page name, the favorite's page link, and which history the favorite belongs to favorites.insert(0, (page['page_name'], favorite['story'] + "/" + favorite['page_id'], favorite['history_id'])) # Returns the favorites.html template with the given values return render_response( render_template('user_pages/favorites.html', first_name=current_user.first_name, favorites=favorites))
def edit_todo(request, todoid): todo = session.query(ToDo).filter_by(id=todoid).first() if request.method == 'POST': if request.form['title'] and request.form['text']: todo.title = request.form['title'] todo.text = request.form['text'] new_file = request.files['userfile'] if new_file: existing_file = session.query(File).filter_by(todo_id=todo.id).one() existing_file.filename = secure_filename(new_file.filename) existing_file.filecontent = new_file.read() session.commit() return redirect("/todo/%s" % todo.id) else: return render_response("edit_todo.html", todo=todo, user=request.session["user"], error="Please enter a title and note for your to do.") else: return render_response("edit_todo.html", todo=todo, user=request.session["user"])
def signup(request): if request.method == 'POST': if request.form['email'] and request.form['password']: user = session.query(User).filter_by(email=request.form['email']).first() if not user: password = hashlib.md5() password.update(request.form['password']) new_user = User(email=request.form['email'], password=password.hexdigest()) session.add(new_user) session.commit() return redirect("/") else: return render_response("signup.html", error="User already exists.") else: return render_response("signup.html", error="Please enter an e-mail address and password.") else: return render_response("signup.html")
def item_detail_render(request, item, ajax): rankings = DataSource.objects.filter(Q(data__item=item) & Q(data__scheme__type='r') & Q(active=True)) stats = DataSource.objects.filter(Q(data__item=item) & Q(data__scheme__type='s') & Q(active=True)) try: ranked = [[ranking, int(Data.objects.get(item=item,source=ranking,scheme__type='r').value)] for ranking in rankings] except Data.MultipleObjectsReturned: # should never happen, but data might be imported wrong ranked = [[ranking, int(Data.objects.filter(item=item,source=ranking,scheme__type='r')[0].value)] for ranking in rankings] utils.send_error_message(request, Data.MultipleObjectsReturned) ranked.sort(lambda x, y: x[1] - y[1]) try: stats = [[stat, Data.objects.get(item=item,source=stat,scheme__type='s')] for stat in stats] except Data.MultipleObjectsReturned: # should never happen, unless stats have a problem (i.e. duplicate entries) stats = [[stat, Data.objects.filter(item=item,source=stat,scheme__type='s')[0]] for stat in stats] utils.send_error_message(request, Data.MultipleObjectsReturned) n = len(ranked) try: wiki_entry = WikiEntry.objects.get(item=item) except WikiEntry.DoesNotExist: wiki_entry = None if ajax: return render_response(request, 'items/item_detail_content.html', {'item': item, 'title': u'Cities', 'rankings': ranked, 'stats': stats }) highlight_item = page_containing_item = item_row = None if 'current_ranking' in request.session: try: rank = request.session['current_ranking'].index(item) page_containing_item = rank / CitiesPerPage item_row = rank - page_containing_item * CitiesPerPage highlight_item = True except ValueError: print "item", item, "not in", request.session['current_ranking'] params = {'item': item, 'rankings': ranked, 'highlight_item': highlight_item, 'page': page_containing_item, 'row': item_row, 'wiki_entry': wiki_entry, 'stats': stats } if(n > 5): params['strengths'] = ranked[:3] params['weaknesses'] = ranked[-3:] strengths = ranked[:3] weaknesses = ranked[-3:] return render_response(request, 'items/item_detail.html', params)
def gallery_detail(request, id): weighting = UserRanking.objects.get(id=id) weightings = weighting.weights.all() items = Item.objects.all() # counts = [utils.sources_for_item(c).count() for c in items] # json_map = utils.items_to_json(items, counts) return render_response(request, 'items/gallery_detail.html', {'weighting': weighting, 'weightings': weightings, 'json_table': weighting.json}) #, 'json_map': json_map}) #, 'item_data': zip(items, ranks, rankMax, values)})
def explore(request): """Explore Page.""" data = {} day = request.GET.get('day', '') data['day'] = day if day: results = shows.get_shows_per_day(day) data['shows'] = results return render_response(request, 'explore.html', data)
def datasource_list(request): check_session_version(request) sources = DataSource.objects.filter(datascheme__type='r', active=True).order_by('id') sources_to_aggregate = request.session.get('sources_to_aggregate', DefaultSources) for source in sources: source.aggregate = source in sources_to_aggregate return render_response(request, 'items/ranking_list.html', {'sources': sources, 'ranking_id': request.session.get('ranking_id', 100) + 1})
def gallery_list(request): weightings = UserRanking.objects.all().order_by('-created') latest = weightings[0:10] feature_group = Group.objects.get(name=u'Featured') featured = UserRanking.objects.filter(creator__groups=feature_group).order_by('-created') return render_response(request, 'items/gallery_list.html', {'latest': latest, 'featured': featured })
def update(request): """Update Page.""" showid = request.GET.get('showid', '') updateAll = request.GET.get('updateAll', False) == "True" if updateAll: shows.update_all() elif showid: shows.update_show(showid) data = shows.get_shows_to_update() return render_response(request, 'update.html', data)
def genres(request): """Genre Page.""" data = {} genre = request.GET.get('genre', '') data['genre'] = genre if genre: results = shows.get_shows_per_genre(genre) data['shows'] = results data['genres'] = shows.get_genres() return render_response(request, 'genres.html', data)
def new_todo(request): if request.method == 'POST': if request.form['title'] and request.form['text']: new_todo = ToDo(title=request.form['title'], text=request.form['text'], user=request.session["user"]) session.add(new_todo) session.commit() if new_todo: sent_file = request.files['userfile'] if sent_file: todo_file = File(todo=new_todo.id, filename=secure_filename(sent_file.filename), filecontent=sent_file.read()) session.add(todo_file) session.commit() return redirect("/todo/%s" % new_todo.id) else: return render_response("new_todo.html", user=request.session["user"], error="Please enter a title and note for your to do.") else: return render_response("new_todo.html", user=request.session["user"])
def add_item_form(request, lat, long, item, country): countries = Country.objects.all() item_form = ItemForm() if item: item_form.fields['item'] = forms.CharField(initial=item) if country: item_form.fields['country'] = forms.ModelChoiceField(queryset=countries, initial=country.id) return render_response(request, 'items/add_item_form.html', {'lat': lat, 'long': long, 'item': item, 'country': country, 'form': item_form})
def upload(): # Checks to see if the HTML method request is 'POST' if request.method == 'POST': # Checks to make sure a file was uploaded if 'file' not in request.files: return render_response(redirect(request.url)) file = request.files['file'] # Checks to make sure the file has an actual name and not just empty if file.filename == '': return render_response(redirect(request.url)) # Checks to make sure the file extension/type is allowed if '.' in file.filename and file.filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']: # Secures the file name for security purposes filename = secure_filename(file.filename) # Saves the file in the specified upload folder file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return render_response(redirect(url + url_for('media'))) # Returns the file_upload.html template with the given values return render_template('admin_pages/file_upload.html')
def datasource_submit(request): class DataSourceSubmitForm(forms.Form): name = forms.CharField(max_length=100, required=True) shortname = forms.CharField(max_length=100, required=True) source = forms.CharField(max_length=100, required=True) description = forms.CharField(widget=forms.widgets.Textarea()) file = forms.FileField(required=True) form = DataSourceSubmitForm() return render_response(request, 'items/ranking_submit.html', {'form': form })
def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): new_user = form.save() return HttpResponseRedirect("/") else: form = UserCreationForm() return render_response(request, "registration/register.html", { 'form': form, })
def index( request): if request.method == 'GET': return render_response('upload.html',request) elif request.method == 'POST': try: ufile = request.FILES['file'] except: context = {'error':'File is Mandatory. Please choose a file'} return render_response('upload.html', request, context) fileMap = FileLink() fileMap.externalName = ufile fileMap.linkSuffix = uuid.uuid4() fileMap.created_on = datetime.datetime.now() fileMap.password_protected = request.POST.get('password_protected', False) fileMap.password = request.POST.get('password') fileMap.save() internal_name = handle_uploaded_file(ufile,fileMap) externalLink = "http://%s/download?fileName=%s" % (request.get_host(),internal_name) return HttpResponse("File Uploaded. Here is the <a target='_blank' href='%s'>link</a>" % externalLink)
def index(request): check_session_version(request) sources_to_aggregate = request.session.get('sources_to_aggregate', DefaultSources) source_weights = request.session.get('source_weights', DefaultWeights) from django.conf import settings weightings = UserRanking.objects.all().order_by('-created') latest = weightings[0:15] return render_response(request, 'index.html', {'latest': latest })
def add_item_submit(request): lat = request.GET.get('lat', '') long = request.GET.get('long', '') name = request.GET.get('item', '') country_id = request.GET.get('country', '') country = Country.objects.get(id=country_id) item = Item(name=name, lat=lat, long=long, tld=country.tld) item.save() return render_response(request, 'items/add_item_submit.html')
def signup(): """signup() Serves the signup page or signs the user up, depending on the request method Accessed at '/signup' via a GET or POST request """ # If the request is a POST request, attempts to create the user using the form input if request.method == 'POST': # Checks for an existing user with the same email if get_user(request.form['email']): # Returns the signup page with an error that an account already exists with that email return render_response( render_template('user_pages/signup.html', user_exists=True)) # Creates the salt used in hashing the password salt = str(uuid.uuid4()) # Hashes the password # (?) TODO: Switch hashing to key derivation function hashed_password = hashlib.sha512( (request.form['password'] + salt).encode('utf-8')).hexdigest() # Creates the user with the values from the form and the hashed password user = User(email=request.form['email'], password=hashed_password, salt=salt, first_name=request.form['first-name'], last_name=request.form['last-name'], authenticated=True) user.save() # Creates a session for the user session = login_user(user) # Sets the session cookie and redirects to the homepage return render_response(redirect(url + url_for('index')), cookies={'__session': session.session_key}) # If the request is a GET request, returns the signup page return render_response(render_template('user_pages/signup.html'))
def login(): """login() Serves the login page or logs the user in, depending on the request method Accessed at '/login' via a GET or POST request """ # If the request is a POST request, attempts to log the user in using the form input if request.method == 'POST': # Looks for a user with the provided email user = get_user(request.form['email']) # If the user exists, attempts to log the user in if user: # Creates the hashed password # (?) TODO: Switch hashing to key derivation function hashed_password = hashlib.sha512( (request.form['password'] + str(user.salt)).encode('utf-8')).hexdigest() # Checks if the provided password matches the user's password if user.password is not None and hashed_password == user.password: # Marks the user as authenticated user.authenticated = True user.save() # Creates a session for the user session = login_user(user) # Sets the session cookie and redirects to the homepage return render_response( redirect(url + url_for('index')), cookies={'__session': session.session_key}) # Returns the login page with an error that the login failed return render_response( render_template('user_pages/login.html', failed_login=True)) # If the request is a GET request, returns the login page return render_response(render_template('user_pages/login.html'))
def signin(request): if request.method == 'POST': error = None if not request.form['email'] or not request.form['password']: error = "Please enter your e-mail and password" email = request.form['email'] password = hashlib.md5() password.update(request.form['password']) password = password.hexdigest() user = session.query(User).filter_by(email=email).first() if not user: error = "You have entered an invalid email." else: if user.password != password: error = 'You have entered an invalid password. \ Did you <a href="/newpassword">forget your password?</a>' if not error: request.session["user"] = user.userid return redirect("/") else: return render_response("signin.html", error=error) else: return render_response("signin.html")
def bugs(request): class ContactForm(forms.Form): name = forms.CharField(initial=request.user.username, label="Name (optional)", required=False) email = forms.EmailField(label="E-mail (optional)", required=False) url = forms.URLField(initial=request.META.get('HTTP_REFERER'), required=False) message = forms.CharField(widget=forms.widgets.Textarea()) if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): message = request.POST.get('message', '') name = request.POST.get('name', '') url = request.POST.get('url', '') subject = '[Django] Bug report for ' + url + ' user id = ' + str(request.user.id) message += '\n\n======== DEBUG INFORMATION ==========\n\nurl: ' + url + '\n\n\n### BEGIN pickle.dumps(request.session[sources_to_aggregate] ###\n' + pickle.dumps(request.session['sources_to_aggregate'], 0) + '\n\n\n### BEGIN pickle.dumps(request.session[weightings] ###\n' + pickle.dumps(request.session['source_weights']) from_email = request.POST.get('email', '') send_mail(subject, message, '%s <%s>' % (name, from_email), ['*****@*****.**']) return render_response(request, 'bugs_thanks.html', {'form': form, 'url': url}) else: return render_response(request, 'bugs.html', {'form': form}) else: form = ContactForm() return render_response(request, 'bugs.html', {'form': form})
def users(): """users() Serves the users page with all of the users Accessed at '/users' via a GET request Requires that the user is logged in """ # Gets basic information for all users # Does NOT contain passwords, salt, or any other sensitive data users = User.get_all_users() # Returns the user page with the users data return render_response( render_template('admin_pages/edit_users.html', users=users))
def forgot_password(): """forgot_password() Serves the forgot password page or creates a temporary password the user can use to reset their password, depending on the request method Accessed at '/forgot_password' via a GET or POST request """ # If the request is a POST request, creates a temporary password for the user to reset their password if request.method == 'POST': # Gets the user by email user = get_user(request.form['email']) # Checks that the user exists if user: # Creates a temporary password and an expiration time of 15 minutes later user.temp_password = ''.join( random.choices(string.ascii_uppercase + string.digits, k=12)) user.temp_password_expire = datetime.now() + timedelta(minutes=15) user.save() # Emails the temporary password to the user's email address mail = Mail( user.email, 'Temporary Password', '<p>Here is your temporary password:</p><h3>' + user.temp_password + '</h3>') # Returns the next page where the user provides the temporary password to verify they own the account return render_response( render_template('user_pages/reset_password_1.html', email=user.email)) # Returns the forgot password page with an error that their is not an account with the email provided return render_response( render_template('user_pages/forgot_password.html', no_account=True)) # Returns the forgot password page return render_response(render_template('user_pages/forgot_password.html'))
def data_submit_final(request): assert request.method == 'POST' assert 'new_stats' in request.session assert 'new_data_values' in request.session values = request.session['new_data_values'] ranks = request.session['new_data_ranks'] newStat = request.session['new_stats'] items = [None] * len(values) for key, value in request.POST.items(): if key[0] == 'c': # a item id = int(key.lstrip("item")) value = int(value) if value > -1: items[id] = value else: items[id] = None source = DataSource(name=newStat['name'], shortname=newStat['shortname'], source=newStat['source'], description=newStat['description'], category=newStat['category'], creator=request.user, active=False) source.save() if newStat['indicator']: schemeW = DataScheme(source=source, type='w', description=newStat['data_label']) schemeR = DataScheme(source=source, type='r', description='Rank') schemeW.save() schemeR.save() for value, rank, item in zip(values, ranks, items): if item: matchedItem = Item.objects.get(id=item) datum = Data(source=source,scheme=schemeW, item=matchedItem, value=value) datum.save() datum = Data(source=source,scheme=schemeR, item=matchedItem, value=rank) datum.save() else: scheme = DataScheme(source=source, type='s', description=newStat['data_label']) scheme.save() for value, item in zip(values, items): if item: matchedItem = Item.objects.get(id=item) datum = Data(source=source,scheme=scheme, item=matchedItem, value=value) datum.save() return render_response(request, 'items/data_submit_final.html')
def index(request): if request.method == 'GET': return render_response('upload.html', request) elif request.method == 'POST': try: ufile = request.FILES['file'] except: context = {'error': 'File is Mandatory. Please choose a file'} return render_response('upload.html', request, context) fileMap = FileLink() fileMap.externalName = ufile fileMap.linkSuffix = uuid.uuid4() fileMap.created_on = datetime.datetime.now() fileMap.password_protected = request.POST.get('password_protected', False) fileMap.password = request.POST.get('password') fileMap.save() internal_name = handle_uploaded_file(ufile, fileMap) externalLink = "http://%s/download?fileName=%s" % (request.get_host(), internal_name) return HttpResponse( "File Uploaded. Here is the <a target='_blank' href='%s'>link</a>" % externalLink)
def guest(request): """Guest Page.""" shows_filter = '' if 'shows' in request.GET: shows_filter = request.GET['shows'] request.session['filter'] = shows_filter elif request.session.get('filter', False): shows_filter = request.session['filter'] else: shows_filter = 'all' data = {} most_rated = shows.get_most_rated_shows() data['recommended'] = most_rated data['filter'] = shows_filter return render_response(request, 'guest/guest.html', data)
def show_ayat(request, surah_num, ayat_num, translator): try: qobj = quran.objects.get(surah_num = surah_num, ayat_num = ayat_num) except ObjectDoesNotExist: return HttpResponse('No quran object found') try: tiobj = translation_info.objects.get(tr_slug__exact = translator) except ObjectDoesNotExist: return HttpResponse('No translator object found') trobj = translation.objects.filter(quran_s__exact = qobj.id, trans_info_s__exact = tiobj.id) if trobj.count() == 0: return Http404 return render_response(request, 'quran/ayat.html',{'ayat':trobj[0].text, 'surah_num':surah_num, 'ayat_num':ayat_num, 'translator':'arabic'})
def explain(request): sources_to_aggregate = DataSource.objects.filter(id__in=[19,20,21,22]) weights = {} for source in sources_to_aggregate: weights[source] = 10 json_table, items, ranked, display, pairwise, after = aggregation_as_json(request, sources_to_aggregate, weights, include_all_sources=True, debugging=True) all_sources = DataSource.objects.filter(datascheme__type='r') for source in all_sources: source.aggregate = source in sources_to_aggregate ranking_id = request.session.get('ranking_id', 100) + 1 request.session['ranking_id'] = ranking_id return render_response(request, 'items/explain.html', {'json_table': json_table, 'sources': sources_to_aggregate, 'items': items, 'pairwise': zip(items, pairwise), 'pairwise_after': zip(items, after), 'debugging': True, 'json_table': json_table, 'data': map(None, ranked, display) })
def history(): """history() Serves the history page with the user's history Accessed at '/history' via a GET request Requires that the user is logged in """ # The current user's history history = current_user.history # The array with the history information to pass to the history page # [[(page_id, history)]] history_arr = [] # Sorts the history for i in range(len(history)): for j in range(i + 1, len(history)): if history[i]['last_updated'].replace( tzinfo=None) < history[j]['last_updated'].replace( tzinfo=None): history[i], history[j] = history[j], history[i] # Builds the array to pass to the history page for hist in history: # The array with the history information for this history new_arr = [] # Gets the story the history belongs to story_ref = db.collection('stories').document(hist['story']) story_doc = story_ref.get() # Adds each page in this history to the array for page_id in hist['pages']: # Gets the page data by page ID page = story_doc.get('page_nodes.`' + page_id + '`') # Adds the page's name and link new_arr.insert(0, (page['page_name'], hist['story'] + "/" + page_id)) # Appends the history_arr.append(new_arr) # Returns the history page with the history data return render_response( render_template('user_pages/history.html', history=history_arr))
def logout(): """logout() Logs the user out of the application Accessed at '/logout' via a GET request Requires that the user is logged in """ # Gets the current user, since the current user will be lost once authenticated is set to false user = __get_current_user() # Sets the user to unauthenticated user.authenticated = False user.save() # Deletes the session associated with the user Session.delete_session(user_id=user.email) # Deletes the session cookie and redirects to the homepage of the application return render_response(redirect(url + url_for('index')), delete_cookies=['__session'])
def home(request): """Home Page.""" if request.session.get('new_user', False): shows_info = request.session["from_guest"] for val in shows_info: if val.isdigit(): shows.get_show_by_id(val, request.user) shows_filter = '' if 'shows' in request.GET: shows_filter = request.GET['shows'] request.session['filter'] = shows_filter elif request.session.get('filter', False): shows_filter = request.session['filter'] else: shows_filter = 'all' data = shows.get_shows_per_user(request.user, shows_filter) most_rated = shows.get_most_rated_shows(request.user) data['recommended'] = most_rated data['filter'] = shows_filter return render_response(request, 'index.html', data)
def report(request): """Report Page.""" return render_response(request, 'report.html')
def test_form(request): return render_response(request, 'test_form.html')
def about(request): """About Page.""" return render_response(request, 'about.html')
def sign_up(request): """Sign Up Page.""" return render_response(request, 'sign-up.html')
def dashboard(request): return render_response(request, 'dashboard.html')
def profile(request): """Profile Page.""" return render_response(request, 'profile.html')
def guest_login(request): following = request.GET.get('following', "").split(",") request.session['from_guest'] = following request.session['new_user'] = True return render_response(request, 'guest/guest_login.html')