コード例 #1
0
ファイル: nas.py プロジェクト: tazjel/nerva2py
def createDataBackup():
    if request.vars.alias == None:
        return P(str(T("Error: Missing alias parameter!")))
    if request.vars.bformat:
        bformat = str(request.vars.bformat)
    else:
        bformat = "backup"
    if ns.local.setEngine(request.vars.alias, True, False) == False:
        if request.vars.filename == "download":
            session.flash = str(ns.error_message)
            redirect(URL("create_backup"))
        else:
            return P("Error: " + str(ns.error_message))
    retbc = dbtool.createDataBackup(alias=request.vars.alias,
                                    bformat=bformat,
                                    filename=request.vars.filename,
                                    verNo=response.verNo)
    if request.vars.filename == "download":
        if (not str(retbc).startswith("<span")) and (
                not str(retbc).startswith("<div")):
            import time
            response.headers['Content-Type'] = 'application/octet-stream'
            response.headers[
                'Content-Disposition'] = 'attachment;filename="' + str(
                    request.vars.alias) + '_' + time.strftime(
                        "%Y%m%d_%H%M") + '.' + bformat + '"'
            return retbc
        else:
            session.flash = str(retbc)
            redirect(URL("create_backup"))
    return P(retbc)
コード例 #2
0
ファイル: nas.py プロジェクト: tazjel/nerva2py
def createDataBackup():
    if request.vars.alias == None:
        return P(str(T("Error: Missing alias parameter!")))
    if request.vars.bformat:
        bformat = str(request.vars.bformat)
    else:
        bformat = "backup"
    if ns.local.setEngine(request.vars.alias, True, False) == False:
        if request.vars.filename == "download":
            session.flash = str(ns.error_message)
            redirect(URL("create_backup"))
        else:
            return P("Error: " + str(ns.error_message))
    retbc = dbtool.createDataBackup(
        alias=request.vars.alias, bformat=bformat, filename=request.vars.filename, verNo=response.verNo
    )
    if request.vars.filename == "download":
        if (not str(retbc).startswith("<span")) and (not str(retbc).startswith("<div")):
            import time

            response.headers["Content-Type"] = "application/octet-stream"
            response.headers["Content-Disposition"] = (
                'attachment;filename="'
                + str(request.vars.alias)
                + "_"
                + time.strftime("%Y%m%d_%H%M")
                + "."
                + bformat
                + '"'
            )
            return retbc
        else:
            session.flash = str(retbc)
            redirect(URL("create_backup"))
    return P(retbc)
コード例 #3
0
ファイル: register.py プロジェクト: kultsinuppeli/happygoblin
def register():
    response.loginmenu = [(T("Login/Register"), URL("default", "user") == URL(), URL("default", "user"), [])]
    playermgmt.ensure_session_vars(auth, inreguser=True)
    # If the user has already registered, forward user to user the index page
    if current.session.playerid != None:
        http.redirect(html.URL("default", "index"))
    return dict()
コード例 #4
0
 def select(self,
            table,
            query=None,
            fields=None,
            orderby=None,
            limitby=None,
            headers={},
            **attr):
     request = self.environment.request
     if not (isinstance(table, self.db.Table) or table in self.db.tables):
         raise HTTP(404)
     if not self.has_permission("select", table):
         redirect(self.settings.auth.settings.on_failed_authorization)
     #if record_id and not self.has_permission("select", table):
     #    redirect(self.settings.auth.settings.on_failed_authorization)
     if not isinstance(table, self.db.Table):
         table = self.db[table]
     if not query:
         query = table.id > 0
     if not fields:
         fields = [table.ALL]
     rows = self.db(query).select(*fields,
                                  **dict(orderby=orderby, limitby=limitby))
     if not rows:
         return None  # Nicer than an empty table.
     if not "linkto" in attr:
         attr["linkto"] = self.url(args="read")
     if not "upload" in attr:
         attr["upload"] = self.url("download")
     if request.extension != "html":
         return rows.as_list()
     return SQLTABLES3(rows, headers=headers, **attr)
コード例 #5
0
def get_table(request):
    db = get_database(request)
    if len(request.args) > 1 and request.args[1] in db.tables:
        return (db, request.args[1])
    else:
        session.flash = T('invalid request')
        redirect(URL('index'))
コード例 #6
0
ファイル: appadmin.py プロジェクト: nervatura/nerva2py
def update():
    (db, table) = get_table(request)
    keyed = hasattr(db[table],'_primarykey')
    record = None
    if keyed:
        key = [f for f in request.vars if f in db[table]._primarykey]
        if key:
            record = db(db[table][key[0]] == request.vars[key[0]]).select().first()
    else:
        record = db(db[table].id == request.args(2)).select().first()

    if not record:
        qry = query_by_table_type(table, db)
        session.flash = T('record does not exist')
        redirect(URL('select', args=request.args[:1],
                     vars=dict(query=qry)))

    if keyed:
        for k in db[table]._primarykey:
            db[table][k].writable=False

    form = SQLFORM(db[table], record, deletable=True, delete_label=T('Check to delete'),
                   ignore_rw=ignore_rw and not keyed,
                   linkto=URL('select',
                   args=request.args[:1]), upload=URL(r=request,
                   f='download', args=request.args[:1]))

    if form.accepts(request.vars, session):
        session.flash = T('done!')
        qry = query_by_table_type(table, db)
        redirect(URL('select', args=request.args[:1],
                 vars=dict(query=qry)))
    return dict(form=form,table=db[table])
