Ejemplo n.º 1
0
class IndexController(BaseController):
    @authorize(ValidAuthKitUser())
    def index(self):
        # Return a rendered template
        #return render('/index.mako')
        # or, return a response
        return render('/pypesvds.mako')

    def signout(self):
        return render('/signin.html')
Ejemplo n.º 2
0
class AccountController(BaseController):
    def signin(self):
        if not h.auth.authorized(h.auth.is_valid_user):
            print("chua dang nhap")
            if request.params:
                print("vao day khong nhi ")
                user = Session.query(model.Users). \
                    filter_by(email=request.params['email'],
                              password=request.params['password']). \
                    first()
                if user:
                    print("dang nhap roi")
                    session['user'] = user
                    session.save()
                    print(user)
                else:
                    return render_jinja2('/account/singin.html')
            else:
                print("vao 1")
                return render_jinja2('/account/singin.html')
        else:
            print("vao 2")
            return redirect(h.url('signedin'))

    @authorize(ValidAuthKitUser())
    def signout(self):
        # The actual removal of the AuthKit cookie occurs when the response passes
        # through the AuthKit middleware, we simply need to display a page
        # confirming the user is signed out
        del session['user']
        session.delete()
        return render_jinja2('/account/singout.html')

    @authorize(ValidAuthKitUser())
    def signedin(self):
        # The actual removal of the AuthKit cookie occurs when the response passes
        # through the AuthKit middleware, we simply need to display a page
        # confirming the user is signed out
        # print(1)
        # print(authorize(h.auth.has_auth_kit_role('admin')))
        #print (student_group_id)
        redirect(url(controller='students', action='show'))
Ejemplo n.º 3
0
class SampleApp:

    # Application setup
    def __call__(self, environ, start_response):
        path = environ.get('PATH_INFO')
        if path == '/user':
            return self.user(environ, start_response)
        elif path == '/admin':
            return self.admin(environ, start_response)
        elif path == '/group':
            return self.group(environ, start_response)
        elif path == '/':
            return self.index(environ, start_response)
        else:
            start_response("404 Not Found", [("Content-type", "text/plain")])
            return ["Not Found"]

    def _access_granted(self, start_response, message):
        start_response("200 OK", [("Content-type", "text/html")])
        return [
            "<html><head><title>AuthKit Database Example</title></head>",
            "<body><h1>AuthKit Database Example</h1>", message,
            "</body></html>"
        ]

    # Induvidual pages
    def index(self, environ, start_response):
        return self._access_granted(
            start_response, """
            <p>This page is public, try visiting the following pages:</p>
            <ul>
            <li><a href="/user">Any signed in user can access this page</a></li>
            <li><a href="/admin">Only signed in users with the <tt>admin</tt> role have access [ben]</a></li>
            <li><a href="/group">Only signed in users in the <tt>pylons</tt> group have access [james]</a></li>
            </ul>
            """)

    @authorize(
        ValidAuthKitUser()
    )  # Note we don't use RemoteUser() here because we only want users in the AuthKit database
    def user(self, environ, start_response):
        return self._access_granted(
            start_response, "Any user in the database can access this")

    @authorize(HasAuthKitRole(["admin"]))
    def admin(self, environ, start_response):
        return self._access_granted(start_response,
                                    "You have the <tt>admin</tt> role.")

    @authorize(HasAuthKitGroup(["pylons"]))
    def group(self, environ, start_response):
        return self._access_granted(start_response,
                                    "You are in the <tt>pylons</tt> group.")
Ejemplo n.º 4
0
from authkit.permissions import ValidAuthKitUser
from authkit.permissions import HasAuthKitRole
from authkit.authorize.pylons_adaptors import authorized
from pylons.templating import render_mako as render
from authkit.authorize.pylons_adaptors import authorize

is_valid_user = ValidAuthKitUser()
has_delete_role = HasAuthKitRole(['delete'])

def render_signin():
    return render('/derived/account/signin.html').encode('utf-8')
