def update_student(sid): #---------------------------------- if not (auth.if_auth()): return redirect(url_for('login')) #---------------------------------- form = StudentForm() if form.validate(): student_id = sid session = db.Session() user = session.query(Student).filter_by(id=sid).first() if user: form.populate_obj(user) # Обновляем принадлежность к группе if user.group == '': user.user_id = None else: if not (auth.user_is_admin()): user.user_id = auth.get_user_id() # Сохраняем session.commit() return redirect(url_for('groups')) params = dict() params['student_id'] = sid params['form'] = form params['username'] = auth.get_user_name() return render_template('students/edit_student.html', params=params)
def show_groups(): #---------------------------------- if not (auth.if_auth()): return redirect(url_for('login')) #---------------------------------- user_id = auth.get_user_id() session = db.Session() users = session.query( Student.group, Student.id, Student.firstname, Student.lastname, Student.middlename, Student.birth_date).filter_by(user_id=user_id).order_by( Student.group).all() # 4 groups = {} for user in users: group = user[0] sid = user[1] firstname = user[2] lastname = user[3] middlename = user[4] birth_date = user[5] if not (group in groups): groups[group] = [] (groups[group]).append({ 'id': sid, 'firstname': firstname, 'lastname': lastname, 'middlename': middlename, 'birth_date': birth_date.strftime('%d-%m-%Y') }) params = dict() params['username'] = auth.get_user_name() params['groups'] = groups return render_template('students/groups.html', params=params)
def edit_item(category_name, item_name): category = session.query(Category).filter_by(name=category_name).one() edited_item = session.query(Item).filter_by(name=item_name, category_id=category.id).one() # Authorisation - check if current user can edit the item # Only a user who created an item can edit/delete it user_id = get_user_id(login_session['email']) if edited_item.user_id != user_id: message = json.dumps('You are not allowed to edit the item') response = make_response(message, 403) response.headers['Content-Type'] = 'application/json' return response # Post method if request.method == 'POST': if request.form['name']: edited_item.name = request.form['name'] if request.form['description']: edited_item.description = request.form['description'] if request.form['category']: category = session.query(Category).filter_by(name=request.form ['category']).one() edited_item.category = category session.add(edited_item) session.commit() return redirect(url_for('show_category', category_name=edited_item.category.name)) else: categories = session.query(Category).all() return render_template('edititem.html', item=edited_item, categories=categories)
def get_item_page(id): categories = db_utils.get_categories() item = db_utils.get_item(id) recent_items = db_utils.get_recent_items(5) if item is None: return render_template('404.html') item.nice_date = '{month} {day}, {year}'.format( month=calendar.month_name[item.created_at.month], day=item.created_at.day, year=item.created_at.year) signed_in = auth.is_signed_in() is_user_admin = False is_item_owner = False if signed_in: is_user_admin = auth.is_user_admin() is_item_owner = item.user_id == auth.get_user_id() return render_template( 'item.html', id=id, categories=categories, item=item, recent_items=recent_items, CLIENT_ID=CLIENT_ID, signed_in=signed_in, is_user_admin=is_user_admin, is_item_owner=is_item_owner, user_name=auth.get_user_name(), picture=login_session.get('picture'), SIGNIN_REQUEST_TOKEN=auth.get_signin_request_token())
def process_unfollowed(): print("Process unfollowed") if auth.authenticated(): print("User is authenticated. Unfollowed will be processed...") list_members = get_list_members(MNG_UNFOLLOWED, auth.get_user_id()) print_list_stats(list_members) u = 0 following = 0 not_following_dict = {} for m in list_members: u = u + 1 print("#### User %d ####" % u) user_dict = m.AsDict() m_id = user_dict["id"] m_screename = user_dict["screen_name"] # TODO: LookupFriendship() should be a bit more efficient friendship_data = auth.api.ShowFriendship(auth.get_user_id(),None,m_id,None) # Check friendship between the two users (the authenticated user and the one on the list) src_tar = friendship_data["relationship"] src = src_tar["source"] if not src["followed_by"]: print("%s IS NOT following!" % m_screename) not_following_dict[m_id] = m_screename # Unfriend user auth.api.DestroyFriendship(m_id,None) print("User %s unfriended" % m_screename) # Remove user from this list and pass it to the following list in the pipeline auth.api.DestroyListsMember(None,MNG_UNFOLLOWED,None,auth.get_user_id(),m_id,None) auth.api.CreateListsMember(None,MNG_UNFOLLOWED_BACK,m_id,None,None,auth.get_user_id()) print("User %s deleted from %s list and added to %s" % (m_screename,MNG_UNFOLLOWED,MNG_UNFOLLOWED_BACK)) else: following += 1 print("Total users following: %s" % following) print("Total users NOT following (and moved): %s %s" % (len(not_following_dict), not_following_dict)) else: print("Please, check authentication tokens")
def process_unfollowed_me(): print("Unfollowed stats") if auth.authenticated(): print("User is authenticated. Unfollowed stats will be listed...") list_members = get_list_members(MNG_UNFOLLOWED_ME, auth.get_user_id()) print_list_stats(list_members) else: print("Please, check authentication tokens")
def login_as_producer(): code_auth = request.args.get('code') token = get_access_token(code_auth) user_id = get_user_id(token) api_token = get_MGMT_API_ACCESS_TOKEN() payload = verify_decode_jwt(token) if 'permissions' not in payload: abort(400) permissions = payload.get('permissions') if len(permissions) == 0: url3 = f'https://{AUTH0_DOMAIN}/api/v2/users/{user_id}/roles' headers = { 'content-type': 'application/json', 'authorization': 'Bearer ' + api_token, 'cache-control': 'no-cache' } data = '{ "roles": [ " rol_t2ets4eZtnaqf6Xo " ] }' data = data.encode('ascii') req3 = uri.Request(url3, data, headers) try: uri.urlopen(req3) except uri.URLError as e: print('URL Error: ', e.reason) except uri.HTTPError as e: print('HTTP Error code: ', e.code) else: session['role'] = 'producer' return redirect(url_for('home')) if 'delete:movie' in permissions: session['role'] = 'producer' elif 'delete:movie' not in permissions and 'delete:actor' \ in permissions: session['role'] = 'director' elif 'delete:actor' not in permissions: session['role'] = 'Casting Assistant' return redirect(url_for('home'))
def item_new_post(form): '''item_new POST handler''' params = {} params['name'] = form.name.data params['description'] = form.description.data params['price'] = form.price.data params['category_id'] = form.category_id.data params['user_id'] = get_user_id(login_session) item = Item(**params) session.add(item) session.commit() flash('New Item <strong>%s</strong> Successfully Created!' % (item.name), 'success') return redirect(url_for('item_view', item_id=item.id))
def get(self): user = get_current_user(self.request) template = JINJA_ENVIRONMENT.get_template('templates/index.html') lists = List.query(ndb.OR(List.owner == user.key, List.public == True)).fetch() item_name_filter = self.request.get('filter_by_name') item_type_filter = self.request.get('filter_by_item_type') item_condition_filter = self.request.get_all('filter_by_condition') item_color_filter = self.request.get_all('filter_by_color') item_color_grouping_filter = self.request.get('filter_by_color_grouping') item_article_filter = self.request.get('filter_by_article') costume_size_string_filter = self.request.get('filter_by_costume_size_string') costume_size_number_min = self.request.get('filter_by_costume_size_min') costume_size_number_max = self.request.get('filter_by_costume_size_max') if not costume_size_number_max: costume_size_number_max = "26" if not costume_size_number_min: costume_size_number_min = "0" exclude_unknown_size = self.request.get('excludeUnknownSize', '') == "true" tags_filter = self.request.get('filter_by_tags') tags_grouping_filter = self.request.get('filter_by_tag_grouping') availability_filter = self.request.get('filter_by_availability') user_id = auth.get_user_id(self.request) items = filterItems( user_id, item_name_filter, item_type_filter, item_condition_filter, item_color_filter, item_color_grouping_filter, item_article_filter, costume_size_string_filter, costume_size_number_min, costume_size_number_max, exclude_unknown_size, tags_filter, tags_grouping_filter, availability_filter, outdated=False) # send to display page = template.render({ 'lists': lists, 'user': user, 'items': items, 'user_id': user_id}) page = page.encode('utf-8') self.response.write(validateHTML(page))
def post(self): user = auth.get_user_id(self.request) to_check_out = self.request.get_all('keys') reason = self.request.get('reason') while to_check_out: urlsafe_key = to_check_out.pop() item = ndb.Key(urlsafe=urlsafe_key).get() if item.key.parent() != None: to_check_out.append(item.key.parent().urlsafe()) item.checked_out = True item.checked_out_by = user item.checked_out_by_name = get_current_user(self.request).name item.checked_out_reason = reason item.put() self.redirect("/")
def add_student(): #---------------------------------- if not (auth.if_auth()): return redirect(url_for('login')) #---------------------------------- student = Student() form = StudentForm(obj=student) if form.validate(): session = db.Session() form.populate_obj(student) user_id = auth.get_user_id() student.user_id = user_id session.add(student) session.commit() return redirect(url_for('groups')) params = dict() params['form'] = form params['username'] = auth.get_user_name() return render_template('students/edit_student.html', params=params)
def delete_item(category_name, item_name): category = session.query(Category).filter_by(name=category_name).one() item_to_delete = session.query(Item).filter_by(name=item_name, category=category).one() # Authorisation - check if current user can edit the item # Only a user who created an item can edit/delete it user_id = get_user_id(login_session['email']) if item_to_delete.user_id != user_id: message = json.dumps('You are not allowed to delete the item') response = make_response(message, 403) response.headers['Content-Type'] = 'application/json' return response if request.method == 'POST': session.delete(item_to_delete) session.commit() return redirect(url_for('show_category', category_name=category.name)) else: return render_template('deleteitem.html', item=item_to_delete)
def get_my_items_page(user_id=0): if user_id == 0 and not auth.is_signed_in(): # This would be reached when /myitems is requested. # Redirect to login page. # The url to which we are redirected will contain a paramenter # which will be the url to redirect back to # after logging in redirect_parameter = 'redirect={}'.format(url_for('get_my_items_page')) url = '{path}?{parameter}'.format(path=url_for('get_login_page'), parameter=redirect_parameter) return redirect(url, 302) page_title = 'My Items' if user_id != 0: user = db_utils.get_user(user_id) page_title = 'Items by {}'.format(user.name) categories = db_utils.get_categories() items = db_utils.get_user_items(user_id if user_id else auth.get_user_id()) for item in items: item.nice_date = '{month} {day}, {year}'.format( month=calendar.month_name[item.created_at.month], day=item.created_at.day, year=item.created_at.year) signed_in = auth.is_signed_in() is_user_admin = False if signed_in: is_user_admin = auth.is_user_admin() return render_template( 'index.html', page_title=page_title, categories=categories, items=items, CLIENT_ID=CLIENT_ID, signed_in=signed_in, is_user_admin=is_user_admin, user_name=auth.get_user_name(), picture=auth.get_user_picture(), SIGNIN_REQUEST_TOKEN=auth.get_signin_request_token())
def post(self): user = get_current_user(self.request) if (user.permissions == wmodels.PENDING_USER or user.permissions == wmodels.DEACTIVATED_USER): self.redirect('/') return try: image_data = self.request.get('image', default_value='') image_url = '' if image_data == '' and self.request.get('duplicate') == "True": image_url = ndb.Key(urlsafe=self.request.get('original_item')).get().image_url elif image_data != '': image_url = saveImageInGCS(image_data) article_type = self.request.get('article') costume_or_prop = self.request.get('item_type') costume_size_number = self.request.get('clothing_size_number') if costume_size_number == "N/A": costume_size_number = -1 else: costume_size_number = int(costume_size_number) costume_size_word = self.request.get('clothing_size_string') tags_string = self.request.get('tags') # Override certain inputs due to costume and prop defaults if costume_or_prop == "Costume" and article_type == "N/A": # An article type was not selected thus is filtered as an # 'Other' item by default article_type = "Other" elif costume_or_prop == "Prop": # Props do not have sizes or article types article_type = "N/A" costume_size_number = -1 costume_size_word = "N/A" # tags is a string. Needs to parsed into an array tags_list = parseTags(tags_string) # Create Item and add to the list duplication = self.request.get('times_to_duplicate') d = int(duplication) while d > 0: qr_code, _ = Item.allocate_ids(1) Item( id=qr_code, creator_id=auth.get_user_id(self.request), creator_name=auth.get_user_name(self.request), name=self.request.get('name'), image_url=image_url, item_type=costume_or_prop, condition=self.request.get('condition'), item_color=self.request.get_all('color'), clothing_article_type=article_type, clothing_size_num=costume_size_number, qr_code=qr_code, description=self.request.get('description', default_value=''), clothing_size_string=costume_size_word, tags=tags_list).put() d = d - 1; #sleep(0.1) next_page = self.request.get("next_page") if next_page == "Make Another Item": self.redirect("/add_item") else: self.redirect("/search_and_browse") except: # Should never be here unless the token has expired, # meaning that we forgot to refresh their token. self.redirect("/enforce_auth")
import hashlib import subprocess import datetime import sys import ConfigParser import pgdb import boto.ses import xml.sax.saxutils from auth import passwd_changer import cgitb cgitb.enable() import auth # user_id = os.environ["REMOTE_USER"] user_id = auth.get_user_id('admin') # Config config = ConfigParser.RawConfigParser() config.read('/home/ec2-user/html/config/config') if config.has_option('all', 'admin_email'): admin_email = config.get('all', 'admin_email') if config.has_option('all', 'dns_name'): sitename = config.get('all', 'dns_name') if config.has_option('all', 'http_or_https'): http_or_https = config.get('all', 'http_or_https') else: http_or_https = "http" ses_region_name = "us-west-2"
def get_edit_item_page(id=0): if request.method == 'GET': if not auth.is_signed_in(): # Redirect to login page. # The url to which we are redirected will contain a paramenter # which will be the url to redirect back to # after logging in redirect_parameter = None if id and id != 0: redirect_parameter = 'redirect={}'.format( url_for('edit_item', id=id)) else: redirect_parameter = 'redirect={}'.format(url_for('new_item')) url = '{path}?{parameter}'.format( path=url_for('get_login_page'), parameter=redirect_parameter) return redirect(url, 302) categories = db_utils.get_categories() item = None if id and id != 0: item = db_utils.get_item(id) if item is None: return render_template('404.html') else: if (not auth.is_user_admin() and item.user_id != auth.get_user_id()): # Cannot edit item that does not belong to user # But admins are allowed return render_template('unauthorized.html') return render_template('edit-item.html', item=item, categories=categories, CLIENT_ID=CLIENT_ID, signed_in=auth.is_signed_in(), user_name=auth.get_user_name(), picture=login_session.get('picture')) elif request.method == 'POST': # This is meant to be reached from AJAX request. # We return a JSON response that will be used by # The JS code making the request. if not auth.is_signed_in(): return response.error('Unauthorized') if id and id != 0: # Update item item = db_utils.get_item(id) if (not auth.is_user_admin() and item.user_id != auth.get_user_id()): # Only item owners and admins allowed to update item return response.error('Unauthorized') if (request.form['name'] and request.form['desc'] and request.form['cat-id']): item = db_utils.update_item(request.form['item-id'], request.form['name'], request.form['desc'], request.form['cat-id']) itemData = { 'id': item.id, 'name': item.name, 'desc': item.desc, 'short_desc': item.short_desc, 'category_id': item.category_id } return response.success( url_for('get_item_page', id=itemData['id']), itemData) else: return response.error('Failed to save') else: # Create new item if (request.form['name'] and request.form['desc'] and request.form['cat-id']): item = db_utils.add_item(request.form['name'], request.form['desc'], request.form['cat-id'], auth.get_user_id()) itemData = { 'id': item.id, 'name': item.name, 'desc': item.desc, 'short_desc': item.short_desc, 'category_id': item.category_id } return response.success( url_for('get_item_page', id=itemData['id']), itemData) else: return response.error('Failed to save')
#!/usr/bin/python # -*- coding: utf-8 -*- import cgi import os import sys import hashlib import cgitb cgitb.enable() import auth # user_id = os.environ["REMOTE_USER"] module_name = "init/user2.py" user_id = auth.get_user_id(module_name) template_html = "base.html" title = "User Configuration" # current_user = os.environ["REMOTE_USER"] # -------------- additional_js = "" # -------------- # Form value form = cgi.FieldStorage() sys.stderr.write(str(form.keys()) + "\n") if 'mode' in form: mode = str(form.getfirst('mode')) sys.stderr.write(str(mode) + "\n") if mode == 'reg': group_con = auth.read_group_list()