コード例 #7
0
ファイル: s3profile.py プロジェクト: AnirudhTiwari/eden
    def apply_method(self, r, **attr):
        """
            API entry point

            @param r: the S3Request instance
            @param attr: controller attributes for the request
        """

        if r.http in ("GET", "POST", "DELETE"):
            if r.record:
                # Initialize CRUD form
                self.settings = current.response.s3.crud
                self.sqlform = sqlform = self._config("crud_form")
                if not sqlform:
                    from s3forms import S3SQLDefaultForm
                    self.sqlform = S3SQLDefaultForm()

                # Render page
                output = self.profile(r, **attr)

            elif r.representation not in ("dl", "aadata"):
                # Redirect to the List View
                redirect(r.url(method=""))

            else:
                # No point redirecting
                r.error(404, current.ERROR.BAD_RECORD)
        else:
            r.error(405, current.ERROR.BAD_METHOD)
        return output
コード例 #8
0
    def apply_method(self, r, **attr):
        """
            API entry point

            @param r: the S3Request instance
            @param attr: controller attributes for the request
        """

        if r.http in ("GET", "POST", "DELETE"):
            if r.record:
                # Initialize CRUD form
                self.settings = current.response.s3.crud
                self.sqlform = sqlform = self._config("crud_form")
                if not sqlform:
                    from s3forms import S3SQLDefaultForm
                    self.sqlform = S3SQLDefaultForm()

                # Render page
                output = self.profile(r, **attr)

            elif r.representation not in ("dl", "aadata"):
                # Redirect to the List View
                redirect(r.url(method=""))

            else:
                # No point redirecting
                r.error(404, current.ERROR.BAD_RECORD)
        else:
            r.error(405, current.ERROR.BAD_METHOD)
        return output
コード例 #9
0
 def select(
     self,
     table,
     query=None,
     fields=None,
     orderby=None,
     limitby=None,
     headers={},
     **attr
     ):
     request = self.environment.request
     if not (isinstance(table, self.db.Table) or table in self.db.tables):
         raise HTTP(404)
     if not self.has_permission("select", table):
         redirect(self.settings.auth.settings.on_failed_authorization)
     #if record_id and not self.has_permission("select", table):
     #    redirect(self.settings.auth.settings.on_failed_authorization)
     if not isinstance(table, self.db.Table):
         table = self.db[table]
     if not query:
         query = table.id > 0
     if not fields:
         fields = [table.ALL]
     rows = self.db(query).select(*fields, **dict(orderby=orderby,
         limitby=limitby))
     if not rows:
         return None # Nicer than an empty table.
     if not "linkto" in attr:
         attr["linkto"] = self.url(args="read")
     if not "upload" in attr:
         attr["upload"] = self.url("download")
     if request.extension != "html":
         return rows.as_list()
     return SQLTABLES3(rows, headers=headers, **attr)
コード例 #10
0
ファイル: plugin_rqdboard.py プロジェクト: rpedroso/rqdboard
 def requeue_all(self):
     fq = get_failed_queue()
     job_ids = fq.job_ids
     count = len(job_ids)
     for job_id in job_ids:
         requeue_job(job_id)
     redirect(URL())
コード例 #11
0
ファイル: appadmin.py プロジェクト: nervatura/nerva2py
def get_table(request):
    db = get_database(request)
    if len(request.args) > 1 and request.args[1] in db.tables:
        return (db, request.args[1])
    else:
        session.flash = T('invalid request')
        redirect(URL('index'))
コード例 #12
0
def update():
    (db, table) = get_table(request)
    keyed = hasattr(db[table], '_primarykey')
    record = None
    if keyed:
        key = [f for f in request.vars if f in db[table]._primarykey]
        if key:
            record = db(
                db[table][key[0]] == request.vars[key[0]]).select().first()
    else:
        record = db(db[table].id == request.args(2)).select().first()

    if not record:
        qry = query_by_table_type(table, db)
        session.flash = T('record does not exist')
        redirect(URL('select', args=request.args[:1], vars=dict(query=qry)))

    if keyed:
        for k in db[table]._primarykey:
            db[table][k].writable = False

    form = SQLFORM(db[table],
                   record,
                   deletable=True,
                   delete_label=T('Check to delete'),
                   ignore_rw=ignore_rw and not keyed,
                   linkto=URL('select', args=request.args[:1]),
                   upload=URL(r=request, f='download', args=request.args[:1]))

    if form.accepts(request.vars, session):
        session.flash = T('done!')
        qry = query_by_table_type(table, db)
        redirect(URL('select', args=request.args[:1], vars=dict(query=qry)))
    return dict(form=form, table=db[table])
コード例 #13
0
ファイル: openid_auth.py プロジェクト: fmobus/forca-inf
    def _login_form(self,
                    openid_field_label=None,
                    submit_button=None,
                    _next=None,
                    style=None):
        """
        Render the form for OpenID login
        """
        def warning_openid_fail(session):
            session.warning = messages.openid_fail_discover

        style = style or """
background-attachment: scroll;
background-repeat: no-repeat;
background-image: url("http://wiki.openid.net/f/openid-16x16.gif");
background-position: 0% 50%;
background-color: transparent;
padding-left: 18px;
width: 400px;
"""
        style = style.replace("\n","")

        request = self.environment.request
        session = self.environment.session
        messages = self.messages
        hidden_next_input = ""
        if _next == 'profile':
            profile_url = self.environment.URL(r=request, f='user', args=['profile'])
            hidden_next_input = INPUT(_type="hidden", _name="_next", _value=profile_url)
        form = FORM(openid_field_label or self.messages.label_alt_login_username,
                    INPUT(_type="input", _name="oid",
                          requires=IS_NOT_EMPTY(error_message=messages.openid_fail_discover),
                          _style=style),
                    hidden_next_input,
                    INPUT(_type="submit", _value=submit_button or messages.submit_button),
                    " ",
                    A(messages.comment_openid_signin,
                      _href=messages.comment_openid_help_url,
                      _title=messages.comment_openid_help_title,
                      _class='openid-identifier',
                      _target="_blank"),
                    _action=self.login_url
                   )
        if form.accepts(request.vars, session):
            oid = request.vars.oid
            consumerhelper = self._init_consumerhelper()
            url = self.login_url
            return_to_url = self.return_to_url
            if not oid:
                warning_openid_fail(session)
                redirect(url)
            try:
                if request.vars.has_key('_next'):
                    return_to_url = self.return_to_url + '?_next=' + request.vars._next
                url = consumerhelper.begin(oid, self.realm, return_to_url)
            except DiscoveryFailure:
                warning_openid_fail(session)
            redirect(url)
        return form