Ejemplo n.º 5
0
class EventController(BaseController):
    @authorize(ValidAuthKitUser())
    def new(self):
        fs = EventForm('event-new')

        if request.POST and fs.fields.cancel.id in request.POST:
            return redirect_to(current_user().url())

        if request.POST and fs.is_valid(request.POST):
            node = model.Event()
            node.title = fs.fields.title.value
            node.summary = fs.fields.summary.value
            node.start = fs.fields.start.value
            node.finish = fs.fields.finish.value
            node.node_user_id = current_user().id

            meta.Session.add(node)
            meta.Session.commit()
            flash(u'Событие успешно добавлено')
            return redirect_to(node.url())

        c.form = fs
        c.fs = fs.fields

        if is_ajax():
            result = render('/event/new_partial.html')
        else:
            result = render('/event/new.html')
        if request.POST:
            result = fs.htmlfill(result)
        return result

    def edit(self, id):
        node = self._get_row(model.Event, id)
        self._check_access(node)

        fs = EventForm('event-edit')

        if request.POST and fs.fields.cancel.id in request.POST:
            return redirect_to(node.url())

        if request.POST and fs.is_valid(request.POST):
            node.title = fs.fields.title.value
            node.summary = fs.fields.summary.value
            node.start = fs.fields.start.value
            node.finish = fs.fields.finish.value

            meta.Session.commit()
            flash(u'Информация о событии успешно сохранена')
            if self.back_page():
                return redirect_to(**self.back_page())
            return redirect_to(node.url())

        if not request.POST:
            fs.set_values({
                'title': node.title,
                'start': node.start.strftime(DATE_FORMAT),
                'finish': node.finish.strftime(DATE_FORMAT),
                'summary': node.summary
            })

        c.node = node
        c.form = fs
        c.fs = fs.fields

        if is_ajax():
            result = render('/event/edit_partial.html')
        else:
            result = render('/event/edit.html')
        return fs.htmlfill(result)

    def show(self, id):
        self.is_page_back = True

        c.node = self._get_row(model.Event, id)

        if is_ajax():
            result = self.taconite(render('/event/show_partial.html'))
        else:
            result = render('/event/show.html')
        return result

    def list(self, user=None):
        self.is_page_back = True
        query = meta.Session.query(model.Event)
        if user is None:
            query = query.select_from(
                join(model.Event, model.User,
                     model.Event.node_user_id == model.User.id)).filter(
                         and_(model.Event.published != None,
                              model.User.nickname != 'demo'))
        else:
            user_query = meta.Session.query(model.User)
            try:
                user_node = user_query.filter(
                    model.User.nickname == user).one()
            except NoResultFound:
                abort(404)

            query = query.filter(model.Event.node_user_id == user_node.id)

            if user_node.nickname != current_user().nickname:
                query = query.filter(model.Event.published != None)

        query = query.order_by(model.Event.start.desc())

        c.user = user
        c.nodes = pager_or_404(query)
        if is_ajax():
            result = self.taconite(render('/event/list_partial.html'))
        else:
            result = render('/event/list.html')
        return result

    def remove(self, id):
        node = self._get_row(model.Event, id)
        if 1 == node.id:
            abort(403)
        self._check_access(node)

        fs = form.DeleteAcceptForm('event-remove')

        if request.POST:
            if fs.fields.save.id in request.POST:
                meta.Session.delete(node)
                meta.Session.commit()
                flash(u'Событие успешно удалено')
                c.is_full_redirect = True
                return self._redirect_to(controller='event',
                                         action='list',
                                         user=current_user().nickname)
            return redirect_to(node.url())
        else:
            c.form = fs
            if is_ajax():
                result = render('/util/delete_accept_partial.html')
            else:
                result = render('/util/delete_accept.html')
            return result

    def publish(self, id, published):
        node = self._get_row(model.Event, id)
        self._check_access(node)

        if published == '1':
            node.published = datetime.now()
            message = u'Событие успешно опубликовано'
        else:
            node.published = None
            message = u'Событие успешно сохранено как черновик'

        meta.Session.commit()
        flash(message)
        return redirect_to(node.url())
Ejemplo n.º 6
0
def is_authorized():
    return authorized(ValidAuthKitUser())
