def permission_met(menu): """ This is one of the more complicated methods. It works recursively. When called, it is given the root of the controller hierarchy. It looks for the path to the menu entry, and checks everything that it can along the way: allow_only on all controllers, and the (optional) permission on the method itself (which must be given to the @menu decorator or menu_append, see the README for details why and a workaround). """ global rootcon retval = True if not rootcon: pname = '%s.controllers.root' % (config['package'].__name__) __import__(pname) rootcon = sys.modules[pname].RootController # Check to see if specific menu permission has been set permission = menu._permission if type(permission) is str: try: has_permission(permission).check_authorization(request.environ) return True except NotAuthorizedError: return False elif permission is not None: try: permission.check_authorization(request.environ) return True except: return False else: # No specific menu permission has been set, walk the tree lpath = menu._url.split('/')[1:] currcon = rootcon for component in lpath: if hasattr(currcon, 'allow_only'): try: getattr(currcon, 'allow_only').check_authorization(request.environ) except: return False if hasattr(currcon, component): currcon = getattr(currcon, component) else: break return True
def get_last_ten_worked(self): """Returns last ten worked boxes data.""" entries = None if has_permission('manage'): entries = BoxEngine.get_all_boxes() else: entries = BoxEngine.get_all_user_boxes( request.identity['user']._id) entries = sorted(entries, key=lambda x: x.datetime_of_modify, reverse=True) entries = entries[:5] data = [] for entry in entries: box = {} box['box_id'] = entry.box_id box['name'] = entry.name box['status'] = entry.status box['datetime_of_creation'] = entry.datetime_of_creation.strftime( "%Y-%m-%d %H:%M") box['datetime_of_modify'] = entry.datetime_of_modify.strftime( "%Y-%m-%d %H:%M") data.append(box) return json.dumps(data)
def respond(self): if not self.survey: abort(404, 'No survey for meeting') if not self.survey.active: if not has_permission('admin'): abort(403, 'Survey not avalible') return flash( 'This page is currently disabled. You can see it because you are an admin.', 'warn') form = request.POST if form: user = request.identity and request.identity.get('user') response = SurveyResponse(user=user, provided_name=form.get('_provided_name'), survey=self.survey) DBSession.add(response) requires_ft = bool(form.get('first_time')) for f in self.survey.fields: if f.first_time and not requires_ft: continue fo = f.type_object() v = fo.from_post(form) if v: DBSession.add( SurveyData(response=response, field=f, contents=v)) flash('Response submitted successfully') redirect(base_url='/') else: return {'survey': self.survey}
class RootController(TGController): custom_allow = CustomAllowOnly() smart_allow = SmartDenialAllowOnly() cp = ControlPanel() rest = DaRestController() mounted_app = WSGIAppController(wsgi_app, allow_only=is_user('gustavo')) @expose() def index(self): return "you're in the main page" @expose() @require(is_user('developer')) def commit(self): return 'you can commit' @expose('json:') @require(is_user('developer'), smart_denial=True) def smartabort(self): return {'key': 'value'} @expose() @require(in_group('managers')) @require(has_permission('commit')) def force_commit(self): return 'you can commit'
class Area51Controller(BaseController): allow_only = predicates.has_permission('manage') @expose('onlinelux.templates.admin') def index(self): subcategories = DBSession.query(SubCategory).all() topics = DBSession.query(Topic).all() return dict(subcategories=subcategories, topics=topics) @expose() def submit_product(self, **kw): images = ','.join([StorageManager().store(i) for i in kw.get('form-images')]) del kw['form-images'] p = Product() p.images = images for k, v in kw.items(): p.__setattr__(k, v) DBSession.add(p) DBSession.flush() redirect('/area51') @expose() def submit_article(self, **kw): image = StorageManager().store(kw.get('image')) del kw['image'] a = Article() a.image = image for k, v in kw.items(): a.__setattr__(k, v) DBSession.add(a) DBSession.flush() redirect('/area51')
def index(self, came_from=lurl('/'), failure=None, login=''): """Handle the front-page.""" if request.identity: has_boxes = False if has_permission('manage'): all_boxes = BoxEngine.get_number_of_all_boxes() if all_boxes['created'] > 0 or all_boxes[ 'stopped'] > 0 or all_boxes['started'] > 0: has_boxes = True else: my_boxes = BoxEngine.get_number_of_user_boxes( request.identity['user']._id) if my_boxes['created'] > 0 or my_boxes[ 'stopped'] > 0 or my_boxes['started'] > 0: has_boxes = True return dict(page='index', has_boxes=has_boxes) else: error_msg = None if failure is not None: if failure == 'user-not-found': error_msg = "Пользователь не найден".decode('utf8') elif failure == 'invalid-password': error_msg = "Некорректный пароль".decode('utf8') else: error_msg = "Ошибка авторизации".decode('utf8') return dict(page='index', came_from=came_from, login=login, error_msg=error_msg)
class UsersController(BaseController): """Subcontrollers for lookup. MAIN SITE FOR PROJECT INSTANCE. Parmission allowed only for logged user with added permision named as a project. """ # The predicate that must be met for all the actions in this controller: allow_only = has_permission( project_name, msg=l_('Permission is not sufficient for this user.')) molecules = MoleculesController() select = SelectController() synthesis = SynthesisController() library = LibraryController() results = ResultsController() @expose('molgears.templates.users.index') def index(self): """Main site for project.""" userid = request.identity['repoze.who.userid'] projects = DBSession.query(Projects).all() user = DBSession.query(User).filter_by( user_name=userid).first() perms = [p.permission_name for p in list(user.permissions)] return dict(page='index', userid=userid, projects=projects, perms=perms, pname=project_name)
def get(self): """Returns boxes data.""" entries = None data = [] if has_permission('manage'): entries = BoxEngine.get_all_boxes() for entry in entries: box = [] box.append(entry.box_id) box.append(entry.name) box.append(entry.status) box.append(entry.user.display_name) box.append( entry.datetime_of_creation.strftime("%Y-%m-%d %H:%M")) box.append(entry.datetime_of_modify.strftime("%Y-%m-%d %H:%M")) data.append(box) else: entries = BoxEngine.get_all_user_boxes( request.identity['user']._id) for entry in entries: box = [] box.append(entry.box_id) box.append(entry.name) box.append(entry.status) box.append( entry.datetime_of_creation.strftime("%Y-%m-%d %H:%M")) box.append(entry.datetime_of_modify.strftime("%Y-%m-%d %H:%M")) data.append(box) json_entries = {} json_entries['data'] = data return json.dumps(json_entries)
def _default(self, page=None, *args, **kw): page_slug = dict(slug=page) hooks.notify('flatpages.before_override_template', args=(page_slug, self)) page = model.FlatPage.by_slug(page_slug['slug']) if page is None: abort(404, 'Page not found') permission = page.required_permission if permission and permission != 'public': if permission == 'not_anonymous': predicate = predicates.not_anonymous() else: predicate = predicates.has_permission(permission) if not predicate.is_met(request.environ): abort(403, 'Forbidden') try: userid = request.identity['user'].user_id except: userid = None override_template(RootController._default, page.template) hooks.notify('flatpages.after_override_template', (page, self)) return dict(page=page, tg_cache={'expire': self.CACHE_EXPIRE, 'key': '%s-%s-%s' % (page.slug, page.updated_at, userid)})
class ManagementController(BaseController): # Uncomment this line if your controller requires an authenticated user allow_only = predicates.has_permission('administration', msg=l_('Only for administrators')) history = HistoryController() def _before(self, *args, **kw): tmpl_context.page_name = "Fortressd" @expose('fortress.templates.management.index') def index(self): """Handle the front-page.""" return dict(page='index') @expose('fortress.templates.management.data_centers') def data_centers(self): """Handle the front-page.""" return dict(page='index') @expose('fortress.templates.management.data_servers') def data_servers(self): """Handle the front-page.""" return dict(page='index') @expose('fortress.templates.management.users') def users(self): """Handle the front-page.""" return dict(page='index') @expose('fortress.templates.management.authorizations') def authorizations(self): """Handle the front-page.""" return dict(page='index')
class SecureController(BaseController): """Sample controller-wide authorization""" # The predicate that must be met for all the actions in this controller: allow_only = has_permission( 'manage', msg=l_('Only for people with the "manage" permission')) @expose('addrbook.templates.index') def index(self): """Let the user know that's visiting a protected controller.""" flash(_("Secure Controller here")) try: username = self.username() except: username = "" return dict(page='index', contacts=[], user="******", total=0, partial=0) @expose('addrbook.templates.index') def some_where(self): """Let the user know that this action is protected too.""" return dict(page='some_where')
def _default(self, page=None, *args, **kw): page = model.FlatPage.by_slug(page) if page is None: abort(404, 'Page not found') permission = page.required_permission if permission and permission != 'public': if permission == 'not_anonymous': predicate = predicates.not_anonymous() else: predicate = predicates.has_permission(permission) if not predicate.is_met(request.environ): abort(403, 'Forbidden') try: userid = request.identity['user'].user_id except: userid = None override_template(RootController._default, page.template) hooks.notify('flatpages.before_render_page', (page, )) return dict(page=page, tg_cache={ 'expire': self.CACHE_EXPIRE, 'key': '%s-%s-%s' % (page.slug, page.updated_at, userid) })
def get_news(self, **kw): """Handle the 'main_user' page.""" freeday=DBSession.query(FreeDay).all() news_show=DBSession.query(News_show).all() users=DBSession.query(User).all() u=request.identity['user'] userr_id=u.user_id lret=list() number=0; if has_permission('manage'): number=DBSession.query(News_show).filter(News_show.admin_show == 1).count(); else: number=DBSession.query(News_show).filter(News_show.user_show == 1).filter(News_show.id_user == userr_id).count(); # # number=DBSession.query(News_show).filter(News_show.user_show == 1).filter(News_show.id_user == userr_id).count(); # lret.append("<li class='active' data-toggle='dropdown'><a href='#'><span class='glyphicon glyphicon-bell'></span>") lret.append("<span class='badge pull-right'>" + str(number) + "</span>") lret.append("<span class='sr-only'>(current)</span></a></li><ul class='dropdown-menu'></ul>") lret.append("<ul class='dropdown-menu'>") for news in news_show: if has_permission('manage'): if news.admin_show == 1: print ("admin--------------------",news.news_id) for freedays in freeday: if news.id_freeday == freedays.id_freeday: print ("admin--------------------",freedays.reason) lret.append("""<li onclick="Update_row_4()">""") lret.append("""<a href='/check_freeday' onclick="Update_row_4('1')">""") lret.append(freedays.reason + "</a></li>") else: for user in users: if user.user_id == userr_id: if news.user_show == 1: print ("user--------------------",news.news_id) for freedays in freeday: if news.id_freeday == freedays.id_freeday and freedays.user_id == userr_id: print ("user--------------------",freedays.reason) lret.append("""<li onclick="Update_row_5()">""") lret.append("""<a href='/userhd' onclick="Update_row_5('1')">""") lret.append(freedays.reason + "</a></li>") html=''.join(lret) return dict(html=html,bar='Alex')
def index(self): if predicates.has_permission('tgapppermissions-admin'): count, permissions = model.provider.query(app_model.Permission) return dict(permissions_count=count, permissions=permissions, mount_point=self.mount_point) else: return redirect(url(self.mount_point + '/users'))
def update_status(self): """Update status of boxes.""" try: if has_permission('manage'): BoxEngine.update_all_boxes_status() else: BoxEngine.update_all_user_boxes_status( request.identity['user']._id) except Exception as ex: return HTTPServerError(ex.message)
def admin_userhd(self, **kw): """Handle the 'userhd' page.""" u=request.identity['user'] userr_id=u.user_id users=DBSession.query(User).all() freeday=DBSession.query(FreeDay).all() vacation=DBSession.query(Vacation).all() if has_permission('manage'): return dict(page='admin_userhd',bar='Alex',users=users, freeday=freeday, uss=userr_id, vacation=vacation, name=u.user_name, us=str(kw['user_id'])) else: return dict(page='admin_userhd',bar='Alex',users=users, freeday=freeday, us=userr_id, vacation=vacation, name=u.user_name)
class SettingController(BaseController): # Uncomment this line if your controller requires an authenticated user allow_only = predicates.has_permission('administration', msg=l_('Only for administrators')) def _before(self, *args, **kw): tmpl_context.page_name = "Fortressd" @expose('fortress.templates.settings.index') def index(self): """Handle the front-page.""" return dict(page='index')
class FlatPagesAdminController(AdminController): allow_only = predicates.has_permission('flatpages') def __init__(self): super(FlatPagesAdminController, self).__init__([model.FlatPage, model.FlatFile], DBSession.wrapped_session, config_type=FlatPagesAdminConfig) @expose() @with_trailing_slash def index(self, *args, **kwargs): return super(FlatPagesAdminController, self).index(*args, **kwargs)
class SurveyController(BaseController): def __init__(self, survey): self.survey = survey @expose('json') @require(has_permission('admin')) def results(self, number=None): responses = self.survey.responses or [] responses = [response_to_dict(r) for r in responses] return { 'count': len(responses), 'responses': responses, 'fields': survey_fields(self.survey), } @expose('acmwebsite.templates.survey') def respond(self): if not self.survey: abort(404, 'No survey for meeting') if not self.survey.active: if not has_permission('admin'): abort(403, 'Survey not avalible') return flash( 'This page is currently disabled. You can see it because you are an admin.', 'warn') form = request.POST if form: user = request.identity and request.identity.get('user') response = SurveyResponse(user=user, provided_name=form.get('_provided_name'), survey=self.survey) DBSession.add(response) requires_ft = bool(form.get('first_time')) for f in self.survey.fields: if f.first_time and not requires_ft: continue fo = f.type_object() v = fo.from_post(form) if v: DBSession.add( SurveyData(response=response, field=f, contents=v)) flash('Response submitted successfully') redirect(base_url='/') else: return {'survey': self.survey}
class RootController(TGController): custom_allow = CustomAllowOnly() smart_allow = SmartDenialAllowOnly() cp = ControlPanel() rest = DaRestController() mounted_app = WSGIAppController(wsgi_app, allow_only=is_user('gustavo')) @expose() def index(self): return "you're in the main page" @expose() @require(is_user('developer')) def commit(self): return 'you can commit' @expose('json:') @require(is_user('developer'), smart_denial=True) def smartabort(self): return {'key': 'value'} @expose() def passthrough_abort(self): abort(403, passthrough='json') @expose() def passthrough_explicit(self): request.disable_auth_challenger() abort(403) @expose() @require(in_group('managers')) @require(has_permission('commit')) def force_commit(self): return 'you can commit' @expose() def login_logout(self, username, noidentifier='0'): if noidentifier == '1': request.environ['repoze.who.plugins'] = {} if username == 'logout': auth_force_logout() else: auth_force_login('%s:managers' % username) return 'OK'
def post_login(self, came_from=lurl('/')): """ Redirect the user to the initially requested page on successful authentication or redirect her back to the login page if login failed. """ if not request.identity: login_counter = request.environ.get('repoze.who.logins', 0) + 1 redirect('/login', params=dict(came_from=came_from, __logins=login_counter)) userid = request.identity['repoze.who.userid'] flash(_('Welcome back, %s!') % userid) if predicates.has_permission('manage'): redirect(came_from) else: redirect(lurl('/graphs/'))
class SecureController(BaseController): """Sample controller-wide authorization""" # The predicate that must be met for all the actions in this controller: allow_only = has_permission( 'manage', msg=l_('Only for people with the "manage" permission')) @expose('tg2express.templates.index') def index(self): """Let the user know that's visiting a protected controller.""" flash(_("Secure Controller here")) return dict(page='index') @expose('tg2express.templates.index') def some_where(self): """Let the user know that this action is protected too.""" return dict(page='some_where')
class StudentController(BaseController): # The predicate that must be met for all the actions in this controller: allow_only = has_permission('instructor') def _get_courses_taught(self, user): return DBSession.query(Course)\ .join(Course.instructors)\ .join(Group.users)\ .filter(User.id == user.id).all() @expose('revsub.templates.viewstudent') def view(self, student_id): login = request.environ.get('repoze.who.identity').get('repoze.who.userid') l_user = DBSession.query(User).filter(User.user_name == login).one() user = DBSession.query(User).filter(User.id == int(student_id)).first() if not user: redirect('/error', params=dict(msg="invalid user")) courses_results = {} courses_taught = self._get_courses_taught(l_user) courses_taught = filter(lambda c: user in c.students.users, courses_taught) sql_s = """ SELECT p.id as paper_id_p, u.*, s.id as summary_id, s.*, p.*, z.avg_rating FROM users u JOIN user_group ug on u.id = ug.user_id JOIN groups g on ug.group_id = g.id JOIN courses c on c.students_id = g.id JOIN papers p on c.id = p.course_id LEFT JOIN paper_summaries s ON s.paper_id = p.id and s.student_id = u.id LEFT JOIN (SELECT s.id, round(avg((r.rating+r.insight_rating)/2),2) as avg_rating FROM paper_summaries s JOIN summary_reviews r on s.id = r.summary_id WHERE s.student_id = :user_id AND r.status = 'complete' GROUP BY s.id ) z on s.id = z.id WHERE u.id = :user_id and c.id = :course_id""" for course in courses_taught: summaries = DBSession.execute(sql_s, dict(course_id=course.id, user_id=user.id)).fetchall() courses_results[course] = summaries reviews = DBSession.query(SummaryReview, PaperSummary, User, Paper)\ .join(SummaryReview.summary).join(PaperSummary.student)\ .join(PaperSummary.paper).filter(SummaryReview.creator_id == user.id).all() return dict(page="viewstudent", student=user, courses=courses_results, reviews=reviews)
def list(self): """Handle the box list page.""" has_boxes = False if has_permission('manage'): all_boxes = BoxEngine.get_number_of_all_boxes() if all_boxes['created'] > 0 or all_boxes[ 'stopped'] > 0 or all_boxes['started'] > 0: has_boxes = True else: my_boxes = BoxEngine.get_number_of_user_boxes( request.identity['user']._id) if my_boxes['created'] > 0 or my_boxes['stopped'] > 0 or my_boxes[ 'started'] > 0: has_boxes = True return dict(page='list', has_boxes=has_boxes)
def get_ways(self, **kw): """Handle the 'main_user' page.""" lret=list() lret.append("<ul class='nav nav-pills nav-stacked span3'>") lret.append("<ul class='nav nav-tabs nav-stacked'>") lret.append(u"""<li role='presentation' ><a href="/">Мои данные</a></li>""") lret.append(u"""<li role='presentation'><a href="/main_user">Сотрудники</a></li>""") if has_permission('manage'): lret.append(u"""<li role='presentation'><a href="/check_freeday">Отпуска и отгулы (проверка)</a></li>""") lret.append(u"""<li role='presentation'><a href="/check_all_freeday">Отпуска и отгулы (всех)</a></li>""") lret.append(u"""<li role='presentation'><a href="/add_new_user">Добавить нового сотрудика</a></li>""") lret.append(u"""<li role='presentation'><a href="/year_list">Отчет за год</a></li>""") else: lret.append(u"""<li role='presentation'><a href="/userhd">Отпуска и отгулы</a></li>""") lret.append("</ul>") lret.append("</ul>") html=''.join(lret) return dict(html=html,bar='Alex')
def delete(self, box_id): """Delete box.""" box_id = int(box_id) try: if not has_permission('manage'): if not BoxEngine.is_author( request.identity['repoze.who.userid'], box_id): return HTTPForbidden( "У Вас нет прав доступа для выполнения действий с этой виртуальной средой" ) BoxEngine.delete_box(box_id) model.History.add_record( request.identity['repoze.who.userid'], None, "Удаление виртуальной среды #" + str(box_id)) except Exception as ex: return HTTPServerError(ex.message)
def get_subdiv(self, **kw): """Handle the 'main_user' page.""" print ("5--------------------",kw) users=DBSession.query(User).all() workers=DBSession.query(Worker).all() lret=list() lret.append("<table class='table table-bordered' id='id_users'>") lret.append(u"""<th><a href="#" onclick="SortTableUsers_1('display_name')">Имя</a></th><th><a href="#" onclick="SortTableUsers_2('subdiv')">Подразделение</a></th><th><a href="#" onclick="SortTableUsers_3('position')">Должность</a></th><th><a href="#" onclick="SortTableUsers_4('work_date')">Дата трудоустройства</a></th>""") for user in users: if has_permission('manage'): lret.append("""<tr><td><a href="/userhd?user_id=${user.user_id}">""" + user.display_name +"</a></td>") #Не хочет определять user else: lret.append("""<tr><td>""" + user.display_name +"</td>") for w in workers: if user.user_id == w.tg_workcol: lret.append("<td>" + w.subdiv + "</td><td>" + w.position + "</td><td>" + str(w.work_date_now) + "</td></tr>") lret.append("</table>") html=''.join(lret) return dict(html=html,bar='Alex',users=users, workers=workers)
def id(self, box_id): """Handle the box page.""" box_id = int(box_id) try: if not has_permission('manage'): if not BoxEngine.is_author( request.identity['repoze.who.userid'], box_id): return HTTPForbidden( "У Вас нет прав доступа для выполнения действий с этой виртуальной средой" ) box = BoxEngine.get_box_by_id(box_id) vagrantfile = BoxEngine.get_vagrantfile_data(box_id) host = get_hostname() except Exception as ex: return HTTPServerError(ex.message) return dict(page='id', box=box, vagrantfile=vagrantfile, host=host)
def copy(self, copied_box_id): """Copy box.""" copied_box_id = int(copied_box_id) try: if not has_permission('manage'): if not BoxEngine.is_author( request.identity['repoze.who.userid'], copied_box_id): return HTTPForbidden( "У Вас нет прав доступа для выполнения действий с этой виртуальной средой" ) box_id = BoxEngine.copy_box(request.identity['repoze.who.userid'], copied_box_id) model.History.add_record( request.identity['repoze.who.userid'], box_id, "Копирование виртуальной среды #" + str(copied_box_id) + " (создана #" + str(box_id) + ")") except Exception as ex: return HTTPServerError(ex.message)
def update_vagrantfile(self, box_id, vagrantfile_text): """Update vagrantfile.""" box_id = int(box_id) try: if not has_permission('manage'): if not BoxEngine.is_author( request.identity['repoze.who.userid'], box_id): return HTTPForbidden( "У Вас нет прав доступа для выполнения действий с этой виртуальной средой" ) BoxEngine.update_vagrantfile(box_id, vagrantfile_text) model.History.add_record( request.identity['repoze.who.userid'], box_id, "Изменение Vagrantfile виртуальной среды #" + str(box_id)) return BoxEngine.get_vagrantfile_data(box_id) except Exception as ex: return HTTPServerError(ex.message)
def get(self): """Returns history data.""" entries = None data = [] if has_permission('manage'): entries = model.History.get_all_records() for entry in entries: box = [] box.append(entry.history_id) box.append(entry.user.display_name) if entry.box: box.append(entry.box.box_id) else: box.append(' - ') box.append(entry.datetime.strftime("%Y-%m-%d %H:%M")) box.append(entry.info) data.append(box) else: entries = model.History.get_all_user_records( request.identity['user']._id) for entry in entries: box = [] box.append(entry.history_id) if entry.box: box.append(entry.box.box_id) else: box.append(' - ') box.append(entry.datetime.strftime("%Y-%m-%d %H:%M")) box.append(entry.info) data.append(box) json_entries = {} json_entries['data'] = data return json.dumps(json_entries)
try: sender = SendMail() sender.send_mail(email, subject, body) DBSession.add(u) DBSession.flush() flash(email + ' added and notified via email.') except Exception, e: flash(('Could not send new login to ' + name + ", " + email + ": " + str(e)), 'error') redirect('/admin_panel') #Assign licenses error @expose('licensing_portal.templates.admin_panel') @require(predicates.has_permission('manage')) @validate(form=AssignLicensesForm) def assign_licences_error(self, **kwargs): return self.get_admin_panel_data(**kwargs) #Assign licenses @expose('licensing_portal.templates.admin_panel') @require(predicates.has_permission('manage')) @validate(form=AssignLicensesForm, error_handler=create_user_error) def assign_licences(self, **kwargs): user_id = kwargs['user_Id'] licenses = kwargs['licenses'] license_type = kwargs['license_type'] count = kwargs['count']
class RootController(BaseController): secc = SecureController() admin = AdminController(model, DBSession, config_type=TGAdminConfig) error = ErrorController() def _before(self, *args, **kw): tmpl_context.project_name = "licensing_portal" #Redirect to login page @expose() def index(self): #If no logged into go to login, else redirect('login/') #Instructions page @expose('licensing_portal.templates.instructions') @require(predicates.not_anonymous(msg='Must be logged in.')) def instructions(self): return dict(page='instructions') #Downloads page @expose('licensing_portal.templates.downloads') @require(predicates.not_anonymous(msg='Must be logged in.')) def downloads(self): return dict(page='downloads') #Serve file for download @expose() @require(predicates.not_anonymous(msg='Must be logged in.')) def serve_file(self, file_path=None, file_name=None): import paste.fileapp f = paste.fileapp.FileApp('/home/authorityfx/plugin_downloads/' + file_path + file_name, **{'Content-Disposition': 'attachment; filename=' + file_name}) from tg import use_wsgi_app return use_wsgi_app(f) #Settings page @expose('licensing_portal.templates.settings') @require(predicates.not_anonymous(msg='Must be logged in.')) def settings(self, **kwargs): return dict(page='settings', form=SettingsForm, data=kwargs) @expose('licensing_portal.templates.settings') @require(predicates.not_anonymous(msg='Must be logged in.')) @validate(form=SettingsForm) def update_settings_error(self, **kwargs): return dict(page='settings', form=SettingsForm, data=kwargs) #Update user credentials @expose('licensing_portal.templates.settings') @require(predicates.not_anonymous(msg='Must be logged in.')) @validate(form=SettingsForm, error_handler=update_settings_error) def update_settings(self, **kwargs): fail = False changed = False update_password = False update_email = False msg = '' #Get user user_name = request.identity['repoze.who.userid'] user = DBSession.query(model.User).filter(model.User.user_name==user_name).first() #Check if current password matches if user.validate_password(kwargs['current_password']) == False: fail = True msg = msg + " Wrong password!" #Update name if fail != True and 'name' in kwargs: if len(kwargs['name']) > 0: #Hash new password user.display_name = kwargs['name'] msg = msg + " Successfully changed name." changed = True #Update email if fail != True and 'login_email' in kwargs: if len(kwargs['login_email']) > 0: new_email = kwargs['login_email'].lower() count = DBSession.query(model.User).filter(model.User.user_name==new_email).count() if count == 0: user.user_name = new_email msg = msg + ' Successfully changed login email.' changed = True else: fail = True msg = msg + ' Email address already assigned.' #Update passwood if fail != True and 'new_password' in kwargs: if len(kwargs['new_password']) > 0: #Hash new password user._set_password(kwargs['new_password']) msg = msg + " Successfully changed password." changed = True #if no errors write to database if fail != True and changed == True: DBSession.flush() flash(msg.strip()) redirect('/logout_handler') elif fail != True and changed == False: flash('No Updates', 'warning') return dict(page='settings', form=SettingsForm, data=kwargs) else: flash(msg.strip(), 'error') return dict(page='settings', form=SettingsForm, data=kwargs) #Admin controllers #_________________________________________ def get_admin_panel_data(self, **kwargs): user_id_query = DBSession.query(model.User.user_id) if 'email_filter' in kwargs: if kwargs['email_filter'] != '': user_id_query = user_id_query.filter(model.User.user_name==kwargs['email_filter']) else: kwargs['email_filter'] = '' if 'id_filter' in kwargs: if kwargs['id_filter'] != '': user_id_query = user_id_query.filter(model.User.user_id==kwargs['id_filter']) else: kwargs['id_filter'] = '' if user_id_query.first(): user_id = user_id_query.first().user_id else: user_id = 1 admin_license_data = DBSession.query(model.User, model.License, model.Plugin, model.LicenseType).join(model.License).join(model.Plugin).join(model.LicenseType).filter(model.User.user_id==user_id) admin_computer_data = DBSession.query(model.User, model.Computer).join(model.Computer).filter(model.User.user_id==user_id) return dict(page='admin_panel', admin_computer_data=admin_computer_data[:10], admin_license_data=admin_license_data, admin_license_grid=admin_license_grid, admin_computer_grid=admin_computer_grid, assign_licences_form=AssignLicensesForm, create_user_form=CreateUserForm, data=kwargs) #Admin panel @expose('licensing_portal.templates.admin_panel') @require(predicates.has_permission('manage')) def admin_panel(self, **kwargs): return self.get_admin_panel_data(**kwargs) #Create user error @expose('licensing_portal.templates.admin_panel') @require(predicates.has_permission('manage')) @validate(form=CreateUserForm) def create_user_error(self, **kwargs): return self.get_admin_panel_data(**kwargs) #Create user @expose('licensing_portal.templates.admin_panel') @require(predicates.has_permission('manage')) @validate(form=CreateUserForm, error_handler=create_user_error) def create_user(self, **kwargs): name = kwargs['name'] email = kwargs['login_email'].lower() if DBSession.query(model.User).filter(model.User.user_name==email).count() > 0: flash(email + ' already exists!', 'error') kwargs['login_email']='' return self.admin_panel(**kwargs) #redirect('/admin_panel', kwargs) password = ''.join(random.choice(string.letters + string.digits + string.punctuation) for x in xrange(8)) u = model.User() u.user_name = email u.display_name = name u.password = password licensing_portal_url = "licensing.authorityfx.com" subject = "New Authority FX Licensing Portal Account" body = "Dear " + name + ",\n" \ + "\n" \ + "Please login into your new Authority FX licensing portal account with the following credentials: \n" \ + "\n" \ + licensing_portal_url + "\n" \ + "\n" \ + "username: "******"\n" \ + "password: "******"\n" \ + "\n" \ + "We suggest that you change you password upon first login.\n" \ + "\n" \ + "Remember that all purchases are added into our licensing portal under the email address provided at checkout. "\ + "If you want to make puchases using another email address, please ensure that you change your login email via the " \ + "settings page prior to making any new purchases.\n" \ + "\n" \ + "Thanks!" try: sender = SendMail() sender.send_mail(email, subject, body) DBSession.add(u) DBSession.flush() flash(email + ' added and notified via email.') except Exception, e: flash(('Could not send new login to ' + name + ", " + email + ": " + str(e)), 'error') redirect('/admin_panel')
class RootController(TGController): allow_only = predicates.has_permission('tgappcategories') @expose('tgappcategories.templates.index') def index(self): categories = model.provider.query(model.Category, order_by='path') return dict( categories_count=categories[0], categories=categories[1], mount_point=self.mount_point, ) @expose('tgappcategories.templates.new_category') def new_category(self, **_): return dict( form=get_new_category_form(), mount_point=self.mount_point, action=plug_url('tgappcategories', '/create_category'), values=None, ) @expose() @validate(get_new_category_form(), error_handler=new_category) def create_category(self, **kwargs): parent = model.provider.get_obj(model.Category, {'_id': kwargs.get('pare\ nt_id')}) image_small = { 'content': kwargs.get('image_small'), 'image_name': 'image_small', } img_small = model.provider.create(model.CategoryImage, image_small) image_big = { 'content': kwargs.get('image_big'), 'image_name': 'image_big', } img_big = model.provider.create(model.CategoryImage, image_big) category = { 'name': kwargs.get('name'), 'description': kwargs.get('description'), 'images': [img_small, img_big], 'path': parent.path + '~' + str(parent._id) if parent else '', 'depth': parent.depth + 1 if parent else 1, } model.provider.create(model.Category, category) flash(_('Category created.')) return redirect(url(self.mount_point)) @expose('tgappcategories.templates.edit_category') def edit_category(self, category_id, **_): category = model.provider.get_obj(model.Category, {'_id': category_id}) or abort(404) category.image_small_id = category.images[0]._id category.image_big_id = category.images[1]._id category.parent_id = category.path.split('~')[-1] return dict( form=get_edit_category_form(), mount_point=self.mount_point, action=plug_url('tgappcategories', '/update_category/' + category_id), values=category, ) @expose() @validate(get_edit_category_form(), error_handler=edit_category) def update_category(self, category_id, **kwargs): category = model.provider.get_obj(model.Category, {'_id': category_id}) category.name = kwargs.get('name') category.description = kwargs.get('description') img_small = img_big = None if kwargs.get('image_small') is not None: image_small = { 'content': kwargs.get('image_small'), 'image_name': 'image_small', } img_small = model.provider.create(model.CategoryImage, image_small) if kwargs.get('image_big') is not None: image_big = { 'content': kwargs.get('image_big'), 'image_name': 'image_big', } img_big = model.provider.create(model.CategoryImage, image_big) category_parent_id = category.path.split('~')[-1] if kwargs.get('parent_id') != category_parent_id: old_path = category.path old_depth = category.depth new_parent = model.provider.get_obj( model.Category, {'_id': kwargs.get('parent_id')}) new_path = (new_parent.path if new_parent else '') \ + ('~' + str(new_parent._id) if new_parent else '') if new_parent and new_parent._id == category._id: abort(412, _('Cannot move category into itself')) new_depth = new_parent.depth + 1 if new_parent else 1 for d in category.descendants: if new_path == d.path + '~' + str(d._id): abort(412, _('Cannot move category to a descendant category')) # calculating descendant depth d.depth += (new_depth - old_depth) # calculate descendant path if old_path != '': d.path = d.path.replace(old_path, new_path) else: d.path = new_path + d.path category.path = new_path category.depth = new_depth original_small = model.provider.get_obj( model.CategoryImage, {'_id': kwargs.get('image_small_id')}) original_big = model.provider.get_obj( model.CategoryImage, {'_id': kwargs.get('image_big_id')}) category.images = [ img_small or original_small, img_big or original_big ] tg.hooks.notify('categories.after_update', args=(category, kwargs)) flash(_('Category updated.')) return redirect(url(self.mount_point)) @expose() def delete_category(self, category_id): category = model.provider.get_obj(model.Category, dict( _id=category_id)) or redirect(url(self.mount_point)) if len(category.descendants) == 0: model.provider.delete(model.Category, dict(_id=category_id)) flash(_('Category deleted')) return redirect(url(self.mount_point)) else: abort(412, _('Cannot delete category because it has descendants'))
from tg.predicates import has_permission, Any host_ro = Any(has_permission('HostRO'), has_permission('HostRW'), msg='User must have Host View permissions') host_rw = has_permission('HostRW', msg='User must have Host Admin permissions')
def test_user_doesnt_have_permission(self): environ = make_environ('gustavo', permissions=['watch-tv']) p = predicates.has_permission('eat') self.eval_unmet_predicate(p, environ, 'The user must have the "eat" permission')
class SurveyController(BaseController): def __init__(self, survey): self.survey = survey @expose('mozzarella.templates.survey_results') @expose("json") @require(has_permission('admin')) def results(self, number=None, order_by=None, reverse=False): """Return results of surveys :param number: (optional) does nothing. Defaults to ``None``. :param order_by: (optional) which field to sort survey results by. Defaults to ``None``. :param reverse: (optional) whether or not the returned results should be ascending. Defaults to ``False``. :return: Results of surveys, modified by parameters :rtype: Dictionary """ if type(reverse) is str: reverse = reverse == 'True' if order_by: # TODO (#46): this doesn't work... If the column is nullable, then # the sort can't deal with comparing None types # order = '{} {}'.format(order_by, 'asc' if reverse else 'desc') # responses = self.survey.responses.order_by(order) responses = self.survey.responses else: responses = self.survey.responses # TODO (#46): This sucks. It would be good to have this done for us with # SQLAlchemy magic responses = [self._response_dict(r) for r in responses or []] survey_title = (self.survey.title or (self.survey.meeting and self.survey.meeting.title) or 'Survey') return { 'survey_id': self.survey.id, 'title': survey_title, 'count': len(responses), 'responses': responses, 'fields': self.survey.field_metadata(), 'order_by': order_by, 'reverse': reverse, } def _response_dict(self, response): """Creates a dictionary based on a single survey response :param response: which specific survey response is desired. This function is called for each response in a survey. :return: a single survey response :rtype: Dictionary """ out = {'name': response.name, 'email': response.email} # Add the actual response data for the fields that exist. out.update({ item.field.name: item.field.type_object().from_contents(item.contents) for item in response.data }) return out @expose('mozzarella.templates.survey') def respond(self): """Create an attendance survey form :return: ``None`` or the survey passed into __init__ :rtype: None or Dictionary """ if not self.survey: abort(404, 'No survey for meeting') if not self.survey.active: if not has_permission('admin'): abort(403, 'Survey not avalible') return flash( 'This page is currently disabled. You can see it because you are an admin.', 'warn') form = request.POST if form: user = request.identity and request.identity.get('user') response = SurveyResponse(user=user, provided_name=form.get('_provided_name'), survey=self.survey) DBSession.add(response) requires_ft = bool(form.get('first_time')) for f in self.survey.fields: if f.first_time and not requires_ft: continue fo = f.type_object() v = fo.from_post(form) if v: DBSession.add( SurveyData(response=response, field=f, contents=v)) flash('Response submitted successfully') redirect(base_url='/') else: return {'survey': self.survey}
def test_user_has_permission(self): environ = make_environ('gustavo', permissions=['watch-tv']) p = predicates.has_permission('watch-tv') self.eval_met_predicate(p, environ)