コード例 #14
0
ファイル: ndr.py プロジェクト: tazjel/nerva2py
def getAppl():
  if request.vars.appl:
    file_name = os.path.join(request.folder, 'static/resources/application', str(request.vars.appl))
    if not os.path.isfile(file_name):
      return "Missing application!"
    redirect(URL('static/resources/application', str(request.vars.appl)))
  else:
    return "Missing appl parameter!"
コード例 #15
0
ファイル: controllers.py プロジェクト: chaconne7/eden
    def __call__(self):

        gtable = current.s3db.gis_location
        syria = current.db(gtable.name == "Syrian Arab Republic").select(gtable.id,
                                                                         limitby=(0, 1)
                                                                         ).first()

        redirect(URL(c="gis", f="location", args=[syria.id, "profile"]))
コード例 #16
0
ファイル: utils.py プロジェクト: bnmnetp/w2p-social-auth
 def wrapper(*args):
     selv = args[0]
     r = selv.environment.request
     if not selv.is_logged_in():
         nextt = URL(r=r, args=r.args)
         redirect(URL(args=['login'], vars={'_next': nextt}),
                  client_side=selv.settings.client_side)
     return f(*args)
コード例 #17
0
def qc_list():
    if 'flash' in request.vars:
        response.flash= request.vars['flash']
    if not db(db.episode.created_by == auth.user.id).count()>0:
        message= "You do not have any QC. Upload a QC first ;)"
        redirect(URL('default','add_qc?flash='+message))
    else:
        return locals()
コード例 #18
0
 def wrapper(*args):
     selv = args[0]
     r = selv.environment.request
     if not selv.is_logged_in():
         nextt = URL(r=r, args=r.args)
         redirect(URL(args=['login'], vars={'_next': nextt}),
                  client_side=selv.settings.client_side)
     return f(*args)
コード例 #19
0
ファイル: authservice.py プロジェクト: harker777/ToDoPy
def checkIfAuthorized():
    if (current.request.cookies.has_key('userid')):
        userId = current.request.cookies['userid'].value
        userName = current.request.cookies['username'].value
        current.userName = userName
        current.userId = userId
        return userId
    else:
        http.redirect(html.URL('auth', 'login'))
コード例 #20
0
ファイル: company.py プロジェクト: JFB1984/Manager
def reject_vacation():
    vacationid = request.args(0, cast = int)
    result = db(db.co_vacation.id == vacationid).update(status = 'Rejected')
    if result == 1:
        session.flash = 'Vacation rejected'
        redirect(URL('confirm_vacation'))
    else:
        session.flash = 'Errors occurs!'
        redirect(URL('confirm_vacation'))
    return dict()
コード例 #21
0
def contact():
    from models.contact import Contact

    db = application.db(models=[Contact])
    form = SQLFORM(db.Contact, _action=URL('experiments', 'default', 'contact'))

    if form.process(session=application.session).accepted:
        redirect(URL())

    return {'form': form}
コード例 #22
0
def getAppl():
    if request.vars.appl:
        file_name = os.path.join(request.folder,
                                 'static/resources/application',
                                 str(request.vars.appl))
        if not os.path.isfile(file_name):
            return "Missing application!"
        redirect(URL('static/resources/application', str(request.vars.appl)))
    else:
        return "Missing appl parameter!"
コード例 #23
0
ファイル: admin.py プロジェクト: pmcilwaine/web2py_unit_test
def myform():
    form = SQLFORM.factory(Field("first_name", "string"), Field("last_name", "string"))

    def onvalidation(form):
        pass

    if form.process(session=application.session, onvaliidation=onvalidation).accepted:
        redirect(URL())

    return dict(form=form)
コード例 #24
0
ファイル: plugin_rqdboard.py プロジェクト: rpedroso/rqdboard
 def job(self, job_id, queue_name, action):
     if action == 'cancel':
         cancel_job(job_id)
     elif action == 'requeue':
         requeue_job(job_id)
     else:
         raise HTTP(404)
     if current.request.ajax:
         return jobs_table(queue_name)
     redirect(URL())
コード例 #25
0
 def __call__(self):
     request = self.environment.request
     args = request.args
     if not args:
         redirect(self.environment.URL(r=request, args=['login']))
     if args[0] == 'login':
         return self.login()
     elif args[0] == 'oidresponse':
         self.process_response()
     else:
         raise HTTP(404)
コード例 #26
0
ファイル: plugin_rqdboard.py プロジェクト: rpedroso/rqdboard
 def compact(self, queue_name):
     q = Queue(queue_name)
     try:
         q.compact()
     except ResponseError:
         # Somethimes I get ResponseError('no such key")
         # from redis connection
         pass
     if current.request.ajax:
         return ''
     redirect(URL(args=['overview'] + current.request.args[1:]))