Ejemplo n.º 7
0
                    c.form_result = {
                        'email': request.params['email'],
                        'password': request.params['password']
                    }
                    c.form_errors = {
                        'email':
                        'Email va Password khong khop voi bat ki tai khoan nao'
                    }
                    if c.form_errors:
                        h.flash('Dang nhap that bai', 'error')
                    return render('/derived/account/signin.html')
        else:
            h.flash('Ban da dang nhap', 'success')
            return redirect(h.url(controller='account', action='signedin'))

    @authorize(ValidAuthKitUser())
    def signout(self):
        # The actual removal of the AuthKit cookie occurs when the response passes
        # through the AuthKit middleware, we simply need to display a page
        # confirming the user is signed out
        del session['user']
        return render('/derived/account/signedout.html')

    @authorize(ValidAuthKitUser())
    def signedin(self):
        # The actual removal of the AuthKit cookie occurs when the response passes
        # through the AuthKit middleware, we simply need to display a page
        # confirming the user is signed out
        # print(1)
        # print(authorize(h.auth.has_auth_kit_role('admin')))
        return render('/derived/account/signedin.html')
Ejemplo n.º 8
0
class UtilController(BaseController):
    @authorize(ValidAuthKitUser())
    def login(self):
        c.message = u'Login success'
        return redirect_to('/')

    @authorize(ValidAuthKitUser())
    def logout(self):
        c.message = u'Logout success'
        return redirect_to('/')

    @authorize(ValidAuthKitUser())
    def demo(self):
        event = meta.Session.query(model.Event).filter(
            model.Event.id == 1
        ).one()
        redirect_to(event.url())

    @authorize(HasAuthKitRole('admin'))
    def demo_up(self):
        event = meta.Session.query(model.Event).filter(
            model.Event.id == 1
        ).one()

        user = meta.Session.query(model.User).filter(
            model.User.nickname == 'demo'
        ).one()

        for node in event.persons: meta.Session.delete(node)
        for node in event.reports: meta.Session.delete(node)
        for node in event.albums: meta.Session.delete(node)

        meta.Session.commit()

        dir = config['demo_dir']

        info_file = os.path.join(dir, 'info.yml')
        info = codecs.open(info_file, 'r', 'utf-8')
        info = yaml.load(info)

        event.title = info['title']
        if 'summary' in info:
            event.summary = info['summary']
        if 'start' in info:
            event.start = info['start']
        if 'finish' in info:
            event.finish = info['finish']
        event.node_user = user
        event.created = datetime.now()

        if 'albums' in info:
            for album in info['albums']:
                node = model.Album()
                node.settings = picasa.photos(album['user'], album['albumid'], 15)
                node.node_user = user
                node.event = event
                meta.Session.add(node)


        persons_dir = os.path.join(dir, u'persons')
        for file in os.listdir(persons_dir):
            path =  os.path.join(persons_dir, file)
            if os.path.isfile(path):
                node = model.Person()
                node.fullname = file.split('.')[0]
                node.avatar = avatar_prepare(open(path, 'r'))
                node.node_user = user
                node.event = event
                meta.Session.add(node)

        reports_dir = os.path.join(dir, u'reports')
        for file in os.listdir(reports_dir):
            path =  os.path.join(reports_dir, file)
            if os.path.isfile(path):
                text = codecs.open(path, 'r', 'utf-8').read()
                node = model.Report()
                node.title = file.split('.')[0]
                node.content = text
                node.node_user = user
                node.event = event
                meta.Session.add(node)

        meta.Session.commit()

        flash(u'Демонстрация обновлена')
        return redirect_to('demo')

    @restrict('POST')
    def markdown(self):
        text = request.POST['data']
        if text is None:
            abort(400)
        c.content = markdown(text)
        return render('/util/response.html')

    @restrict('POST')
    def rst(self):
        text = request.POST['data']
        if c.content is None:
            abort(400)
        text = rst2html(text)
        c.content = text
        return render('/util/response.html')

    def flash_file(self, id):
        if id in session['flash_file']:
            file =  session['flash_file'][id];
        else:
            abort(404)
        data = file['content']
        response.content_type = guess_type(file['filename'])[0] or 'text/plain'
        return data