Esempio n. 1
0
    def GET(self):
        """
        HTTP Success:
            200 OK

        HTTP Error:
            401 Unauthorized

        :param QUERY_STRING: the URL query string itself

        :returns: "Rucio-Auth-Token" as a variable-length string header.
        """

        header('Access-Control-Allow-Origin', ctx.env.get('HTTP_ORIGIN'))
        header('Access-Control-Allow-Headers',
               ctx.env.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS'))
        header('Access-Control-Allow-Methods', '*')
        header('Access-Control-Allow-Credentials', 'true')

        # interaction with web browser - display response in html format
        header('Content-Type', 'text/html')
        header('Cache-Control',
               'no-cache, no-store, max-age=0, must-revalidate')
        header('Cache-Control', 'post-check=0, pre-check=0', False)
        header('Pragma', 'no-cache')

        query_string = ctx.env.get('QUERY_STRING')
        try:
            fetchtoken = ctx.env.get('HTTP_X_RUCIO_CLIENT_FETCH_TOKEN')
            fetchtoken = (fetchtoken == 'True')
            result = redirect_auth_oidc(query_string, fetchtoken)

        except AccessDenied:
            render = template.render(
                join(dirname(__file__), '../auth_templates/'))
            return render.auth_crash('contact')

        except RucioException:
            render = template.render(
                join(dirname(__file__), '../auth_templates/'))
            return render.auth_crash('internal_error')

        except Exception:
            print(format_exc())
            render = template.render(
                join(dirname(__file__), '../auth_templates/'))
            return render.auth_crash('internal_error')

        if not result:
            render = template.render(
                join(dirname(__file__), '../auth_templates/'))
            return render.auth_crash('no_token')
        if fetchtoken:
            # this is only a case of returning the final token to the Rucio Client polling
            # or requesting token after copy-pasting the Rucio code from the web page page
            header('Content-Type', 'application/octet-stream')
            header('X-Rucio-Auth-Token', result)
            return str()
        else:
            raise seeother(result)
Esempio n. 2
0
    def GET(self):
        """
        HTTP Success:
            200 OK

        HTTP Error:
            401 Unauthorized

        :param QUERY_STRING: the URL query string itself

        :returns: "Rucio-Auth-Token" as a variable-length string header.
        """

        header('Access-Control-Allow-Origin', ctx.env.get('HTTP_ORIGIN'))
        header('Access-Control-Allow-Headers',
               ctx.env.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS'))
        header('Access-Control-Allow-Methods', '*')
        header('Access-Control-Allow-Credentials', 'true')

        header('Content-Type', 'text/html')
        header('Cache-Control',
               'no-cache, no-store, max-age=0, must-revalidate')
        header('Cache-Control', 'post-check=0, pre-check=0', False)
        header('Pragma', 'no-cache')

        query_string = ctx.env.get('QUERY_STRING')
        ip = ctx.env.get('HTTP_X_FORWARDED_FOR')
        if ip is None:
            ip = ctx.ip

        try:
            result = get_token_oidc(query_string, ip)

        except AccessDenied:
            render = template.render(
                join(dirname(__file__), '../auth_templates/'))
            return render.auth_crash('contact')
        except RucioException:
            render = template.render(
                join(dirname(__file__), '../auth_templates/'))
            return render.auth_crash('internal_error')
        except Exception:
            print(format_exc())
            render = template.render(
                join(dirname(__file__), '../auth_templates/'))
            return render.auth_crash('internal_error')

        render = template.render(join(dirname(__file__), '../auth_templates/'))
        if not result:
            return render.auth_crash('no_result')
        if 'fetchcode' in result:
            authcode = result['fetchcode']
            return render.auth_granted(authcode)
        elif 'polling' in result and result['polling'] is True:
            authcode = "allok"
            return render.auth_granted(authcode)
        else:
            return render.auth_crash('bad_request')
Esempio n. 3
0
	def GET(self, action):
		if not session.auth:
			session.page = action
			return render('templates').login('')
		settings = {}
		with open(self.config) as file:
			for line in file:
				line = line.strip()
				if not line or line.startswith('#'):
					continue
				key, value = line.split(': ')
				settings[key] = value
		return render('templates').settings(settings, int(self.running()), self.captchas())
Esempio n. 4
0
 def GET(self):
     try:
         get_input = input(_method='get')
         ses = sessionmaker(bind=engine.DBEngine.get_engine());
         s = ses();
         c = s.query(models.Citizen).filter_by(id=int(get_input['id'])).first()
         s.delete(c)
         s.commit()
         c = s.query(models.Citizen).order_by(models.Citizen.id)
         render = template.render('src/templates/citizen')
         return render.list(c)
     except Exception, e:
         render = template.render('src/templates')
         return render.error(err_msg=e)
Esempio n. 5
0
def authenticate(rendered_tpl):

    try:
        auth_type = config_get('webui', 'auth_type')

    except:
        auth_type = 'x509'

    session_token = cookies().get('x-rucio-auth-token')
    validate_token = authentication.validate_auth_token(session_token)

    render = template.render(join(dirname(__file__), '../templates'))

    if auth_type == 'x509':
        return check_token(rendered_tpl)

    elif auth_type == 'userpass':
        if validate_token:
            return log_in(None, rendered_tpl)

        return seeother('/login')

    elif auth_type == 'x509_userpass':
        if ctx.env.get('SSL_CLIENT_VERIFY') == 'SUCCESS':
            return check_token(rendered_tpl)

        elif validate_token:
            return log_in(None, rendered_tpl)

        return render.no_certificate()

    return render.problem('Invalid auth type')
Esempio n. 6
0
 def GET(self):
     ses = sessionmaker(bind=engine.DBEngine.get_engine());
     s = ses();
     c = s.query(models.Citizen).order_by(models.Citizen.id)
     render = template.render('src/templates/citizen')
     print render.__dict__
     return render.list(c)
Esempio n. 7
0
File: utils.py Progetto: zlion/rucio
def authenticate(rendered_tpl):
    """ Select the auth type defined in config """

    session_token = cookies().get('x-rucio-auth-token')
    validate_token = authentication.validate_auth_token(session_token)

    render = template.render(join(dirname(__file__), '../templates'))

    if AUTH_TYPE == 'x509':
        return check_token(rendered_tpl)

    elif AUTH_TYPE == 'userpass':
        if validate_token:
            return log_in(None, rendered_tpl)

        return seeother('/login')

    elif AUTH_TYPE == 'x509_userpass':
        if ctx.env.get('SSL_CLIENT_VERIFY') == 'SUCCESS':
            return check_token(rendered_tpl)

        elif validate_token:
            return log_in(None, rendered_tpl)

        return render.no_certificate()

    elif AUTH_TYPE == 'saml':
        return saml_authentication("GET", rendered_tpl)

    return render.problem('Invalid auth type')
Esempio n. 8
0
	def POST(self):
		chdir(path[0]+sep+'avinfo')
		render = template.render('templates/')
		f = updata_form();
		if not f.validates():
			return render.updata(f)
		aid = f.id.value
		c = connect()
		nav,ntitle,nupid,\
		ncreate_time,nplay_times,ncollects_count,\
		ndans_count,nreview_count,ncoin_count = \
		int(f.av.value),f.title.value,int(f.up.value),\
		str(f.create_time.value),int(f.play_times.value),int(f.collects_count.value),\
		int(f.dans_count.value),int(f.reviews_count.value),int(f.coins_count.value)
		insertdic = {}
		insertdic["av"] = nav
		insertdic["title"] = ntitle
		insertdic["up_id"] = nupid
		insertdic['create_stamp'] = ncreate_time
		insertdic["create_at"] = ncreate_time
		insertdic["play_times"] = nplay_times
		insertdic["collect_times"] = ncollects_count
		insertdic["dan_count"] = ndans_count
		insertdic["review_times"] = nreview_count
		insertdic['coins_count'] = ncoin_count
		print insertdic
		con = connect()
		result = insert_av_info(con,insertdic)
		if result == 403:
			f.up.note = "该up id不满足约束条件"
			return render.insert(f)
		return render.success('updata')
Esempio n. 9
0
def main():
    urls = ('/', 'HomePage', '/push/rev', 'RevScanData', '/items', 'ShowData',
            '/idact', 'id_for_Update', '/stact', 'state_for_Update',
            '/api/logincy', 'getToken', '/api/content', 'trans_content',
            '/api/weakness', 'trans_weakness', '/api/getTimeInterval',
            'getTimeInterval')
    app = application(urls, globals())
    app.internalerror = debugerror

    if web.config.get('_session') is None:
        ds = init_ds()
        session = Session(app, ds)
        web.config._session = session

    if web.config.get('_render') is None:
        render = template.render('templates', globals={'context': session})
        web.config._render = render

    if web.config.get('_cookies') is None:
        cookies = cookielib.CookieJar()
        web.config._cookies = cookies

    if web.config.get('_opener') is None:
        opener = init_opener(web.config._cookies)
        web.config._opener = opener

    if web.config.get('_rev') is None:
        web.config._rev = {}

    app.wsgifunc(StaticMiddleware)
    return app
Esempio n. 10
0
 def GET(self):
     if session.loggedin:
         return session.username
     # if logged():
     #    ...
     # else:
     template = render('template')
     return template.login()
Esempio n. 11
0
 def GET(self):
     try:
         render = template.render('src/templates/citizen')
         get_input = input(_method='get')
         ses = sessionmaker(bind=engine.DBEngine.get_engine());
         s = ses()
         c = s.query(models.Citizen).filter_by(id=int(get_input['id'])).first()
         c_form = form.Form(
             form.Textbox('name', value=c.name),
             form.Textbox('surname', value=c.surname),
             form.Textbox('birth_date', value=str(c.birth_date)),
             form.Textbox('pesel', value=str(c.pesel))
         )
         return render.generic(c_form)
     except Exception, e:
         render = template.render('src/templates')
         return render.error(err_msg=e)
Esempio n. 12
0
 def __init__(self):
     self.TextBoxList = []
     self.ButtonList = []
     self.DropdownList = []
     self.CheckBoxList = []
     self.divGetHtml = {}
             
     self.render2 = template.render('template/')
Esempio n. 13
0
 def GET(self):
     try:
         render = template.render('src/templates/user')
         get_input = input(_method='get')
         ses = sessionmaker(bind=engine.DBEngine.get_engine());
         s = ses()
         c = s.query(models.User).filter_by(id=int(get_input['id'])).first()
         c_form = form.Form(
             form.Textbox('email', value=c.email),
             form.Textbox('password', value=c.password),
             form.Textbox('role', value=str(c.role)),
             form.Textbox('citizen_id', value=str(c.citizen_id))
         )
         return render.generic(c_form)
     except Exception, e:
         render = template.render('src/templates')
         return render.error(err_msg=e)
Esempio n. 14
0
    def GET(self):
        """
        HTTP Success:
            200 OK

        HTTP Error:
            401 Unauthorized

        :param QUERY_STRING: the URL query string itself

        :returns: "Rucio-Auth-Token" as a variable-length string header.
        """

        header('Access-Control-Allow-Origin', ctx.env.get('HTTP_ORIGIN'))
        header('Access-Control-Allow-Headers', ctx.env.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS'))
        header('Access-Control-Allow-Methods', '*')
        header('Access-Control-Allow-Credentials', 'true')

        header('Content-Type', 'application/octet-stream')
        header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate')
        header('Cache-Control', 'post-check=0, pre-check=0', False)
        header('Pragma', 'no-cache')

        query_string = ctx.env.get('QUERY_STRING')
        ip = ctx.env.get('HTTP_X_FORWARDED_FOR')
        if ip is None:
            ip = ctx.ip

        try:
            result = get_token_oidc(query_string, ip)

        except AccessDenied:
            raise generate_http_error(401, 'CannotAuthorize', 'Cannot authorize token request.')
        except RucioException as error:
            raise generate_http_error(500, error.__class__.__name__, error.args[0])
        except Exception as error:
            print(format_exc())
            raise InternalError(error)

        if not result:
            raise generate_http_error(401, 'CannotAuthorize', 'Cannot authorize token request.')
        if 'token' in result and 'webhome' not in result:
            header('X-Rucio-Auth-Token', result['token'].token)  # pylint: disable=no-member
            header('X-Rucio-Auth-Token-Expires', date_to_str(result['token'].expired_at))  # pylint: disable=no-member
            return str()
        elif 'webhome' in result:
            webhome = result['webhome']
            if webhome is None:
                header('Content-Type', 'text/html')
                render = template.render(join(dirname(__file__), '../auth_templates/'))
                return render.auth_crash('unknown_identity')
            # domain setting is necessary so that the token gets distributed also to the webui server
            domain = '.'.join(urlparse.urlparse(webhome).netloc.split('.')[1:])
            setcookie('x-rucio-auth-token', value=result['token'].token, domain=domain, path='/')
            setcookie('rucio-auth-token-created-at', value=int(time.time()), domain=domain, path='/')
            return seeother(webhome)
        else:
            raise BadRequest()
Esempio n. 15
0
    def POST(self):
        try:
            render = template.render('src/templates/user')
            get_input = input()
            ses = sessionmaker(bind=engine.DBEngine.get_engine());
            s = ses()
            c = s.query(models.User).filter_by(id=int(get_input['id'])).first()
            c.email = get_input['email']
            c.password = get_input['password']
            c.role = int(get_input['role'])
            c.citizen_id = int(get_input['citizen_id'])
            s.commit()
            c = s.query(models.User).order_by(models.User.id)
            return render.list(c)

        except Exception, e:
            render = template.render('src/templates')
            return render.error(err_msg=e)
Esempio n. 16
0
 def GET(self):
     """ GET """
     render = template.render(join(dirname(__file__), 'templates/'))
     data = param_input()
     if hasattr(data, 'account') and data.account:
         account = data.account
     else:
         account = None
     return render.login(account)
Esempio n. 17
0
    def POST(self):
        try:
            get_input = input()
            render = template.render('src/templates/user')
            c = models.User(email=get_input['email'],
                               password=get_input['password'],
                               role=get_input['role'],
                               citizen_id=get_input['citizen_id'])

            ses = sessionmaker(bind=engine.DBEngine.get_engine());
            s = ses();
            s.add(c)
            s.commit()
            c = s.query(models.User).order_by(models.User.id)
            return render.list(c)

        except Exception, e:
            render = template.render('src/templates')
            return render.error(err_msg=e)
Esempio n. 18
0
    def POST(self):
        try:
            get_input = input()
            render = template.render('src/templates/citizen')
            c = models.Citizen(name=get_input['name'],
                               surname=get_input['surname'],
                               birth_date=parser.parse(get_input['birth_date']),
                               pesel=get_input['pesel'])

            ses = sessionmaker(bind=engine.DBEngine.get_engine());
            s = ses();
            s.add(c)
            s.commit()
            c = s.query(models.Citizen).order_by(models.Citizen.id)
            return render.list(c)

        except Exception, e:
            render = template.render('src/templates')
            return render.error(err_msg=e)
Esempio n. 19
0
 def __init__(self, filename=None, glob=None, **keywords):
     """If glob isn't None it will be added to keywords as 'globals'"""
     if filename is not None:
         if glob is not None:
             keywords["globals"] = glob
         #self._tpl = template.frender(os.path.join(templates_dir, filename),
         #                             **keywords)
         self._tpl = getattr(template.render(templates_dir, **keywords),
                             filename)
     self._divs = {}
Esempio n. 20
0
 def GET(self, course_id):
     if course_id.isdigit() and int(course_id) not in session.course_ids:
         return "<h1>ennnnnnn... what's your problem...</a>"
     sql_session = SqliteSession().session
     res = sql_session.query(
         Course.course_name, Course.chapter_id, Course.chapter_name,
         Course.section_id, Course.section_name,
         Course.section_md5).filter(Course.course_id == course_id).order_by(
             Course.chapter_id.asc()).order_by(
                 Course.section_id.asc()).all()
     return render('template').listCourseDetail(res)
Esempio n. 21
0
 def GET(self):
     sql_session = SqliteSession().session
     user_all_course = sql_session.query(distinct(
         UserCourse.course_id)).filter(
             UserCourse.username == session.username).all()
     course_ids = list(map(lambda s: s[0], user_all_course))
     session.course_ids = course_ids
     res = sql_session.query(distinct(Course.course_id),
                             Course.course_name).filter(
                                 Course.course_id.in_(course_ids)).all()
     return render('template').listCourse(res)
Esempio n. 22
0
 def GET(self):
     userdata = webinput(did=0)
     did = userdata.did
     if did == 0 or did == "0":
         return 404
     else:
         c = connect()
         delete_av_info(c, did)
         chdir(path[0] + sep + "avinfo")
         render = template.render("templates/")
         return render.delete()
Esempio n. 23
0
	def GET(self):
		global session
		chdir(path[0]+sep+'index')
		render = template.render('templates/')
		fo = loginform()
		if session == None:
			session = webconfig._session
		if session.login == 0:
         		return render.index(False,fo)
         	elif session.login == 1:
         		return render.index(True,fo)
Esempio n. 24
0
def check_token(rendered_tpl):
    token = None
    js_token = ""
    js_account = ""
    def_account = None
    accounts = None
    cookie_accounts = None
    rucio_ui_version = version.version_string()

    render = template.render(join(dirname(__file__), '../templates'))
    if ctx.env.get('SSL_CLIENT_VERIFY') != 'SUCCESS':
        return render.problem("No certificate provided. Please authenticate with a cerficate registered in Rucio.")

    dn = ctx.env.get('SSL_CLIENT_S_DN')

    # try to get and check the rucio session token from cookie
    session_token = cookies().get('x-rucio-auth-token')
    validate_token = authentication.validate_auth_token(session_token)

    # if there is no session token or if invalid: get a new one.
    if validate_token is None:
        # get all accounts for an identity. Needed for account switcher in UI.
        accounts = identity.list_accounts_for_identity(dn, 'x509')
        cookie_accounts = accounts
        try:
            try:
                # try to get the default account for the identity.
                def_account = identity.get_default_account(dn, 'x509')
            except IdentityError:
                # if there is no default account used the first from the list off accounts.
                def_account = accounts[0]

            token = authentication.get_auth_token_x509(def_account,
                                                       dn,
                                                       'webui',
                                                       ctx.env.get('REMOTE_ADDR'))
        except:
            return render.problem("Your certificate (%s) is not registered in Rucio. Please contact <a href=\"mailto:[email protected]\">Rucio Support</a>" % dn)

        # write the token and account to javascript variables, that will be used in the HTML templates.
        js_token = __to_js('token', token)
        js_account = __to_js('account', def_account)

    # if there was no valid session token write the new token to a cookie.
    if token:
        setcookie('x-rucio-auth-token', value=token, expires=3600, path='/')

    if cookie_accounts:
        values = ""
        for acc in cookie_accounts:
            values += acc + " "
        setcookie('rucio-available-accounts', value=values[:-1], path='/')

    return render.base(js_token, js_account, rucio_ui_version, rendered_tpl)
Esempio n. 25
0
    def POST(self):
        myform = citizen_form()
        try:
            render = template.render('src/templates/citizen')
            get_input = input()
            ses = sessionmaker(bind=engine.DBEngine.get_engine());
            s = ses()
            c = s.query(models.Citizen).filter_by(id=int(get_input['id'])).first()
            c.name = get_input['name']
            c.surname = get_input['surname']
            print get_input['birth_date']
            c.birth_date = parser.parse(get_input['birth_date'])
            c.pesel = int(get_input['pesel'])
            s.commit()
            c = s.query(models.Citizen).order_by(models.Citizen.id)
            return render.list(c)

        except Exception, e:
            render = template.render('src/templates')
            return render.error(err_msg=e)
Esempio n. 26
0
    def GET(self):
        self.holeParser = HoleParser(CSV_PATH)
        self.holeParser.parse()
        render = template.render('pages/')

        #TODO Make the rendering scaling not based on changing the actual raw data
        scale = 10

        canvasWidth = self.holeParser.getEastingDifference()*scale
        canvasHeight = self.holeParser.getNorthingDifference()*scale
        normalizedPointCloud = self.holeParser.normalizePointCloud(self.holeParser.getMinEasting().easting, self.holeParser.getMinNorthing().northing, 0, scale=10)
        borderSize = 40

        return render.index(canvasWidth, canvasHeight, normalizedPointCloud, borderSize)
Esempio n. 27
0
	def POST(self, action):
		data = web.input()
		if action == 'login':
			if data.password == admin_password:
				session.auth = True
				raise web.seeother('/' + session.page)
			return render('templates').login('Password incorrect.')
		web.header('Content-Type', 'text/plain')
		if not session.auth:
			return self.response('Unauthorized.')
		if action == 'save':
			try:
				with open(self.config, 'w') as file:
					for name, value in data.iteritems():
						if value != '':
							file.write('%s: %s\n' % (name, value))
				return self.response('')
			except Exception as e:
				return self.response(e)
		if action == 'start':
			return self.response(self.start())
		if action == 'stop':
			return self.response(self.stop())
		if action == 'restart':
			return self.response(self.stop() or self.start())
		if action == 'poll':
			logs = ''
			end = 0
			if data.get('logs', False):
				start = int(data.get('offset', 0))
				fsize = getsize(self.logpath)
				if start > fsize:
					start = 0 # Logs may have been truncated, start over.
				try:
					if start > 0:
						with open(self.logpath) as file:
							file.seek(start)
							for line in file:
								end = file.tell()
								logs += line
								if len(logs) > 100240:
									break # Send up to 100 KB at a time.
					else:
						logs = check_output(['tail', '-n' '46', self.logpath])
						end = fsize
				except:
					pass # Oh well.
			return self.response(logs=logs, offset=end)
		return self.response('Unrecognized POST action: %s' % action)
Esempio n. 28
0
 def GET(self):  # pylint:disable=no-self-use,invalid-name
     """ GET """
     # get info about x509 or not and decide
     auth_type = cookies().get('x-rucio-auth-type')
     if str(auth_type).lower() == 'x509':
         token = get_token(get_auth_token_x509)
         if token:
             header('X-Rucio-Auth-Token', token)
             return str()
         else:
             raise generate_http_error(401, 'CannotAuthenticate',
                                       'Cannot get token')
     else:
         render = template.render(join(dirname(__file__), 'templates/'))
         return render.select_login_method(AUTH_ISSUERS, SAML_SUPPORT, None)
Esempio n. 29
0
	def POST(self):
		chdir(path[0]+sep+'avinfo')
		render = template.render('templates/')
		f = updata_form();
		if not f.validates():
			return render.updata(f)
		aid = f.id.value
		c = connect()
		avin = query_av_info(c,int(aid)-1,1)
		_,av,title,upid,up,create_time,play_times,collects_count,dans_count,\
		reviews_count,coins_count = avin[0]
		nav,ntitle,nupid,\
		ncreate_time,nplay_times,ncollects_count,\
		ndans_count,nreview_count,ncoin_count = \
		int(f.av.value),f.title.value,int(f.up.value),\
		str(f.create_time.value),int(f.play_times.value),int(f.collects_count.value),\
		int(f.dans_count.value),int(f.reviews_count.value),int(f.coins_count.value)
		updadic = {}
		if nav != av:
			updadic["av"] = nav
		if ntitle != title:
			updadic["title"] = ntitle
		if nupid != upid:
			updadic["up_id"] = nupid
		if ncreate_time != str(create_time):
			updadic['create_stamp'] = ncreate_time
		if nplay_times != play_times:
			updadic["play_times"] = nplay_times
		if ncollects_count != collects_count:
			updadic["collect_times"] = ncollects_count
		if ndans_count != dans_count:
			updadic["dan_count"] = ndans_count
		if nreview_count != reviews_count:
			updadic["review_times"] = nreview_count
		if ncoin_count != coins_count:
			updadic['coins_count'] = ncoin_count
		if len(updadic) == 0:
			f.av.note = "don't change any thing!!"
			return render.updata(f)
		con = connect()
		result = update_av_info(con,updadic,aid)
		if result == 403:
			f.up.note = "该up id不满足约束条件"
			return render.updata(f)
		return render.success('updata')
Esempio n. 30
0
	def POST(self):
		global session
		chdir(path[0]+sep+'index')
		render = template.render('templates/')
		fo = loginform()
		if session == None:session = webconfig._session
		if not fo.validates():
			return render.index(False,fo)
		else:
			name = fo["username"].value
			up = fo["password"].value
			tc = connect()
			dp = query_admin_user_password(tc,name)
			if dp == "":
				fo["username"].note = "username not exist"
				return render.index(False,fo)				
			if md5st(up) != dp:
				fo["password"].note = "Password incorrect"
				return render.index(False,fo)
			session.login = 1
			session.name = fo["username"].value
			# print session.login,session.name
			return render.index(True,fo)
Esempio n. 31
0
	def GET(self):
		user_data = webinput(aid=0)
		aid = user_data.aid
		if aid==0:return 404
		if aid!=0 and not aid.isdigit():return 404
		f = updata_form()
		c = connect()
		avin = query_av_info(c,int(aid)-1,1)
		_,av,title,upid,up,create_time,play_times,collects_count,dans_count,\
		reviews_count,coins_count = avin[0]
		f.id.set_value(_)
		f.av.set_value(av)
		f.title.set_value(title)
		f.up.set_value(upid)
		f.create_time.set_value(create_time)
		f.play_times.set_value(play_times)
		f.collects_count.set_value(collects_count)
		f.dans_count.set_value(dans_count)
		f.reviews_count.set_value(reviews_count)
		f.coins_count.set_value(coins_count)
		chdir(path[0]+sep+'avinfo')
		render = template.render('templates/')
		#totalCounts,pageSize,currentPage
		return render.updata(f)
Esempio n. 32
0
	def GET(self):
		chdir(path[0]+sep+'avinfo')
		render = template.render('templates/')
		f = updata_form()
		#totalCounts,pageSize,currentPage
		return render.insert(f)
Esempio n. 33
0
 def POST(self):
     """ POST """
     render = template.render(join(dirname(__file__), 'templates/'))
     return saml_authentication("POST", render.atlas_index())
Esempio n. 34
0
 def GET(self):  # pylint:disable=no-self-use,invalid-name
     """ GET """
     render = template.render(join(dirname(__file__), 'templates/'))
     return authenticate(render.account())
Esempio n. 35
0
File: browseui.py Progetto: nh/imgc
def print_selection(mindex=[], mkey=[], file_id = None, response_format = "html", sizeX = config.image_preview):
  """prints a browsing page including the selected indexes, the index which are
  still selectable and the result of the current selection as thumbnails"""

  render = template.render('templates/')
  template.Template.globals['HTML'] = HTMLTemplates
  template.Template.globals['config'] = config
  template.Template.globals['uihelper'] = uihelper

  selection = None
  indexes = None
  file_url = None
  
  print mindex
  print mkey

  if file_id:
    #we need to request the filename
    db_file = db.query("select filename from images where id = %s" % file_id)
    if len(db_file) == 1:
      file_path = db_file[0].filename
      file_url = config.web_alias + file_path[len(config.base_dir):]

  #first let's see if anything was choosen
  if mindex:
    #choosing the kind of situation we have to handle
    if len(mindex) == len(mkey):
      #we have the same number of indexes and key so we can print image list
      sel_ik = build_sel_ik(mindex, mkey, len(mkey))
      print "xx_xxxxxx"
      print sel_ik
      #selecting files from the given index values
      #files = indexhelper.select_files (sel_ik)
      files, clustered_files, cluster_pivot = indexhelper.select_clusters_of_files(sel_ik)
      
      if files:
        cache_key = uihelper.build_link(sel_ik)
        #get the index possible values
        index_othervalues = {}
        for index in config.indexes:
          index_othervalues[index] = [i for i in indexhelper.get_values(sel_ik, index)]

        #now also get the selected index possible values without them (changing stuff)

        sel_index_othervalues = {}
        for (index, value) in sel_ik:
          temp_sel_ik = sel_ik[:]
          temp_sel_ik.remove((index,value))
          sel_index_othervalues[index] = len(indexhelper.get_values(temp_sel_ik, index))

      if len(files) == 1 and not file_id:
        #TODO have the redirect be a temporary one, or check how long the browser retain the redirect
        web.found('%s%s/%s%s' % (config.base_url, uihelper.build_link(sel_ik), config.file_url_id, files[0].id))
      else:
        if response_format in config.format_http_header.keys():
          web.header("Content-Type", config.format_http_header[response_format])
        #render.web.render('browse.'+response_format)
        return render.browse(file_url,file_id,sel_ik,sel_index_othervalues,index_othervalues,files,clustered_files,cluster_pivot)

    elif len(mindex)-len(mkey) == 1:
      #there is a different process if len(mindex) and len(mkey) are differents, 
      #it means an index was selected but no key for it we have to print the 
      #keys for which the current selection of indexes/keys has left some images to view
      sel_ik = build_sel_ik(mindex, mkey, len(mkey))
      current_index = mindex[-1]

      index_possible_values = indexhelper.get_values(sel_ik, current_index)
      
      #if for_ajax:
      #  web.render('browsechoosevalue.ajax')
      #else:
      #web.render('browsechoosevalue.'+response_format)
      return render.browsechoosevalue(current_index,index_possible_values,sel_ik)
    else:
      #complaining about the uneven (more than usual at least) numbers of index and keys provided
      print("you have selected %s index but only %s keys where given\
          , stop messing around with things you don't understand please ;)<br/>"\
          % (len(mindex), len(mkey)))

  elif file_url:
    web.render('browse.html')
  else:
    indexes = [idx for idx in config.root_indexes if idx != 'tag'] 
    all_tags = indexhelper.get_values(None, "tag")
    return render.browseroot(all_tags, indexes)
Esempio n. 36
0
File: main.py Progetto: afcarl/rucio
 def GET(self):  # pylint:disable=no-self-use,invalid-name
     """ GET """
     render = template.render(join(dirname(__file__), 'templates/'))
     return check_token(render.bad_replicas_summary())
Esempio n. 37
0
File: main.py Progetto: afcarl/rucio
 def GET(self):  # pylint:disable=no-self-use,invalid-name
     """ GET """
     render = template.render(join(dirname(__file__), 'templates/'))
     return check_token(render.subscriptions_editor())
Esempio n. 38
0
 def GET(self):
     """ GET """
     render = template.render(join(dirname(__file__), 'templates/'))
     return render.login()
Esempio n. 39
0
File: utils.py Progetto: zlion/rucio
def saml_authentication(method, rendered_tpl):
    """
    Login with SAML

    :param method: method type, GET or POST
    :param rendered_tpl: page to be rendered
    """

    attribs = None
    token = None
    js_token = ""
    js_account = ""
    def_account = None
    accounts = None
    cookie_accounts = None
    rucio_ui_version = version.version_string()
    policy = config_get('policy', 'permission')

    # Initialize variables for sending SAML request
    SAML_PATH = join(dirname(__file__), 'saml/')
    request = ctx.env
    data = dict(input())
    req = prepare_webpy_request(request, data)
    auth = OneLogin_Saml2_Auth(req, custom_base_path=SAML_PATH)

    saml_user_data = cookies().get('saml-user-data')

    render = template.render(join(dirname(__file__), '../templates'))

    session_token = cookies().get('x-rucio-auth-token')
    validate_token = authentication.validate_auth_token(session_token)

    if method == "GET":
        # If user data is not present, redirect to IdP for authentication
        if not saml_user_data:
            return seeother(auth.login())

        # If user data is present and token is valid, render the required page
        elif validate_token:
            js_token = __to_js('token', session_token)
            js_account = __to_js('account', def_account)

            return render.base(js_token, js_account, rucio_ui_version, policy,
                               rendered_tpl)

        # If user data is present but token is not valid, create a new one
        saml_nameid = cookies().get('saml-nameid')
        accounts = identity.list_accounts_for_identity(saml_nameid, 'saml')

        cookie_accounts = accounts
        try:
            token = authentication.get_auth_token_saml(
                def_account, saml_nameid, 'webui',
                ctx.env.get('REMOTE_ADDR')).token

        except:
            return render.problem('Cannot get auth token')

        attribs = list_account_attributes(def_account)
        # write the token and account to javascript variables, that will be used in the HTML templates.
        js_token = __to_js('token', token)
        js_account = __to_js('account', def_account)

        set_cookies(token, cookie_accounts, attribs)

        return render.base(js_token, js_account, rucio_ui_version, policy,
                           rendered_tpl)

    # If method is POST, check the received SAML response and redirect to home if valid
    auth.process_response()
    errors = auth.get_errors()
    if not errors:
        if auth.is_authenticated():
            setcookie('saml-user-data', value=auth.get_attributes(), path='/')
            setcookie('saml-session-index',
                      value=auth.get_session_index(),
                      path='/')
            setcookie('saml-nameid', value=auth.get_nameid(), path='/')
            saml_nameid = auth.get_nameid()

            accounts = identity.list_accounts_for_identity(saml_nameid, 'saml')
            cookie_accounts = accounts
            # try to set the default account to the user account, if not available take the first account.
            def_account = accounts[0]
            for account in accounts:
                account_info = get_account_info(account)
                if account_info.account_type == AccountType.USER:
                    def_account = account
                    break

            selected_account = cookies().get('rucio-selected-account')
            if (selected_account):
                def_account = selected_account

            try:
                token = authentication.get_auth_token_saml(
                    def_account, saml_nameid, 'webui',
                    ctx.env.get('REMOTE_ADDR')).token

            except:
                return render.problem('Cannot get auth token')

            attribs = list_account_attributes(def_account)
            # write the token and account to javascript variables, that will be used in the HTML templates.
            js_token = __to_js('token', token)
            js_account = __to_js('account', def_account)

            set_cookies(token, cookie_accounts, attribs)

            return seeother("/")

        return render.problem("Not authenticated")

    return render.problem("Error while processing SAML")
Esempio n. 40
0
File: main.py Progetto: afcarl/rucio
 def GET(self):  # pylint:disable=no-self-use,invalid-name
     """ GET """
     render = template.render(join(dirname(__file__), 'templates/'))
     return check_token(render.approve_rules())
Esempio n. 41
0
    'flash': flash,
    'asset_url': asset_url,
    'auth': auth,
    'config': config,
    'datify': datify,
    'smarty': smarty,
    'to_json': json.dumps,
    'ctx': ctx,
    '_': _,
    'n_': n_,
    'url': web.url,
}


class template_global(object):
    """Registers func for use in templates"""

    def __init__(self, f):
        self.f = template_globals[f.__name__] = f

    def __call__(self, *k, **kw):
        return self.f(*k, **kw)


render_partial = template.render(config.template_dir, globals=template_globals)
render = template.render(config.template_dir, globals=template_globals,
                         base="layout")
render_email = template.render(config.template_dir + "/email",
                               globals=template_globals, base="layout")
template_globals.update(render=render_partial)
Esempio n. 42
0
exts = {
    '.html': html,
    '.csv': csv,
    '.txt': text,
    '.n3': n3,
    '.rdf': rdf,
    '.json': jsonld
}


def strfepoch(epoch, fmt="%Y-%m-%d"):
    return time.strftime(fmt, time.localtime(float(epoch)))


helper = {'time': strfepoch, 'config': config}
render = template.render('templates', globals=helper)


class index:
    def GET(self):
        q = web.input()
        if 'id' in q:
            raise web.seeother("/resolver/%s" % q['id'])
        return render.index()


class resolver:
    def GET(self, raw):
        key, ext = os.path.splitext(raw)
        key = key.replace("urn:uuid:", "")
        key = key.replace("urn:catalog:", "")
Esempio n. 43
0
File: utils.py Progetto: zlion/rucio
def log_in(data, rendered_tpl):
    attribs = None
    token = None
    js_token = ""
    js_account = ""
    def_account = None
    accounts = None
    cookie_accounts = None
    rucio_ui_version = version.version_string()
    policy = config_get('policy', 'permission')

    render = template.render(join(dirname(__file__), '../templates'))

    # # try to get and check the rucio session token from cookie
    session_token = cookies().get('x-rucio-auth-token')
    validate_token = authentication.validate_auth_token(session_token)

    # if token is valid, render the requested page.
    if validate_token and not data:
        token = session_token
        js_token = __to_js('token', token)
        js_account = __to_js('account', def_account)

        return render.base(js_token, js_account, rucio_ui_version, policy,
                           rendered_tpl)

    else:
        # if there is no session token or if invalid: get a new one.
        # if user tries to access a page through URL without logging in, then redirect to login page.
        if rendered_tpl:
            return render.login()

        # get all accounts for an identity. Needed for account switcher in UI.
        accounts = identity.list_accounts_for_identity(data.username,
                                                       'userpass')
        if len(accounts) == 0:
            return render.problem('No accounts for the given identity.')

        cookie_accounts = accounts
        # try to set the default account to the user account, if not available take the first account.
        def_account = accounts[0]
        for account in accounts:
            account_info = get_account_info(account)
            if account_info.account_type == AccountType.USER:
                def_account = account
                break

        selected_account = cookies().get('rucio-selected-account')
        if (selected_account):
            def_account = selected_account

        try:
            token = authentication.get_auth_token_user_pass(
                def_account, data.username, data.password.encode("ascii"),
                'webui', ctx.env.get('REMOTE_ADDR')).token

        except:
            return render.problem('Cannot get auth token')

        attribs = list_account_attributes(def_account)
        # write the token and account to javascript variables, that will be used in the HTML templates.
        js_token = __to_js('token', token)
        js_account = __to_js('account', def_account)

    set_cookies(token, cookie_accounts, attribs)

    return seeother('/')
Esempio n. 44
0
 def GET(self):
     render = template.render('src/templates/citizen')
     myform = citizen_form()
     return render.generic(myform)
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from web import template

render = template.render('app/gtemplator/templates')

class MainHandler(webapp.RequestHandler):
    def get(self,numA,numB):
        self.response.out.write(
          render.index(int(numA),int(numB))["__body__"]
        )

application = webapp.WSGIApplication(
  [(r'/webapptemplator/(.*)/(.*)', MainHandler)],debug=False)

def main():
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()
Esempio n. 46
0
def check_token(rendered_tpl):
    attribs = None
    token = None
    js_token = ""
    js_account = ""
    def_account = None
    accounts = None
    cookie_accounts = None
    rucio_ui_version = version.version_string()

    ui_account = None
    if 'ui_account' in input():
        ui_account = input()['ui_account']

    render = template.render(join(dirname(__file__), '../templates'))
    if ctx.env.get('SSL_CLIENT_VERIFY') != 'SUCCESS':
        return render.problem(
            "No certificate provided. Please authenticate with a certificate registered in Rucio."
        )

    dn = ctx.env.get('SSL_CLIENT_S_DN')

    msg = "Your certificate (%s) is not mapped to any rucio account." % dn
    msg += "<br><br><font color=\"red\">First, please make sure it is correctly registered in <a href=\"https://voms2.cern.ch:8443/voms/atlas\">VOMS</a> and be patient until it has been fully propagated through the system.</font>"
    msg += "<br><br>Then, if it is still not working please contact <a href=\"mailto:[email protected]\">DDM Support</a>."

    # try to get and check the rucio session token from cookie
    session_token = cookies().get('x-rucio-auth-token')
    validate_token = authentication.validate_auth_token(session_token)

    # check if ui_account param is set and if yes, force new token
    if ui_account:
        accounts = identity.list_accounts_for_identity(dn, 'x509')

        if len(accounts) == 0:
            return render.problem(msg)

        if ui_account not in accounts:
            return render.problem(
                "The rucio account (%s) you selected is not mapped to your certificate (%s). Please select another account or none at all to automatically use your default account."
                % (ui_account, dn))

        cookie_accounts = accounts
        if (validate_token is None) or (validate_token['account'] !=
                                        ui_account):
            try:
                token = authentication.get_auth_token_x509(
                    ui_account, dn, 'webui', ctx.env.get('REMOTE_ADDR'))
            except:
                return render.problem(msg)

        attribs = list_account_attributes(ui_account)
        js_token = __to_js('token', token)
        js_account = __to_js('account', def_account)
    else:
        # if there is no session token or if invalid: get a new one.
        if validate_token is None:
            # get all accounts for an identity. Needed for account switcher in UI.
            accounts = identity.list_accounts_for_identity(dn, 'x509')
            if len(accounts) == 0:
                return render.problem(msg)

            cookie_accounts = accounts

            # try to set the default account to the user account, if not available take the first account.
            def_account = accounts[0]
            for account in accounts:
                account_info = get_account_info(account)
                if account_info.account_type == AccountType.USER:
                    def_account = account
                    break

            selected_account = cookies().get('rucio-selected-account')
            if (selected_account):
                def_account = selected_account
            try:
                token = authentication.get_auth_token_x509(
                    def_account, dn, 'webui', ctx.env.get('REMOTE_ADDR'))
            except:
                return render.problem(msg)

            attribs = list_account_attributes(def_account)
            # write the token and account to javascript variables, that will be used in the HTML templates.
            js_token = __to_js('token', token)
            js_account = __to_js('account', def_account)

    # if there was no valid session token write the new token to a cookie.
    if token:
        setcookie('x-rucio-auth-token', value=token, path='/')
        setcookie('rucio-auth-token-created-at', value=int(time()), path='/')

    if cookie_accounts:
        values = ""
        for acc in cookie_accounts:
            values += acc + " "
        setcookie('rucio-available-accounts', value=values[:-1], path='/')

    if attribs:
        setcookie('rucio-account-attr', value=dumps(attribs), path='/')

    if ui_account:
        setcookie('rucio-selected-account', value=ui_account, path='/')
    return render.base(js_token, js_account, rucio_ui_version, rendered_tpl)
Esempio n. 47
0
    else:
        self._setcookie(self.session_id, expires=-1)


web.session.Session._save = toughcookie

app = web.application(urls, locals())
session = web.session.Session(
    app, web.session.DiskStore(config.get('sessions', 'sessions')))

simplerender = template.render('templates',
                               globals={
                                   '_': _,
                                   'prefix': prefix,
                                   'json': json,
                                   'helper': helpers(),
                                   'web': web,
                                   'config': config,
                                   'crumbs': crumbs,
                                   'version': VERSION
                               })

render = template.render('templates',
                         base='layout',
                         globals={
                             '_': _,
                             'prefix': prefix,
                             'json': json,
                             'helper': helpers(),
                             'web': web,
                             'config': config,
Esempio n. 48
0
 def GET(self):
     render = template.render(join(dirname(__file__), 'templates/'))
     return check_token(render.rse_usage())
Esempio n. 49
0
import web
from web import template
from tests import tests_model
from build import Build

urls = (
    '/testcase/(RGraph|Treemap|Icicle|Hypertree|Spacetree|ForceDirected|ForceDirected3D|Sunburst|AreaChart|BarChart|PieChart|TimeGraph|HeatMap|Voronoi|Other)/([0-9]+)/?',
    'testcase',
)

app = web.application(urls, globals())

render = {
    'TestCases': template.render('Templates/'),
}


class testcase:
    def GET(self, type, number):
        number_int = int(number)
        max = len(tests_model[type])
        if number_int > max:
            return "Wrong test number"

        name = type
        test = 'test' + number + '.js'

        model = tests_model[type][number_int - 1]
        title = model['Title']
        extras = model['Extras'][:]
Esempio n. 50
0
def sql(sql_talk):
    try:
        row = cursor.execute(sql_talk)
        db.commit()
    except:
        db.rollback()


import sys

reload(sys)
sys.setdefaultencoding('utf-8')
type = sys.getfilesystemencoding()

db = database(dbn='mysql', db='website', user='******', pw='123456')
render = template.render('templates')
'''
class Help:
    def GET(self):
        return render.help()
'''


class News:
    def GET(self, id):
        print id
        all_news = db.select('news', order='id DESC')
        return render.index(all_news)
        # return u'访问深度边缘的用户ID是:'+id

Esempio n. 51
0
#Translator
translator = Translator(mediaproxy.workingpath,mediaproxy.config.get('main','language'))
_ = translator.translate

def pathencode(path):
    return pathname2url(path.encode('utf-8'))
#Render

template_globals = {}
template_globals['_'] = _
template_globals['path2url'] = pathencode

serverpath = os.path.dirname(os.path.realpath(__file__))

if mediaproxy.setup_check():
    render = Templator_Wrapper(template.render(os.path.join(serverpath,'template'),base='base',globals=template_globals))
else:
    render = Templator_Wrapper(template.render(os.path.join(serverpath,'template'),globals=template_globals))

def format_exception(exc):
    exc_string = ''.join(exc)
    exc_string = exc_string.decode(locale_enc)
    exc_string = exc_string.encode('ascii', 'xmlcharrefreplace')
    exc_string = exc_string.replace('\n','<br>')
    return exc_string

@route('/')
def root():
    if not mediaproxy.setup_check():
        redirect("/setup_language")
    redirect("/channels/")
Esempio n. 52
0
escapefunc = None
try:
    import html
    escapefunc = html.escape
except ImportError:
    import cgi
    escapefunc = cgi.escape

try:
    from onelogin.saml2.auth import OneLogin_Saml2_Auth
    SAML_SUPPORT = True
except:
    SAML_SUPPORT = False

RENDERER = template.render(join(dirname(__file__), '../templates'))
# check if there is preferred server side config for webui authentication
AUTH_TYPE = config_get('webui', 'auth_type', False, None)
if AUTH_TYPE == 'oidc':
    try:
        AUTH_ISSUER_WEBUI = config_get('webui', 'auth_issuer')
    except:
        RENDERER.problem(
            "Please specify auth_issuer in the [webui] section of the Rucio configuration."
        )

# if no specific config on the server side - we collect information
# about all authentication options, in particular OIDC
AUTH_ISSUERS = []
if not AUTH_TYPE:
    IDPSECRETS = config_get('oidc', 'idpsecrets', False, None)
Esempio n. 53
0
import web
from web import template
from tests import tests_model
from build import Build

urls = (
    '/testcase/(EventTunnel|RGraph|Treemap|Icicle|Hypertree|Spacetree|ForceDirected|ForceDirected3D|Sunburst|AreaChart|BarChart|PieChart|TimeGraph|HeatMap|Other)/([0-9]+)/?', 'testcase',
)

app = web.application(urls, globals())

render = {
    'TestCases': template.render('Templates/'),
}

class testcase:
    def GET(self, type, number):
        number_int = int(number)
        max = len(tests_model[type])
        if number_int > max:
            return "Wrong test number"
        
        name = type
        test = 'test' + number + '.js'
                
        model = tests_model[type][number_int -1]
        title = model['Title']
        extras = model['Extras'][:]
        
        if 'Build' in model: build_config = model['Build']
        else: build_config = [type]
Esempio n. 54
0
# little hack so that debug mode works with sessions
if config.get('_session') is None:
    store = session.DiskStore('sessions')
    session = session.Session(app,
                              store,
                              initializer={
                                  'room': None,
                                  'login': 0,
                                  'help_user': 0
                              })
    config._session = session
else:
    session = config._session

render = template.render('templates/',
                         base="layout",
                         globals={'session': session})


class Index(object):
    def GET(self):
        if not logged():
            seeother("/login")
        else:
            # this is used to 'setup' the session with starting values
            session.room = map.START
            seeother("/game")


class Register(object):
    def GET(self):
Esempio n. 55
0
File: main.py Progetto: afcarl/rucio
 def GET(self):  # pylint:disable=no-self-use,invalid-name
     """ GET """
     render = template.render(join(dirname(__file__), 'templates/'))
     return check_token(render.list_lifetime_exceptions())
Esempio n. 56
0
 def GET(self):
     render = template.render(join(dirname(__file__), 'templates/'))
     return check_token(render.accounting())
Esempio n. 57
0
File: main.py Progetto: afcarl/rucio
 def GET(self):  # pylint:disable=no-self-use,invalid-name
     """ GET """
     render = template.render(join(dirname(__file__), 'templates/'))
     return check_token(render.account_rse_usage())
Esempio n. 58
0
 def GET(self):
     render = template.render(join(dirname(__file__), 'templates/'))
     return check_token(render.subscriptionrules())
Esempio n. 59
0
File: index.py Progetto: shrsv/koko
from web import form, template, internalerror, debugerror, application
import tagger

render = template.render('templates/')

urls = (
    '/', 'index'
)

app = application(urls, globals())

myform = form.Form(
    form.Textarea('paragraph'),
)

class index:
    def GET(self):
        form = myform()
        return render.index(form)

    def POST(self):
        form = myform()
        if not form.validates():
            return render.index(form)
        else:
            para = form["paragraph"].value;
            tags = tagger.tagger(para)

            # Set maximum number of tags
            max_tags = 12
            if len(tags) > max_tags:
Esempio n. 60
0
 def GET(self):
     render = template.render(join(dirname(__file__), 'templates/'))
     return check_token(render.infrastructure())