コード例 #27
0
def contact():
    from models.contact import Contact

    db = application.db(models=[Contact])
    form = SQLFORM(db.Contact,
                   _action=URL('experiments', 'default', 'contact'))

    if form.process(session=application.session).accepted:
        redirect(URL())

    return {'form': form}
コード例 #28
0
ファイル: helpers.py プロジェクト: saul/cs-iapt-longboxes
def flash(flash_class, text, redirect_url=None):
    """Updates the flash key and optionally redirects to another URL."""
    flash_info = {
        'class': flash_class,
        'text': text
    }

    if redirect_url:
        current.session.flash = flash_info
        redirect(redirect_url)
    else:
        current.response.flash = flash_info
コード例 #29
0
ファイル: company.py プロジェクト: JFB1984/Manager
def create_project():
    response.view = 'company/details_project.html'
    
    form = SQLFORM(db.co_project)
    
    if form.process().accepted:
        session.flash = 'Project created'
        redirect(URL('list_project'))
    elif form.errors:
        response.flash = 'Errors occurs!'
    
    return locals()
コード例 #30
0
def require_facebook_login(request, settings,next=None):
    """
    Used for redirecting the user to the Facebook
    login page if not already logged in.

    Usage:
      require_facebook_login(request,settings)
    """
    if not request.facebook: add_facebook_instance(request,settings)
    fb = request.facebook
    if not fb.check_session(request):
        redirect(fb.get_login_url(next=next))
コード例 #31
0
ファイル: s3tools.py プロジェクト: Koperj/SahanaEden
            def f(*a, **b):
                if not self.shn_logged_in():
                    request = self.environment.request
                    next = URL(r=request, args=request.args, vars=request.get_vars)
                    redirect(self.settings.login_url + "?_next=" + urllib.quote(next))

                if not self.shn_has_role(role) and not self.shn_has_role(1):
                    self.environment.session.error = self.messages.access_denied
                    next = self.settings.on_failed_authorization
                    redirect(next)

                return action(*a, **b)
コード例 #32
0
def file_upload():
    form = SQLFORM.factory(Field('file',
                                 'upload',
                                 uploadfolder=application.config.upload_folder,
                                 requires=IS_IMAGE(extensions=('jpg',
                                                               'jpeg'))),
                           _action=URL())

    if form.process().accepted:
        redirect(URL())

    return {'form': form}
コード例 #33
0
def myform():
    form = SQLFORM.factory(Field('first_name', 'string'),
                           Field('last_name', 'string'))

    def onvalidation(form):
        pass

    if form.process(session=application.session,
                    onvaliidation=onvalidation).accepted:
        redirect(URL())

    return dict(form=form)
コード例 #34
0
ファイル: controllers.py プロジェクト: vpccalderara/sahana
    def __call__(self):

        auth = current.auth
        ADMIN = auth.get_system_roles().ADMIN

        if auth.s3_has_role(ADMIN):

            T = current.T

            form = FORM(
                H3(T("Check transferability for all current cases")),
                INPUT(
                    _class="tiny primary button",
                    _type="submit",
                    _value=T("Update now"),
                ),
                P("(%s)" % T("This process can take a couple of minutes")),
            )

            if form.accepts(current.request.post_vars, current.session):

                # Get default site
                default_site = current.deployment_settings.get_org_default_site(
                )

                # Update transferability
                result = update_transferability(site_id=default_site)
                if result:
                    msg = current.T("%(number)s transferable cases found") % {
                        "number": result
                    }
                    current.session.confirmation = msg
                else:
                    msg = current.T("No transferable cases found")
                    current.session.warning = msg

                # Forward to list of transferable cases
                redirect(
                    URL(
                        c="dvr",
                        f="person",
                        vars={
                            "closed": "0",
                            "dvr_case.transferable__belongs": "True",
                            "show_family_transferable": "1",
                        },
                    ))

            self._view(THEME, "transferability.html")
            return {"form": form}

        else:
            auth.permission.fail()
コード例 #35
0
 def login(self):
     request = self.environment.request
     session = self.environment.session
     form = self.environment.FORM("openID: ",
                                  self.environment.INPUT(_type="input", _name="oid"),
                                  self.environment.INPUT(_type="submit"))
     if form.accepts(request.vars, session):
         auth_req = self.consumer.begin(request.vars.oid)
         auth_req.addExtension(SRegRequest(required=['email','nickname']))
         url = auth_req.redirectURL(return_to=self.return_to_url, realm=self.realm)
         #print url
         redirect(url)
     return form
コード例 #36
0
def edit():
    form = SQLFORM.factory(
        Field('first_name', 'string',
              requires=IS_NOT_EMPTY(error_message='Please enter first name')),
        Field('last_name', 'string',
              requires=IS_NOT_EMPTY(error_message='Please enter last name')),
        _action=URL('experiments', 'default', 'edit')
    )

    if form.process(session=application.session).accepted:
        redirect(URL())

    return {'form': form}
コード例 #37
0
ファイル: globals.py プロジェクト: Nuevalgo/Feedbot
 def requires_https(self):
     """
     If request comes in over HTTP, redirects it to HTTPS
     and secures the session.
     """
     cmd_opts = global_settings.cmd_options
     # checking if this is called within the scheduler or within the shell
     # in addition to checking if it's not a cronjob
     if (cmd_opts and (cmd_opts.shell or cmd_opts.scheduler)) or global_settings.cronjob or self.is_https:
         current.session.secure()
     else:
         current.session.forget()
         redirect(URL(scheme="https", args=self.args, vars=self.vars))
