def send_page(page, request): """Sends a given page to a user if they have access rights. Args: page: The page to send to the user request: The Django request object Returns: A Django HttpResponse containing the requested page, or an error message. """ profile = request.profile global_access = page.acl.global_read if not global_access: if profile is None: return http.HttpResponseRedirect(users.create_login_url(request.path)) if not page.user_can_read(profile): logging.warning("User %s made an invalid attempt to access page %s" % (profile.email, page.name)) return utility.forbidden(request) files = page.attached_files() files = [file_obj for file_obj in files if not file_obj.is_hidden] for item in files: ext = item.name.split(".")[-1] item.icon = "/static/images/fileicons/%s.png" % ext is_editor = page.user_can_write(profile) if configuration.SYSTEM_THEME_NAME: template = "themes/%s/page.html" % (configuration.SYSTEM_THEME_NAME) return utility.respond(request, template, {"page": page, "files": files, "is_editor": is_editor})
def delete_page(request, page_id): """Removes a page from the database. The page with name page_name is completely removed from the db, and all files attached to that page are removed. Args: request: The request object page_id: Key id of the page to delete Returns: A http redirect to the admin index page. """ page = models.Page.get_by_id(int(page_id)) if not page: return utility.page_not_found(request) if not page.user_can_write(request.profile): return utility.forbidden(request) page.delete() url = urlresolvers.reverse('views.admin.index') return http.HttpResponseRedirect(url)
def new_page(request, parent_id): """Create a new page. Args: request: The request object parent_id: Page that will be the parent of the new page Returns: A Django HttpResponse object. """ if parent_id: parent_page = models.Page.get_by_id(int(parent_id)) else: parent_page = models.Page.get_root() if parent_page: # there is a root, lets force everything to be a child of the root # and set the parent_id parent_id = parent_page.key().id() else: # TODO(gpennington): Figure out a more intuitive method for site # initialization parent_page = utility.set_up_data_store() return utility.edit_updated_page(parent_page.key().id()) if not parent_page.user_can_write(request.profile): return utility.forbidden(request) return edit_page(request, None, parent_id=parent_id)
def edit_page(request, page_id, parent_id=None): """Generates and processes the form to create or edit a specified page. Args: request: The request object page_id: ID of the page. parent_id: ID of the parent page Returns: A Django HttpResponse object. """ page = None files = None if page_id: page = models.Page.get_by_id(int(page_id)) if not page: return utility.page_not_found( request, 'No page exists with id %r.' % page_id) if not page.user_can_write(request.profile): return utility.forbidden(request) files = list( models.FileStore.all().filter('parent_page =', page).order('name')) for item in files: ext = item.name.lower().split('.')[-1] item.icon = '/static/images/fileicons/%s.png' % ext acl_data = None if page: all_group_keys = [ g.key() for g in models.UserGroup.all().order('name')] groups_without_write_keys = [ k for k in all_group_keys if k not in page.acl.group_write] groups_without_read_keys = [ k for k in all_group_keys if k not in page.acl.group_read] acl_data = { 'groups_without_write': models.UserGroup.get(groups_without_write_keys), 'groups_without_read': models.UserGroup.get(groups_without_read_keys), 'group_write': models.UserGroup.get(page.acl.group_write), 'group_read': models.UserGroup.get(page.acl.group_read), 'user_write': models.UserProfile.get(page.acl.user_write), 'user_read': models.UserProfile.get(page.acl.user_read), 'inherits_acl': page.inherits_acl(), } if not request.POST: form = forms.PageEditForm(data=None, instance=page) return utility.respond(request, 'admin/edit_page', {'form': form, 'page': page, 'files': files, 'acl_data': acl_data, 'parent_id': parent_id}) form = forms.PageEditForm(data=request.POST, instance=page) if not form.errors: try: page = form.save(commit=False) except ValueError, err: form.errors['__all__'] = unicode(err)
def __wrapper(request, *args, **kwds): """Makes it possible for super_user_required to be used as a decorator.""" if request.profile.is_superuser: return func(request, *args, **kwds) # pylint: disable-msg=W0142 else: return utility.forbidden( request, error_message='You must be a superuser to view this page.')
def __wrapper(request, *args, **kwds): """Makes it possible for admin_required to be used as a decorator.""" if request.user_is_admin: return func(request, *args, **kwds) # pylint: disable-msg=W0142 else: return utility.forbidden( request, error_message='You must be an administrator to view this page.')
def edit_page(request, page_id, parent_id=None): """Generates and processes the form to create or edit a specified page. Args: request: The request object page_id: ID of the page. parent_id: ID of the parent page Returns: A Django HttpResponse object. """ page = None files = None if page_id: page = models.Page.get_by_id(int(page_id)) if not page: return utility.page_not_found(request, "No page exists with id %r." % page_id) if not page.user_can_write(request.profile): return utility.forbidden(request) files = list(models.FileStore.all().filter("parent_page =", page).order("name")) for item in files: item.icon = "/static/images/fileicons/%s.png" % item.name.split(".")[-1] acl_data = None if page: all_group_keys = [g.key() for g in models.UserGroup.all().order("name")] groups_without_write_keys = [k for k in all_group_keys if k not in page.acl.group_write] groups_without_read_keys = [k for k in all_group_keys if k not in page.acl.group_read] acl_data = { "groups_without_write": models.UserGroup.get(groups_without_write_keys), "groups_without_read": models.UserGroup.get(groups_without_read_keys), "group_write": models.UserGroup.get(page.acl.group_write), "group_read": models.UserGroup.get(page.acl.group_read), "user_write": models.UserProfile.get(page.acl.user_write), "user_read": models.UserProfile.get(page.acl.user_read), "inherits_acl": page.inherits_acl(), } if not request.POST: form = forms.PageEditForm(data=None, instance=page) return utility.respond( request, "admin/edit_page", {"form": form, "page": page, "files": files, "acl_data": acl_data} ) form = forms.PageEditForm(data=request.POST, instance=page) if not form.errors: try: page = form.save(commit=False) except ValueError, err: form.errors["__all__"] = unicode(err)
def send_page(page, request): """Sends a given page to a user if they have access rights. Args: page: The page to send to the user request: The Django request object Returns: A Django HttpResponse containing the requested page, or an error message. """ profile = request.profile global_access = page.acl.global_read if not global_access: if profile is None: return http.HttpResponseRedirect(users.create_login_url(request.path)) if not page.user_can_read(profile): logging.warning('User %s made an invalid attempt to access page %s' % (profile.email, page.name)) return utility.forbidden(request) files = page.attached_files() files = [file_obj for file_obj in files if not file_obj.is_hidden] for item in files: ext = item.name.split('.')[-1] item.icon = '/static/images/fileicons/%s.png' % ext is_editor = page.user_can_write(profile) if page.template: page_template = template.Template(page.template.source) params = utility.set_params(request, {'page': page, 'files': files, 'is_editor': is_editor}) context = template.Context(params) return http.HttpResponse(page_template.render(context)) #mytemplate = Template(page.template.source) #return http.HttpResponse(mytemplate.render(name="jack")) else: base_html = '../templates/themes/%s/base.html' % (configuration.SYSTEM_THEME_NAME) page_html = '../templates/themes/%s/page.html' % (configuration.SYSTEM_THEME_NAME) return utility.respond(request, page_html, {'page': page, 'files': files, 'is_editor': is_editor, 'base_html': base_html})
def filebrowser(request, page_id): """File Browser for CKEditor. The File Browser simplifies including images on the page by select file from list by one-click. Args: request: The request object page_id: ID of the page that attached files are listing Returns: A Django HttpResponse object. """ if page_id: page = models.Page.get_by_id(int(page_id)) if not page: return utility.page_not_found(request) if not page.user_can_write(request.profile): return utility.forbidden(request) files = page.attached_files() if request.GET.get('Type') == 'Image': files = [item for item in files if item.name.lower().split('.')[-1] in ('jpg', 'gif', 'jpeg', 'png', 'bmp', 'webp')] if request.GET.get('Type') == 'Flash': files = [item for item in files if item.name.lower().split('.')[-1] in ('swf', 'flv')] for item in files: ext = item.name.lower().split('.')[-1] item.icon = '/static/images/fileicons/%s.png' % ext return utility.respond(request, 'admin/filebrowser', {'files': files, 'funcNum': request.GET.get('CKEditorFuncNum')}) else: return utility.page_not_found(request)
def upload_file(request): """Reads a file from POST data and stores it in the db. Args: request: The request object Returns: A http redirect to the edit form for the parent page """ if not request.POST or not 'page_id' in request.POST: return utility.page_not_found(request) page_id = request.POST['page_id'] page = models.Page.get_by_id(int(page_id)) if not page: logging.warning('admin.upload_file was passed an invalid page id %r', page_id) return utility.page_not_found(request) if not page.user_can_write(request.profile): return utility.forbidden(request) file_data = None file_name = None url = None if request.FILES and 'attachment' in request.FILES: file_name = request.FILES['attachment'].name file_data = request.FILES['attachment'].read() elif 'url' in request.POST: url = request.POST['url'] file_name = url.split('/')[-1] else: return utility.page_not_found(request) if not url and not file_name: url = 'invalid URL' if url: validate = validators.URLValidator() try: validate(url) except exceptions.ValidationError, excption: return utility.page_not_found(request, excption.messages[0])
def upload_file(request): """Reads a file from POST data and stores it in the db. Args: request: The request object Returns: A http redirect to the edit form for the parent page """ if not request.POST or not "page_id" in request.POST: return utility.page_not_found(request) page_id = request.POST["page_id"] page = models.Page.get_by_id(int(page_id)) if not page: logging.warning("admin.upload_file was passed an invalid page id %r", page_id) return utility.page_not_found(request) if not page.user_can_write(request.profile): return utility.forbidden(request) file_data = None file_name = None url = None if request.FILES and "attachment" in request.FILES: file_name = request.FILES["attachment"]["filename"] file_data = request.FILES["attachment"]["content"] elif "url" in request.POST: url = request.POST["url"] file_name = url.split("/")[-1] else: return utility.page_not_found(request) if not url and not file_name: url = "invalid URL" if url: try: validators.isValidURL(url, None) except validators.ValidationError, excption: return utility.page_not_found(request, excption.messages[0])
def delete_file(request, page_id, file_id): """Removes a specified file from the database. Args: request: The request object page_id: ID of the page the file is attached to. file_id: Id of the file. Returns: A Django HttpResponse object. """ record = models.FileStore.get_by_id(int(file_id)) if record: if not record.user_can_write(request.profile): return utility.forbidden(request) record.delete() return utility.edit_updated_page(page_id, tab_name='files') else: return utility.page_not_found(request)
def send_page(page, request): """Sends a given page to a user if they have access rights. Args: page: The page to send to the user request: The Django request object Returns: A Django HttpResponse containing the requested page, or an error message. """ profile = request.profile global_access = page.acl.global_read if not global_access: if profile is None: return http.HttpResponseRedirect( users.create_login_url(request.path)) if not page.user_can_read(profile): logging.warning( 'User %s made an invalid attempt to access page %s' % (profile.email, page.name)) return utility.forbidden(request) files = page.attached_files() files = [file_obj for file_obj in files if not file_obj.is_hidden] for item in files: ext = item.name.lower().split('.')[-1] item.icon = '/static/images/fileicons/%s.png' % ext is_editor = page.user_can_write(profile) if configuration.SYSTEM_THEME_NAME: template = 'themes/%s/page.html' % (configuration.SYSTEM_THEME_NAME) return utility.respond(request, template, { 'page': page, 'files': files, 'is_editor': is_editor })
def send_file(file_record, request): """Sends a given file to a user if they have access rights. Args: file_record: The file to send to the user request: The Django request object Returns: A Django HttpResponse containing the requested file, or an error message. """ profile = request.profile mimetype = mimetypes.guess_type(file_record.name)[0] if not file_record.user_can_read(profile): logging.warning("User %s made an invalid attempt to access file %s" % (profile.email, file_record.name)) return utility.forbidden(request) expires = datetime.datetime.now() + configuration.FILE_CACHE_TIME response = http.HttpResponse(content=file_record.data, mimetype=mimetype) response["Cache-Control"] = configuration.FILE_CACHE_CONTROL response["Expires"] = expires.strftime("%a, %d %b %Y %H:%M:%S GMT") return response
def send_file(file_record, request): """Sends a given file to a user if they have access rights. Args: file_record: The file to send to the user request: The Django request object Returns: A Django HttpResponse containing the requested file, or an error message. """ profile = request.profile mimetype = mimetypes.guess_type(file_record.name)[0] if not file_record.user_can_read(profile): logging.warning('User %s made an invalid attempt to access file %s' % (profile.email, file_record.name)) return utility.forbidden(request) expires = datetime.datetime.now() + configuration.FILE_CACHE_TIME response = http.HttpResponse(content=file_record.data, mimetype=mimetype) response['Cache-Control'] = configuration.FILE_CACHE_CONTROL response['Expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S GMT') return response
def edit_acl(request): """Edits the contents of an ACL.""" def grant_access(acl, list_to_edit): """Grants access to a page based on data in the POST. Args: acl: AccessControlList to be manipulated list_to_edit: string representing the list on the ACL to add users or groups to """ if request.POST[list_to_edit]: datastore_object = None if request.POST[list_to_edit].startswith('user'): datastore_object = models.UserProfile.load(request.POST[list_to_edit]) else: datastore_object = models.UserGroup.get_by_id( int(request.POST[list_to_edit])) if datastore_object.key() not in acl.__getattribute__(list_to_edit): acl.__getattribute__(list_to_edit).append(datastore_object.key()) def remove_access(acl, list_to_edit): """Removes access to a page based on data in the POST. Args: acl: AccessControlList to be manipulated list_to_edit: string representing the list on the ACL to remove users or groups from """ post_key = '%s_remove_' % list_to_edit removal_keys = [k for k in request.POST.keys() if k.startswith(post_key)] for key in removal_keys: model_type = models.UserGroup if list_to_edit.startswith('user'): model_type = models.UserProfile key_id = int(key.replace(post_key, '')) datastore_object = model_type.get_by_id(key_id) acl.__getattribute__(list_to_edit).remove(datastore_object.key()) page_id = request.POST['page_id'] page = models.Page.get_by_id(int(page_id)) if not page: return utility.page_not_found(request) if not page.user_can_write(request.profile): return utility.forbidden(request) acl = page.acl if page.inherits_acl(): acl = acl.clone() acl.put() page.acl = acl page.put() acl.global_write = 'global_write' in request.POST acl.global_read = 'global_read' in request.POST for object_list in ['group_write', 'group_read', 'user_write', 'user_read']: grant_access(acl, object_list) remove_access(acl, object_list) acl.put() return utility.edit_updated_page(page_id, tab_name='security', message_id='msgChangesSaved')