コード例 #38
0
def require_facebook_add(request, settings, next=None):
    """
    Used for redirecting the user to the Facebook
    add-app page.

    Usage:
      require_facebook_add(request,settings)
    """
    if not request.facebook: add_facebook_instance(request,settings)
    fb = request.facebook
    if not fb.check_session(request):
        redirect(fb.get_login_url(next=next))
    if not fb.added:
        redirect(fb.get_add_url(next=next)) 
コード例 #39
0
ファイル: company.py プロジェクト: JFB1984/Manager
def create_task():
    response.view = 'company/details_task.html'
    
    projectid = request.args(1, cast = int)
    projectname = db.co_project(projectid).name
    db.co_task.project.default = projectid
    form = SQLFORM(db.co_task)
    
    if form.process().accepted:
        session.flash = 'Task created'
        redirect(URL('list_task', args = (projectid)))
    elif form.errors:
        response.flash = 'Errors occurs!'
    return locals()
コード例 #40
0
ファイル: openid_auth.py プロジェクト: fmobus/forca-inf
    def get_user(self):
        """
        It supports the logout_url, implementing the get_user and login_form
        for cas usage of gluon.tools.Auth.
        """
        environment = self.environment
        request = environment.request
        args = request.args

        if args[0] == 'logout':
            return True # Let logout_url got called

        if environment.session.w2popenid:
            w2popenid = environment.session.w2popenid
            db = self.db
            if (w2popenid.ok is True and w2popenid.oid): # OpenID authenticated
                if self._w2popenid_expired(w2popenid):
                    del(self.environment.session.w2popenid)
                    flash = self.messages.flash_openid_expired
                    environment.session.warning = flash
                    redirect(self.auth.settings.login_url)
                oid = self._remove_protocol(w2popenid.oid)
                alt_login = self._find_matched_openid(db, oid)

                nextvar = self.nextvar
                # This OpenID not in the database. If user logged in then add it
                # into database, else ask user to login or register.
                if not alt_login:
                    if self.auth.is_logged_in():
                        # TODO: ask first maybe
                        self._associate_user_openid(self.auth.user, oid)
                        if self.environment.session.w2popenid:
                            del(self.environment.session.w2popenid)
                        environment.session.flash = self.messages.flash_openid_associated
                        if request.vars.has_key(nextvar):
                            redirect(request.vars[nextvar])
                        redirect(self.auth.settings.login_next)

                    if not request.vars.has_key(nextvar):
                        # no next var, add it and do login again
                        # so if user login or register can go back here to associate the OpenID
                        redirect(self.environment.URL(r=request,
                                                      args=['login'],
                                                      vars={nextvar:self.login_url}))
                    self.login_form = self._form_with_notification()
                    environment.session.flash = self.messages.flash_associate_openid
                    return None # need to login or register to associate this openid

                # Get existed OpenID user
                user = db(self.table_user.id==alt_login.user).select().first()
                if user:
                    if self.environment.session.w2popenid:
                        del(self.environment.session.w2popenid)
                if 'username' in self.table_user.fields():
                    username = '******'
                elif 'email' in self.table_user.fields():
                    username = '******'
                return {username: user[username]} if user else None # login success (almost)
 
        return None # just start to login
コード例 #41
0
ファイル: globals.py プロジェクト: mjhea0/realpython-book2
 def requires_https(self):
     """
     If request comes in over HTTP, redirects it to HTTPS
     and secures the session.
     """
     cmd_opts = global_settings.cmd_options
     #checking if this is called within the scheduler or within the shell
     #in addition to checking if it's not a cronjob
     if ((cmd_opts and (cmd_opts.shell or cmd_opts.scheduler))
         or global_settings.cronjob or self.is_https):
         current.session.secure()
     else:
         current.session.forget()
         redirect(URL(scheme='https', args=self.args, vars=self.vars))
コード例 #42
0
def edit():
    form = SQLFORM.factory(
        Field('first_name',
              'string',
              requires=IS_NOT_EMPTY(error_message='Please enter first name')),
        Field('last_name',
              'string',
              requires=IS_NOT_EMPTY(error_message='Please enter last name')),
        _action=URL('experiments', 'default', 'edit'))

    if form.process(session=application.session).accepted:
        redirect(URL())

    return {'form': form}
コード例 #43
0
ファイル: company.py プロジェクト: JFB1984/Manager
def view_task():
    taskid = request.args(1, cast = int)
    projectid = db(db.co_task.id == taskid).select(db.co_task.project).first().project
    task = SQLFORM(db.co_task, taskid, showid = False, readonly = True)
    posts = db(db.co_taskpost.task == taskid).select(orderby = db.co_taskpost.created_on)
    db.co_taskpost.task.default = taskid
    post = SQLFORM(db.co_taskpost)
    if post.process().accepted:
        session.flash = 'Post added'
        redirect(URL('view_task', args = ('view', taskid)))
    elif post.errors:
        response.flash = 'Errors occurs!'
    
    return locals()
コード例 #44
0
def _auth():
    r = current.request

    # Store "remember me" value in session
    current.strategy.session_set('remember', r.vars.get('remember', False))

    if r.vars.backend == 'persona':
        # Mozilla Persona
        if r.vars.assertion == '': del r.vars.assertion
        redirect(URL(f='complete', args=['persona'], vars=r.vars))
    else:
        try:
            return do_auth(current.backend)
        except Exception as e:
            process_exception(e)
コード例 #45
0
 def __call__(self):
     request = self.environment.request
     args = request.args
     if not args:
         redirect(URL(r=request, args='login'))
     if args[0] == 'login':
         return self.social_login()
     if args[0] == 'logout':
         return self.logout()
     if args[0] == 'confirm':
         return self.__confirm()
     elif args[0] in ['logout', 'associations', 'confirm', 'profile']:
         return getattr(self, args[0])()
     else:
         raise HTTP(404)
コード例 #46
0
def verifiable_redirect(*args, **kwargs):
    """
    Redirect function to be used in combination with @verify decorator.
    Adds a uuid to session and URL vars which the decorator then
    verifies after the redirect.
    Must be called with args/kwargs that are normally passed to URL().

    """

    uuid = web2py_uuid()
    current.plugin_social_auth.s.req_uuid = uuid
    varz = kwargs.get('vars', {})
    varz['req_uuid'] = uuid
    kwargs['vars'] = varz
    redirect(URL(*args, **kwargs))
コード例 #47
0
def show_qc():
    id=None
    key=None
    episode = None
    #start, limit, orderQuery, filterQuery = ExtJS.getExtPaging(request, limit=50)
    if len(request.args)>=2:
        id = request.args[0]
        key = request.args[1]
        episode= db((db.episode.id==id)&(db.episode.key==key)).select().first()
        #subs = db((db.sub.episode == id) & (db.episode.key==key)).select(limitby=(start,limit))
    if episode:
        return locals()
    else:
        message= "Invalid QC"
        redirect(URL('default','qc_list?flash='+message))
コード例 #48
0
ファイル: s3profile.py プロジェクト: gnarula/eden_deployment
    def apply_method(self, r, **attr):
        """
            API entry point

            @param r: the S3Request instance
            @param attr: controller attributes for the request
        """

        if r.http in ("GET", "POST", "DELETE"):
            if r.record:
                output = self.profile(r, **attr)
            else:
                # Redirect to the List View
                redirect(r.url(method=""))
        else:
            r.error(405, current.ERROR.BAD_METHOD)
        return output
コード例 #49
0
 def f(*args, **kwargs):
     if not self.has_role(roles):
         return redirect(
             URL(r=self.request,
                 c='members',
                 f='login',
                 vars=dict(err='needrole')))
     return func(*args, **kwargs)
コード例 #50
0
 def f(*args, **kwargs):
     if not self.is_auth():
         return redirect(
             URL(r=self.request,
                 c='members',
                 f='login',
                 vars=dict(err='needlogin')))
     return func(*args, **kwargs)
コード例 #51
0
ファイル: storage.py プロジェクト: guadaltech/web2py-ruben
 def __call__(self, i, default=DEFAULT, cast=None, otherwise=None):
     """Allows to use a special syntax for fast-check of
     `request.args()` validity.
     :params:
         i: index
         default: use this value if arg not found
         cast: type cast
         otherwise:
             will be executed when:
                 - casts fail
                 - value not found, dont have default and otherwise is
                 especified
             can be:
                 - None: results in a 404
                 - str: redirect to this address
                 - callable: calls the function (nothing is passed)
     Example:
         You can use::
             request.args(0,default=0,cast=int,otherwise='http://error_url')
             request.args(0,default=0,cast=int,otherwise=lambda:...)
     """
     n = len(self)
     if 0 <= i < n or -n <= i < 0:
         value = self[i]
     elif default is DEFAULT:
         value = None
     else:
         value, cast, otherwise = default, False, False
     try:
         if cast:
             value = cast(value)
         if not value and otherwise:
             raise ValueError('Otherwise will raised.')
     except (ValueError, TypeError):
         from gluon.http import HTTP, redirect
         if otherwise is None:
             raise HTTP(404)
         elif isinstance(otherwise, str):
             redirect(otherwise)
         elif callable(otherwise):
             return otherwise()
         else:
             raise RuntimeError("invalid otherwise")
     return value
コード例 #52
0
    def process_exception(self, exception):
        self.strategy = current.strategy
        if self.strategy is None or self.__raise_exception():
            raise

        #FIXME: workaround for issue:
        # https://code.google.com/p/w2p-social-auth/issues/detail?id=1
        def is_social_auth_exception(ex):
            return ex.__class__.__module__ in('social.exceptions', SocialAuthBaseException.__module__)

        if is_social_auth_exception(exception):
            backend_name = current.session.backend
            message = exception.message

            logging.error("[social_auth] backend: %s | message: %s" % (backend_name, message))

            current.plugin_social_auth.session.flash = message
            redirect(self.__get_redirect_uri())
        else:
            raise
コード例 #53
0
    def __confirm(self, verified=False):
        # Hide auth navbar
        self.navbar = lambda **x: ''

        backend = current.request.vars.backend

        if not backend:
            raise HTTP(400)

        form = self.__confirm_form(SocialAuth.__get_providers()[backend])

        # Allow requests that use  form
        if form.process().accepted:
            # Get vars back from session and delete them
            varz = current.plugin_social_auth.s.pop('confirm', {})

            return redirect(URL(f='complete', args=['confirmed'], vars=varz))

        # Deny request that do not use form and are not verified as app redirects
        if not verified:
            raise HTTP(400)

        return current.response.render(dict(form=form))
コード例 #54
0
ファイル: main.py プロジェクト: mjhea0/realpython-book2
def wsgibase(environ, responder):
    """
    The gluon wsgi application. The first function called when a page
    is requested (static or dynamic). It can be called by paste.httpserver
    or by apache mod_wsgi (or any WSGI-compatible server).

      - fills request with info
      - the environment variables, replacing '.' with '_'
      - adds web2py path and version info
      - compensates for fcgi missing path_info and query_string
      - validates the path in url

    The url path must be either:

    1. for static pages:

      - /<application>/static/<file>

    2. for dynamic pages:

      - /<application>[/<controller>[/<function>[/<sub>]]][.<extension>]

    The naming conventions are:

      - application, controller, function and extension may only contain
        `[a-zA-Z0-9_]`
      - file and sub may also contain '-', '=', '.' and '/'
    """
    eget = environ.get
    current.__dict__.clear()
    request = Request(environ)
    response = Response()
    session = Session()
    env = request.env
    #env.web2py_path = global_settings.applications_parent
    env.web2py_version = web2py_version
    #env.update(global_settings)
    static_file = False
    try:
        try:
            try:
                # ##################################################
                # handle fcgi missing path_info and query_string
                # select rewrite parameters
                # rewrite incoming URL
                # parse rewritten header variables
                # parse rewritten URL
                # serve file if static
                # ##################################################

                fixup_missing_path_info(environ)
                (static_file, version, environ) = url_in(request, environ)
                response.status = env.web2py_status_code or response.status

                if static_file:
                    if eget('QUERY_STRING', '').startswith('attachment'):
                        response.headers['Content-Disposition'] \
                            = 'attachment'
                    if version:
                        response.headers['Cache-Control'] = 'max-age=315360000'
                        response.headers[
                            'Expires'] = 'Thu, 31 Dec 2037 23:59:59 GMT'
                    response.stream(static_file, request=request)

                # ##################################################
                # fill in request items
                # ##################################################
                app = request.application  # must go after url_in!

                if not global_settings.local_hosts:
                    local_hosts = set(['127.0.0.1', '::ffff:127.0.0.1', '::1'])
                    if not global_settings.web2py_runtime_gae:
                        try:
                            fqdn = socket.getfqdn()
                            local_hosts.add(socket.gethostname())
                            local_hosts.add(fqdn)
                            local_hosts.update([
                                addrinfo[4][0]
                                for addrinfo in getipaddrinfo(fqdn)
                            ])
                            if env.server_name:
                                local_hosts.add(env.server_name)
                                local_hosts.update([
                                    addrinfo[4][0] for addrinfo in
                                    getipaddrinfo(env.server_name)
                                ])
                        except (socket.gaierror, TypeError):
                            pass
                    global_settings.local_hosts = list(local_hosts)
                else:
                    local_hosts = global_settings.local_hosts
                client = get_client(env)
                x_req_with = str(env.http_x_requested_with).lower()

                request.update(
                    client = client,
                    folder = abspath('applications', app) + os.sep,
                    ajax = x_req_with == 'xmlhttprequest',
                    cid = env.http_web2py_component_element,
                    is_local = env.remote_addr in local_hosts,
                    is_https = env.wsgi_url_scheme in HTTPS_SCHEMES or \
                        request.env.http_x_forwarded_proto in HTTPS_SCHEMES \
                        or env.https == 'on'
                    )
                request.compute_uuid()  # requires client
                request.url = environ['PATH_INFO']

                # ##################################################
                # access the requested application
                # ##################################################

                disabled = pjoin(request.folder, 'DISABLED')
                if not exists(request.folder):
                    if app == rwthread.routes.default_application \
                            and app != 'welcome':
                        redirect(URL('welcome', 'default', 'index'))
                    elif rwthread.routes.error_handler:
                        _handler = rwthread.routes.error_handler
                        redirect(
                            URL(_handler['application'],
                                _handler['controller'],
                                _handler['function'],
                                args=app))
                    else:
                        raise HTTP(404,
                                   rwthread.routes.error_message %
                                   'invalid request',
                                   web2py_error='invalid application')
                elif not request.is_local and exists(disabled):
                    raise HTTP(
                        503,
                        "<html><body><h1>Temporarily down for maintenance</h1></body></html>"
                    )

                # ##################################################
                # build missing folders
                # ##################################################

                create_missing_app_folders(request)

                # ##################################################
                # get the GET and POST data
                # ##################################################

                #parse_get_post_vars(request, environ)

                # ##################################################
                # expose wsgi hooks for convenience
                # ##################################################

                request.wsgi = LazyWSGI(environ, request, response)

                # ##################################################
                # load cookies
                # ##################################################

                if env.http_cookie:
                    try:
                        request.cookies.load(env.http_cookie)
                    except Cookie.CookieError, e:
                        pass  # invalid cookies

                # ##################################################
                # try load session or create new session file
                # ##################################################

                if not env.web2py_disable_session:
                    session.connect(request, response)

                # ##################################################
                # run controller
                # ##################################################

                if global_settings.debugging and app != "admin":
                    import gluon.debug
                    # activate the debugger
                    gluon.debug.dbg.do_debug(mainpyfile=request.folder)

                serve_controller(request, response, session)

            except HTTP, http_response:

                if static_file:
                    return http_response.to(responder, env=env)

                if request.body:
                    request.body.close()

                if hasattr(current, 'request'):

                    # ##################################################
                    # on success, try store session in database
                    # ##################################################
                    session._try_store_in_db(request, response)

                    # ##################################################
                    # on success, commit database
                    # ##################################################

                    if response.do_not_commit is True:
                        BaseAdapter.close_all_instances(None)
                    elif response.custom_commit:
                        BaseAdapter.close_all_instances(response.custom_commit)
                    else:
                        BaseAdapter.close_all_instances('commit')

                    # ##################################################
                    # if session not in db try store session on filesystem
                    # this must be done after trying to commit database!
                    # ##################################################

                    session._try_store_in_cookie_or_file(request, response)

                    # Set header so client can distinguish component requests.
                    if request.cid:
                        http_response.headers.setdefault(
                            'web2py-component-content', 'replace')

                    if request.ajax:
                        if response.flash:
                            http_response.headers['web2py-component-flash'] = \
                                urllib2.quote(xmlescape(response.flash)\
                                                  .replace('\n',''))
                        if response.js:
                            http_response.headers['web2py-component-command'] = \
                                urllib2.quote(response.js.replace('\n',''))

                    # ##################################################
                    # store cookies in headers
                    # ##################################################

                    session._fixup_before_save()
                    http_response.cookies2headers(response.cookies)

                ticket = None

            except RestrictedError, e:

                if request.body:
                    request.body.close()

                # ##################################################
                # on application error, rollback database
                # ##################################################

                # log tickets before rollback if not in DB
                if not request.tickets_db:
                    ticket = e.log(request) or 'unknown'
                # rollback
                if response._custom_rollback:
                    response._custom_rollback()
                else:
                    BaseAdapter.close_all_instances('rollback')
                # if tickets in db, reconnect and store it in db
                if request.tickets_db:
                    ticket = e.log(request) or 'unknown'

                http_response = \
                    HTTP(500, rwthread.routes.error_message_ticket %
                         dict(ticket=ticket),
                         web2py_error='ticket %s' % ticket)
コード例 #55
0
    def _login_form(self,
                    openid_field_label=None,
                    submit_button=None,
                    _next=None,
                    style=None):
        """
        Render the form for OpenID login
        """
        def warning_openid_fail(session):
            session.warning = messages.openid_fail_discover

        style = style or """
background-attachment: scroll;
background-repeat: no-repeat;
background-image: url("http://wiki.openid.net/f/openid-16x16.gif");
background-position: 0% 50%;
background-color: transparent;
padding-left: 18px;
width: 400px;
"""
        style = style.replace("\n", "")

        request = self.environment.request
        session = self.environment.session
        messages = self.messages
        hidden_next_input = ""
        if _next == 'profile':
            profile_url = self.environment.URL(r=request,
                                               f='user',
                                               args=['profile'])
            hidden_next_input = INPUT(_type="hidden",
                                      _name="_next",
                                      _value=profile_url)
        form = FORM(openid_field_label
                    or self.messages.label_alt_login_username,
                    INPUT(_type="input",
                          _name="oid",
                          requires=IS_NOT_EMPTY(
                              error_message=messages.openid_fail_discover),
                          _style=style),
                    hidden_next_input,
                    INPUT(_type="submit",
                          _value=submit_button or messages.submit_button),
                    " ",
                    A(messages.comment_openid_signin,
                      _href=messages.comment_openid_help_url,
                      _title=messages.comment_openid_help_title,
                      _class='openid-identifier',
                      _target="_blank"),
                    _action=self.login_url)
        if form.accepts(request.vars, session):
            oid = request.vars.oid
            consumerhelper = self._init_consumerhelper()
            url = self.login_url
            return_to_url = self.return_to_url
            if not oid:
                warning_openid_fail(session)
                redirect(url)
            try:
                if request.vars.has_key('_next'):
                    return_to_url = self.return_to_url + '?_next=' + request.vars._next
                url = consumerhelper.begin(oid, self.realm, return_to_url)
            except DiscoveryFailure:
                warning_openid_fail(session)
            redirect(url)
        return form
コード例 #56
0
    def get_user(self):
        """
        It supports the logout_url, implementing the get_user and login_form
        for cas usage of gluon.tools.Auth.
        """
        environment = self.environment
        request = environment.request
        args = request.args

        if args[0] == 'logout':
            return True  # Let logout_url got called

        if environment.session.w2popenid:
            w2popenid = environment.session.w2popenid
            db = self.db
            if (w2popenid.ok is True
                    and w2popenid.oid):  # OpenID authenticated
                if self._w2popenid_expired(w2popenid):
                    del (self.environment.session.w2popenid)
                    flash = self.messages.flash_openid_expired
                    environment.session.warning = flash
                    redirect(self.auth.settings.login_url)
                oid = self._remove_protocol(w2popenid.oid)
                alt_login = self._find_matched_openid(db, oid)

                nextvar = self.nextvar
                # This OpenID not in the database. If user logged in then add it
                # into database, else ask user to login or register.
                if not alt_login:
                    if self.auth.is_logged_in():
                        # TODO: ask first maybe
                        self._associate_user_openid(self.auth.user, oid)
                        if self.environment.session.w2popenid:
                            del (self.environment.session.w2popenid)
                        environment.session.flash = self.messages.flash_openid_associated
                        if request.vars.has_key(nextvar):
                            redirect(request.vars[nextvar])
                        redirect(self.auth.settings.login_next)

                    if not request.vars.has_key(nextvar):
                        # no next var, add it and do login again
                        # so if user login or register can go back here to associate the OpenID
                        redirect(
                            self.environment.URL(
                                r=request,
                                args=['login'],
                                vars={nextvar: self.login_url}))
                    self.login_form = self._form_with_notification()
                    environment.session.flash = self.messages.flash_associate_openid
                    return None  # need to login or register to associate this openid

                # Get existed OpenID user
                user = db(
                    self.table_user.id == alt_login.user).select().first()
                if user:
                    if self.environment.session.w2popenid:
                        del (self.environment.session.w2popenid)
                if 'username' in self.table_user.fields():
                    username = '******'
                elif 'email' in self.table_user.fields():
                    username = '******'
                return {
                    username: user[username]
                } if user else None  # login success (almost)

        return None  # just start to login