예제 #1
0
파일: app.py 프로젝트: xltank/pytest
def checkToken():
    un = web.cookies().get('userName')
    tk = web.cookies().get('token')
    if(un and tk and ses):
        if(un == ses.userName and tk == ses.token):
            return True
    raise web.seeother('/login')
예제 #2
0
파일: urls.py 프로젝트: sdamashek/webvirt
 def GET(self):
     cookies = web.cookies()
     if cookies.get("session") == None:
         web.seeother("http://www.tjhsst.edu/hackathon/login")
     templates = web.template.render('webvirt/templates/')
     myform = web.form.Form( 
         web.form.Textbox("name",web.form.notnull,description="Name of Virtual Machine: ",align='left'),
         web.form.Textbox("mem",web.form.notnull,web.form.regexp('\d+', 'Must be a digit'),description="Amount of Memory (in KiB): ",align='left'),
         web.form.Textbox("cpu",web.form.notnull,web.form.regexp('\d+', 'Must be a digit'),description="Number of Virtual Processors: ",align='left'),
         web.form.Textbox("hd",web.form.notnull,description='Full Path to hard drive file: ',align='left'),
         web.form.Textbox("iso",web.form.notnull,description="Full Path to cdrom iso file (e.x /var/hackfiles/gentoo.iso): ",align='left'),
         web.form.Textbox("vnc",web.form.notnull,description="VNC Port Number: ",align='left'),
         web.form.Textbox("pts",web.form.notnull,web.form.regexp('\d+', 'Must be a digit'),description="PTS number for serial console: ",align='left')
     )
     form = myform()
     data = ""
     content = "<h2>Create a New VM</h2>"
     for dom in conn.listAllDomains(0):
         dom = virt.Domain(dom)
         if(dom.rawstate == libvirt.VIR_DOMAIN_RUNNING):
             data += "<li><a href='/hackathon/vm?vm=" + dom.name + "'>" + dom.name + "<div class='pull-right'><span class='label label-success'>" + dom.state + "</span></div></a></li>"
         elif(dom.rawstate == libvirt.VIR_DOMAIN_SHUTOFF):
             data += "<li><a href='/hackathon/vm?vm=" + dom.name + "'>" + dom.name + "<div class='pull-right'><span class='label label-important'>" + dom.state + "</span></div></a></li>"
         else:
             data += "<li><a href='/hackathon/vm?vm=" + dom.name + "'>" + dom.name + "<div class='pull-right'><span class='label label-warning'>" + dom.state + "</span></div></a></li>"
     return templates.create(content, data,form,web.cookies().get("session"))
예제 #3
0
    def POST(self):
        i = web.input()
        
        board_list = [u'校外教育', u'远程办公', u'智慧之门', u'美容美体', u'情感天地',
                      u'健康管理', u'娱乐人生', u'家政辅导', u'购物天堂', u'职业生涯',
                      u'社区服务',u'公共信息']
        
        board_id = board_list.index(i.board_id) + 1
        x = web.input(upload_pic={})
        f = None
        if 'upload_pic' in x:
            f = x['upload_pic'].value
            # upload a file
        headers2 = {
            'X-Token': web.cookies().get('token')
        }
        upload_res = requests.post(conf.locate('/attachments/upload'),
                                   data=f,
                                   headers=headers2)
        uuid = simplejson.loads(upload_res.text)
        uuid = uuid['id']
        payload = {
            'introduction': i.introduction
        }
        headers = {
            'X-Token': web.cookies().get('token'),
            'Content-Type': 'application/json'
        }
        res = requests.post(conf.locate('/pin/create/%s/%s' % (board_id, uuid)),
                            data=simplejson.dumps(payload),
                            headers=headers)

        return web.seeother('/controlskip/%s' % board_id)
예제 #4
0
def auth_processor(handler):
    path = web.ctx.path
    method = web.ctx.method
    if path == '/auth' and (method == 'POST' or method == 'GET'):
        return handler()
    else:
        name = web.cookies().get('user_name')
        passwd = web.cookies().get('user_passwd')

        if not name or not passwd:
            raise RestfulError('570 cookies auth error')

        # Note:
        # 1. switch system model for develop or release, must auth 'admin' user,
        #     'user' user has no permission.
        # 2. shutdown or reboot the mechine, must auth the user, only 'admin' can do.
        if path in ['/system/shutdown', '/system/reboot'] \
            or (path == '/system/startup-mode' and method == 'PUT'):
            # check user is 'admin'
            if name != 'admin':
                raise RestfulError("580 Auth Error: No permission, only admin can do this!")


        # filter chinese and other characters
        # rule = re.compile("^[\w-]+$")
        # if not rule.match(name) or not rule.match(passwd):
        #     raise RestfulError('570 name or passwd just support [0-9a-zA-Z_-] characters')

        ret = auth_user(name, passwd)
        if ret:
            return handler()
        else:
            raise RestfulError('570 auth failed')
예제 #5
0
    def GET(self):
        res = requests.get(conf.locate('/user/%s/profile' % web.cookies().get('key')))
        present_user = simplejson.loads(res.text)
        res = requests.get(conf.locate('/pin/user/%s' % web.cookies().get('key')))
        present_user_pin = simplejson.loads(res.text)
        pins = [[], [], [], []]
        for i, p in enumerate(present_user_pin['pins']):
            print "111111111222222"
            print p
            if p['type'] == 'movie':
                res = requests.get(conf.locate('/user/%s/profile' % p['author_id']))
                profile = simplejson.loads(res.text)
                i %= 4
                pin_obj = Pin(p, profile, present_user)
                pins[i].append(pin_obj.render_video())
            elif p['type'] == 'picture':
                res = requests.get(conf.locate('/user/%s/profile' % p['author_id']))
                profile = simplejson.loads(res.text)
                print profile
                i %= 4
                pin_obj = Pin(p, profile, present_user)
                pins[i].append(pin_obj.render())

        headers = {
            'X-Token': web.cookies().get('token')
        }

        res = requests.get(conf.locate('/following/%s' % web.cookies().get('key')), headers=headers)
        result = simplejson.loads(res.text)
        attentions = []
        for attention in result:
            attentions.append(str(pure_render.attention_list(attention)))
        attentions_len=len(attentions)
        
        return render.usermessage(pins, present_user, attentions,attentions_len)
예제 #6
0
 def GET(self):
   
   rdio, currentUser = get_rdio_and_current_user()
   
   if rdio and currentUser:
     user_id = int(currentUser['key'][1:])
     
     myPlaylists = rdio.call('getPlaylists')['result']['owned']
     
     db = get_db()
     
     result = list(db.select('discoversong_user', what='address, playlist', where="rdio_user_id=%i" % user_id))
     if len(result) == 0:
       access_token = web.cookies().get('at')
       access_token_secret = web.cookies().get('ats')
       db.insert('discoversong_user', rdio_user_id=user_id, address=make_unique_email(currentUser), token=access_token, secret=access_token_secret, playlist='new')
       result = list(db.select('discoversong_user', what='address, playlist', where="rdio_user_id=%i" % user_id))[0]
     else:
       result = result[0]
     
     message = ''
     if 'saved' in get_input():
       message = '  Saved your selections.'
     
     return render.loggedin(name=currentUser['firstName'],
                            message=message,
                            to_address=result['address'],
                            editform=editform(myPlaylists, result['playlist'])
                           )
   else:
     return render.loggedout()
예제 #7
0
 def POST(self):
         my_login = login_form()
         if my_login.validates():
                 email = my_login['username'].value
                 password = my_login['password'].value
                 session_creation = CreateSession()
                 session_creation.session_hook()
                 print "INSIDE LOGIN PRINTING SESSION"
                 session_creation.add_hook()
                 print "THIS IS WHERE THE COOKIE SHOULD BE CREATED AND CALLED: "
                 print web.cookies()
                 result = handle_user(email, password, "login")
                 if (result == False):
                         print "something unexpected has occured"
                         my_login['username'].note = "Invalid Username/Password Combination"
                         return render.login(my_login)
                 else:
                         print "THIS MEANS YOU GOT VALIDATED BABY!(LOGIN)"
                         return render.myCitations([citation("Johnson v. Johnson", "Johnson v Johnson, 2008 SCC 9 at para 289, [2008] 1 SCR 190, Binnie J.", "4 Feb 2013", "Canadian Case")])
         else:
                 print "didn't validate baby! (LOGIN)"
                 print "note", my_signup['username'].note
                 print my_signup['username'].value
                 print my_signup['password'].value
                 if ((my_signup['username'].value == "") or (my_signup['username'].value == None)):
                         my_login['username'].note = "Please enter a valid username"
                         return render.login(my_login)
                 elif((my_signup['password'].value == "") or (my_signup['password'].value == None)):
                         my_login['password'].note = "Please enter a valid password"
                         return render.login(my_login)
                 else:
                         return render.login()
예제 #8
0
 def GET(self):
     try: 
         posts=db.posts
         query=posts.find({"user":web.cookies().user})
         usuario1 = query[0]["user"]
         password1 = query[0]["password"]
         nombre1 = query[0]["nombre"]
         apellidos1 = query[0]["apellidos"]
         correo1 = query[0]["correo"]
         dia1 = query[0]["dia"]
         mes1 = query[0]["mes"]
         anio1 = query[0]["anio"]
         direccion1 = query[0]["direccion"]
         pago1 = query[0]["pago"]
         visa1 = query[0]["visa"]
         res="Bienvenido usuario: %s " % (usuario1)
         web.setcookie('pagina3', web.cookies().pagina2)
         web.setcookie('pagina2', web.cookies().pagina1)
         web.setcookie('pagina1', "ver_perfil")
         web.header('Content-Type', 'text/html; charset=utf-8')
         return plantillas.datos_perfil(formulario=res, mensaje="", usuario = usuario1, password = password1, nombre= nombre1, apellidos=apellidos1, correo=correo1, dia=dia1, mes=mes1, anio=anio1, direccion=direccion1, pago=pago1, visa=visa1)
     except:
         l=form_log()
         web.header('Content-Type', 'text/html; charset=utf-8')
         return plantillas.pagina_desconectado(formulario=l.render(), mensaje="Se ha producido algun error. Inicie sesion de nuevo.")
예제 #9
0
파일: page.py 프로젝트: JoonyLi/zbox_wiki
def get_view_settings(config_agent, simple = False):
    theme_name = config_agent.config.get("frontend", "theme_name")

    c_fp = config_agent.config.get("frontend", "show_full_path")
    show_full_path = int(web.cookies().get("zw_show_full_path", c_fp))

    c_toc = config_agent.config.getboolean("frontend", "auto_toc")
    auto_toc = int(web.cookies().get("zw_auto_toc", c_toc))

    c_hc = config_agent.config.get("frontend", "highlight_code")
    highlight_code = int(web.cookies().get("zw_highlight", c_hc))

    reader_mode = config_agent.config.getboolean("frontend", "reader_mode")

    show_quick_links = config_agent.config.getboolean("frontend", "show_quick_links")
    show_home_link = config_agent.config.getboolean("frontend", "show_home_link")

    button_mode_path = config_agent.config.getboolean("frontend", "button_mode_path")
    show_toolbox = True
    show_view_source_button = config_agent.config.getboolean("frontend", "show_view_source_button")

    if simple:
        auto_toc = False
        reader_mode = False
        highlight_code = False

    settings = dict(theme_name = theme_name,
                    show_full_path = show_full_path,
                    auto_toc = auto_toc, highlight_code = highlight_code, reader_mode = reader_mode,
                    show_quick_links = show_quick_links, show_home_link = show_home_link,
                    button_mode_path = button_mode_path,
                    show_toolbox = show_toolbox,
                    show_view_source_button = show_view_source_button)
    return settings
예제 #10
0
def check_login_state():
    """
    If current user has logined in,
    return True,
    otherwise return False
    """
    username = web.cookies().get('user_name')
    if not username:
        return False

    logged_in = web.cookies().get('logged_in')
    if not logged_in:
        return False

    client_info = get_client_info()
    server_session = userstate.get_session()
    #server_ip = userstate.get_session('ip')
    #server_agent = userstate.get_session('agent')
    server_ip = server_session.ip
    server_agent = server_session.agent

    if not server_ip == client_info['ip']:
        return False

    if not server_agent == client_info['agent']:
        return False

    return True
예제 #11
0
    def POST(self):
        i = web.input()
        print "1111111."
        print i.board_id
        boardlist = ['education', 'remotworking', 'intelligence', 'beauty', 'emotion', 'health_management',
                     'entertainment', 'Domestic_counseling', 'shopping', 'career', 'community_services',
                     'public_information']

        board_id = boardlist.index(i.board_id) + 1
        # buffer
        x = web.input(upload_pic={})
        f = None
        if 'upload_pic' in x:
            f = x['upload_pic'].value
            # upload a file
        headers2 = {
            'X-Token': web.cookies().get('token')
        }
        upload_res = requests.post(conf.locate('/attachments/upload'),
                                   data=f,
                                   headers=headers2)
        uuid = simplejson.loads(upload_res.text)
        uuid = uuid['id']
        payload = {
            'introduction': i.introduction
        }
        headers = {
            'X-Token': web.cookies().get('token'),
            'Content-Type': 'application/json'
        }
        res = requests.post(conf.locate('/pin/create/%s/%s' % (board_id, uuid)),
                            data=simplejson.dumps(payload),
                            headers=headers)

        return web.seeother('/controlskip/%s' % board_id)
예제 #12
0
파일: dnspod.py 프로젝트: EugeneLiu/dnspod
 def GET(self,domain):
     domainId = processData.domainInfo(
                                     web.cookies().email,
                                     web.cookies().password,
                                     domain=domain
                                     )#获取域名ID
     
     recordList = processData.recordList(
                                     web.cookies().email,
                                     web.cookies().password,
                                     id=domainId
                                     )#获取记录列表
     fileHead = '主机|类型|线路|记录值|MX优先级|TTL'#导出文件的头部
     s = ''
     s += fileHead + '\n'
     for i in recordList:
         s += i['name'].encode() + '\t'
         s += str(i['type']) + '\t'
         s += i['line'].encode('utf-8') + '\t'
         s += str(i['value']) + '\t'
         s += str(i['mx']) + '\t'
         s += str(i['ttl']) + '\n'
     web.header('Content-Type','static/txt')
     web.header('Content-Disposition',"attachment;filename="+domain+".txt")
     return s
예제 #13
0
def loadcookie():
    try:
        id_, passwd = web.cookies().id_, web.cookies().passwd
    except AttributeError:
        pass
    else:
        authenticate(id_=id_, passwd=passwd)
예제 #14
0
    def GET(self):
        try:
            posts=db.posts
            query=posts.find({"user":web.cookies().user})
            form_reg_editar = form.Form(
                form.Textbox('nombre', form.notnull, form.regexp('^[A-Z, a-z]', 'No hay nadie en el mundo cuyo nombre tenga números.¡Use letras!'), description="Nombre", value=query[0]["nombre"]),
                form.Textbox('apellidos', form.notnull, form.regexp('^[A-Z, a-z]', 'No hay nadie en el mundo cuyo apellido tenga números.¡Use letras!'), description="Apellido", value=query[0]["apellidos"]),
                form.Textbox('correo', form.notnull,  form.regexp('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$', 'Introduzca un correo válido'), description="Correo electrónico", value=query[0]["correo"]),

                form.Dropdown('dias', dias, description="Dia", value=int(query[0]["dia"])),
                form.Dropdown('meses', meses, description="Mes", value=int(query[0]["mes"])),
                form.Dropdown('anios', anios, description="Anio", value=int(query[0]["anio"])),

                form.Textarea('direccion', form.notnull,  description="Dirección", value=query[0]["direccion"]),
                form.Password('clave', form.notnull, description="Contraseña", value=query[0]["password"]),
                form.Password('clave2', form.notnull, description="Repetir contraseña", value=query[0]["password"]),
                form.Radio('pago', ['Contra reembolso', 'Tarjeta VISA'], description="Forma de pago", value=query[0]["pago"]),
                form.Textbox('visa', form.regexp('((\d{4})[\-,\s](\d{4})[\-,\s](\d{4})[\-,\s](\d{4}))', 'Introduzca un número de tarjeta VISA válido'), description="Tarjeta VISA", value=query[0]["visa"]),
                form.Button('Editar'),
                validators = [form.Validator("Fecha de nacimiento no válida.", lambda i: (((int(i.meses) == 2) and  ((int(i.dias) <= 28) and ((int(i.anios) % 4) != 0) or (int(i.dias) <= 29) and ((int(i.anios) % 4) == 0))) or ((int(i.dias) <= 31) and ((int(i.meses) == 1) or (int(i.meses) == 3) or (int(i.meses) == 5) or (int(i.meses) == 7) or (int(i.meses) == 8) or (int(i.meses) == 10) or (int(i.meses) == 12))) or ((int(i.dias) <= 30) and ((int(i.meses) == 4) or (int(i.meses) == 6) or (int(i.meses) == 9) or (int(i.meses) == 11))))), form.Validator("Las contraseñas no coinciden.", lambda i: i.clave == i.clave2),  form.Validator('Míninmo 7 caracteres', lambda x:len(x.clave)>=7), form.Validator('Míninmo 7 caracteres', lambda x:len(x.clave2)>=7)]
            )
            res="Bienvenido usuario: %s " % (web.cookies().user)
            web.setcookie('pagina3', web.cookies().pagina2)
            web.setcookie('pagina2', web.cookies().pagina1)
            web.setcookie('pagina1', "editar_perfil")
            web.header('Content-Type', 'text/html; charset=utf-8')
            return plantillas.editar_perfil(formulario=res, registro=form_reg_editar.render())
        except:
            l=form_log()
            web.header('Content-Type', 'text/html; charset=utf-8')
            return plantillas.pagina_desconectado(formulario=l.render(), mensaje="Se ha producido algun error. Inicie sesion de nuevo.")
예제 #15
0
파일: auth.py 프로젝트: blankyin/sports
	def POST(self):
		data = web.input()

		username = data.get('username','')
		password = data.get('password','')
		remember = data.get('remember', '')

		if not username or not password:
			error_msg = u"用户名或密码不能为空!"
			return render.render('auth/login', username=username, error_msg=error_msg)
		else:
			password = hash_password(password)

			if not self.checkUser(username, password):
				error_msg = u'用户名或密码错误!'
				return render.render('auth/login', username=username, error_msg=error_msg)
			else:
				web.ctx.session.login = 1
				web.ctx.session.username = username

				# 记住密码一周
				if remember == 'on':
					expires = 7 * 24 * 60 * 60
					web.setcookie("username", username, expires)
					web.setcookie("password", password, expires)
				else:
					# 如果没有选择记住密码,清除cookie
					if web.cookies().get('username'):
						web.setcookie("username", username, -1)
					if web.cookies().get('password'):
						web.setcookie("password", password, -1)

				return web.seeother("/")
예제 #16
0
  def GET(self):
    access_token = web.cookies().get('at')
    access_token_secret = web.cookies().get('ats')
    if access_token and access_token_secret:
      rdio = Rdio((RDIO_CONSUMER_KEY, RDIO_CONSUMER_SECRET),
        (access_token, access_token_secret))
      # make sure that we can make an authenticated call

      try:
        currentUser = rdio.call('currentUser')['result']
      except urllib2.HTTPError:
        # this almost certainly means that authentication has been revoked for the app. log out.
        raise web.seeother('/logout')

      myPlaylists = rdio.call('getPlaylists')['result']['owned']

      response = '''
      <html><head><title>Rdio-Simple Example</title></head><body>
      <p>%s's playlists:</p>
      <ul>
      ''' % currentUser['firstName']
      for playlist in myPlaylists:
        response += '''<li><a href="%(shortUrl)s">%(name)s</a></li>''' % playlist
      response += '''</ul><a href="/logout">Log out of Rdio</a></body></html>'''
      return response
    else:
      return '''
예제 #17
0
파일: views.py 프로젝트: hellolibo/pyblog
    def GET(self, f_year):
        query = web.input(curpage=1)
        curpage = query.curpage

        list_title = u"%s年" % (f_year)
        list_description = list_title
        list_keywords = list_title
        articles = (
            session.query(Article)
            .filter("date_format(addTime,'%Y') = '" + f_year + "'")
            .order_by(Article.addTime.desc())
        )

        offset = (curpage - 1) * config.COMMENT_PAGE_LEN
        p = divmod(articles.count(), config.COMMENT_PAGE_LEN)
        if p[1] > 0:
            pagecount = p[0] + 1
        else:
            pagecount = 1
        articles = articles.limit(config.COMMENT_PAGE_LEN).offset(offset).all()
        pages = util.pages(
            pagecount, curpage, 10, "&".join("%s=%s" % (a, b) for a, b in query.items() if a != "curpage") + "#comment"
        )
        cookie = {
            "author": web.cookies(author="").author,
            "email": web.cookies(email="").email,
            "weburl": web.cookies(weburl="").weburl,
        }
        return render_blog.article_list(locals(), self)
예제 #18
0
파일: views.py 프로젝트: hellolibo/pyblog
 def GET(self, slug):
     query = web.input(curpage=1)
     curpage = query.curpage
     if slug:
         article = session.query(Article).filter(Article.slug == slug).first()
         comments = article.comments
         offset = (curpage - 1) * config.COMMENT_PAGE_LEN
         p = divmod(len(comments), config.COMMENT_PAGE_LEN)
         if p[1] > 0:
             pagecount = p[0] + 1
         else:
             pagecount = 1
         comments = comments[offset : offset + config.COMMENT_PAGE_LEN - 1]
         pages = util.pages(
             pagecount,
             curpage,
             10,
             "&".join("%s=%s" % (a, b) for a, b in query.items() if a != "curpage") + "#comment",
         )
         cookie = {
             "author": web.cookies(author="").author,
             "email": web.cookies(email="").email,
             "weburl": web.cookies(weburl="").weburl,
         }
         return render_blog.article_detail(locals(), self)
     else:
         return web.notfound("not found the page")
예제 #19
0
파일: config.py 프로젝트: lujinda/pylot
 def __init__(self):
     try:
         username=web.cookies().user
         password=web.cookies().pwd
         self.uid=get_isLoginOk(username,password)
     except:
         raise web.seeother("/login")
예제 #20
0
파일: netfpga.py 프로젝트: BillWSY/netfpga
	def POST(self):
		web.header("Content-Type","text/html; charset=utf-8")
		content = ""
		if check_sid(web.cookies().get('sid')):
			connrtn = conn()
			if (connrtn == None):
				try:
					num = int(web.input().get('val', None))
				except:
					content += "Invalid input, assuming 0\n"
					num = 0
				buf = send_recv(47 * '0')
				if (buf[43] == '1'): #input request
					res = "Input request #" + str(str_to_num(buf[38:42])) + " : " + str(num)
					buf = num_to_str(num) + 10 * '0' + '010'; #set in_ack
					send_recv(buf)
					buf = num_to_str(num) + 10 * '0' + '000'; #clr in_ack
					send_recv(buf)
					io_history = open('interaction.txt', 'a')
					io_history.write(res + "\n")
					io_history.close()
				sock.close()
				raise web.seeother('/interaction')
			else:
				content += connrtn
		else:
			content += "Serving other user.\nACCESS DENIED.\n"
		return render.interaction(get_status(), check_sid(web.cookies().get('sid')), content, False, False, '')
예제 #21
0
파일: dnspod.py 프로젝트: EugeneLiu/dnspod
 def POST(self,balabala):
     domainId = processData.domainInfo(
                                     web.cookies().email,
                                     web.cookies().password,
                                     domain=domain_g
                                     )#获取域名ID
     x = web.input(myfile={})
     count = 0
     k = 0
     for line in x['myfile'].file:
         line = line.split('\t')
         count += 1
         if count == 1 or line[3] == 'f1g1ns1.dnspod.net.' or line[3] == 'f1g1ns2.dnspod.net.':
             k += 1   
             continue
         message = processData.addRecord(
                                     web.cookies().email,#邮箱
                                     web.cookies().password,#密码
                                     domain_id=domainId,#域名ID
                                     sub_domain = line[0],#主机记录        
                                     record_type = line[1],#记录类型
                                     route_line = line[2],#线路类型
                                     value = line[3],#记录值
                                     mx = line[4],#MX值
                                     ttl = line[5][:-1]#TTL
                                     )        
     count -= k
     return render.upload(domain_g,msg='成功导入'+str(count)+'条记录,请点击左上角的域名进行查看!')
예제 #22
0
파일: auth.py 프로젝트: olin/ldap-auth-2012
def clear_session():
	key = web.cookies().get('olin-auth-key')
	username = web.cookies().get('olin-auth-username')
	if key != None and username != None and verify_username(key, username):
		clear_keys(username)
	set_auth_cookie('olin-auth-key', "", 60*60*24*30)
	set_auth_cookie('olin-auth-username', "", 60*60*24*30)
예제 #23
0
파일: rdio.py 프로젝트: eae/discoversong
def get_rdio_with_access(access_token, access_token_secret):
  if access_token == NOT_SPECIFIED:
    access_token = web.cookies().get('at')
  if access_token_secret == NOT_SPECIFIED:
    access_token_secret = web.cookies().get('ats')
  logging.error("Making Rdio %s %s %s %s" % (config.RDIO_CONSUMER_KEY, config.RDIO_CONSUMER_SECRET, access_token, access_token_secret))
  return Rdio((config.RDIO_CONSUMER_KEY, config.RDIO_CONSUMER_SECRET), (access_token, access_token_secret))
예제 #24
0
파일: rdio.py 프로젝트: eae/discoversong
def get_rdio_and_current_user(access_token=NOT_SPECIFIED, access_token_secret=NOT_SPECIFIED, request=True):

  if access_token and access_token_secret:
    try:
      rdio = get_rdio_with_access(access_token, access_token_secret)
      logging.error('got rdio %s' % rdio)
      # make sure that we can make an authenticated call
      currentUser = rdio.call('currentUser', {'extras': 'username'})['result']
      rdio_user_id = int(currentUser['key'][1:])
      if access_token == NOT_SPECIFIED and access_token_secret == NOT_SPECIFIED:
        access_token = web.cookies().get('at')
        access_token_secret = web.cookies().get('ats')
        db = get_db()
        db.update(USER_TABLE, where="rdio_user_id=%i" % rdio_user_id, token=access_token, secret=access_token_secret)
        logging.info('updated token and secret for user')
    except urllib2.HTTPError as ex:
      logging.exception(ex.message)
      # this almost certainly means that authentication has been revoked for the app. log out.
      if request:
        raise web.seeother('/logout')
      else:
        logging.error('could not get rdio with token and secret %s %s and cannot log out because not a web call' % (access_token, access_token_secret))
        return None, None, None
    except Exception as ex2:
      logging.exception(ex2.message)
      return None, None, None
    return rdio, currentUser, int(currentUser['key'][1:])
  else:
    return None, None, None
예제 #25
0
파일: rdio.py 프로젝트: eae/discoversong
def get_discoversong_user(user_id):
  assert user_id is not None
  db = get_db()

  disco_user = list(db.select(USER_TABLE, where="rdio_user_id=%i" % user_id))
  
  if len(disco_user) == 0:
    access_token = web.cookies().get('at')
    access_token_secret = web.cookies().get('ats')
    
    db.insert(USER_TABLE,
      rdio_user_id=user_id,
      address=make_unique_email(),
      token=access_token,
      secret=access_token_secret,
      first_use=datetime.date.today(),
      last_use=datetime.date.today(),
      emails=0,
      searches=0,
      songs=0,
      prefs=BSONPostgresSerializer.from_dict({}))
    
    disco_user = list(db.select(USER_TABLE, where="rdio_user_id=%i" % user_id))[0]
    count = int(list(db.query("SELECT count(*) from %s" % USER_TABLE))[0]['count'])
    announce_new_user(count)
    
  else:
    disco_user = disco_user[0]
    
    def none_or_empty(strg):
      return strg is None or strg == ''
    
    def fields_need_update(field_names):
      for field in field_names:
        if not disco_user.has_key(field):
          return True
        if none_or_empty(disco_user[field]):
          return True
      return False
    
    if fields_need_update(['token', 'secret', 'address', 'prefs']):
      
      if fields_need_update(['token', 'secret']):
        access_token = web.cookies().get('at')
        access_token_secret = web.cookies().get('ats')
        db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, secret=access_token_secret, token=access_token)
      if fields_need_update(['address']):
        db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, address=make_unique_email())
      if fields_need_update(['prefs']):
        db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, prefs=BSONPostgresSerializer.from_dict({}))
      
      disco_user = list(db.select(USER_TABLE, where="rdio_user_id=%i" % user_id))[0]
  
  if not disco_user.has_key('prefs') or not disco_user['prefs']:
    logging.info('resetting preferences')
    db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, prefs=BSONPostgresSerializer.from_dict({}))
    disco_user = list(db.select(USER_TABLE, where="rdio_user_id=%i" % user_id))[0]

  return disco_user, BSONPostgresSerializer.to_dict(disco_user['prefs'])
예제 #26
0
파일: search.py 프로젝트: lujinda/pylot
 def getIsLogin(self):
     try:
         username=web.cookies().user
         password=web.cookies().pwd
         self.uid=get_isLoginOk(username,password)
         return True
     except:
         return False
예제 #27
0
 def GET(self):
     """
     A simple function that reads the client cookies and renders a simple HTML template with the data.
     This is used in spadmin.html template in the header bar.
     """
     token = web.cookies().get("token")
     tenant_id = web.cookies().get("tenant_id")
     return render_auth.logininfo(token, tenant_id)
예제 #28
0
 def GET(self):
     web.setcookie('user', web.cookies().user, -3600)
     web.setcookie('pagina1', web.cookies().pagina1, -3600)
     web.setcookie('pagina2', web.cookies().pagina2, -3600)
     web.setcookie('pagina3', web.cookies().pagina3, -3600)
     l=form_log()
     web.header('Content-Type', 'text/html; charset=utf-8')
     return plantillas.pagina_desconectado(formulario=l.render(), mensaje="")
예제 #29
0
파일: index.py 프로젝트: nighelles/editr
def logged_in_as():
    username = web.cookies().get('username')
    sessionkey = web.cookies().get('session')
    if (username is None) or (sessionkey is None):
        return None
    if (check_session_key(username, sessionkey)):
        return username
    return None
예제 #30
0
	def checkAuth(self):
		token=web.cookies().get("token")
		user=web.cookies().get("user")
		if self.db.verify_user(user,token):
			return True
		else:
			print "please login"
			return False
예제 #31
0
    def execute(self):
        #开始执行部署变更
        logger.info(u"Trying to start deployment at cluster '{0}'".format(
            self.cluster.name or self.cluster.id))
        #显示网络信息(openstack部署前执行网络验证)
        network_info = self.serialize_network_cfg(self.cluster)
        logger.info(u"Network info:\n{0}".format(
            jsonutils.dumps(network_info, indent=4)))

        self._remove_obsolete_tasks()  #obsolete 过时的

        supertask = Task(name=TASK_NAMES.deploy, cluster=self.cluster)
        db().add(supertask)

        nodes_to_delete = TaskHelper.nodes_to_delete(self.cluster)
        nodes_to_deploy = TaskHelper.nodes_to_deploy(self.cluster)
        nodes_to_provision = TaskHelper.nodes_to_provision(self.cluster)

        task_messages = []
        #如果是openstack环境,就执行原来流程判断看集群中是否有节点的变化
        if self.cluster.cluster_type == 1:
            if not any([nodes_to_provision, nodes_to_deploy, nodes_to_delete]):
                db().rollback()
                raise errors.WrongNodeStatus("No changes to deploy")

        # we should have task committed for processing in other threads
        db().commit()
        TaskHelper.create_action_log(supertask)

        # Run validation if user didn't redefine
        # provisioning and deployment information

        if (not objects.Cluster.get_provisioning_info(self.cluster)
                and not objects.Cluster.get_deployment_info(self.cluster)):
            try:
                if self.cluster.cluster_type == 1:
                    self.check_before_deployment(supertask)
            except errors.CheckBeforeDeploymentError:
                db().commit()
                return supertask

        task_deletion, task_provision, task_deployment = None, None, None

        if nodes_to_delete:
            objects.TaskCollection.lock_cluster_tasks(self.cluster.id)
            # For more accurate progress calculation
            task_weight = 0.4
            task_deletion = supertask.create_subtask(TASK_NAMES.node_deletion,
                                                     weight=task_weight)
            logger.debug("Launching deletion task: %s", task_deletion.uuid)

            self._call_silently(task_deletion, tasks.DeletionTask)
            # we should have task committed for processing in other threads
            db().commit()

        if nodes_to_provision:
            objects.TaskCollection.lock_cluster_tasks(self.cluster.id)
            # updating nodes
            nodes_to_provision = objects.NodeCollection.lock_nodes(
                nodes_to_provision)
            objects.NodeCollection.update_slave_nodes_fqdn(nodes_to_provision)
            logger.debug("There are nodes to provision: %s",
                         " ".join([n.fqdn for n in nodes_to_provision]))

            # For more accurate progress calulation
            task_weight = 0.4
            task_provision = supertask.create_subtask(TASK_NAMES.provision,
                                                      weight=task_weight)

            # we should have task committed for processing in other threads
            db().commit()
            provision_message = self._call_silently(task_provision,
                                                    tasks.ProvisionTask,
                                                    nodes_to_provision,
                                                    method_name='message')

            task_provision = objects.Task.get_by_uid(task_provision.id,
                                                     fail_if_not_found=True,
                                                     lock_for_update=True)
            # if failed to generate task message for orchestrator
            # then task is already set to error
            if task_provision.status == TASK_STATUSES.error:
                return supertask

            task_provision.cache = provision_message
            db().commit()
            task_messages.append(provision_message)
        else:
            pass

        #nodes_to_deploy=self.cluster.nodes
        if nodes_to_deploy:
            objects.TaskCollection.lock_cluster_tasks(self.cluster.id)
            # locking nodes before updating
            objects.NodeCollection.lock_nodes(nodes_to_deploy)
            # updating nodes
            objects.NodeCollection.update_slave_nodes_fqdn(nodes_to_deploy)
            logger.debug("There are nodes to deploy: %s",
                         " ".join([n.fqdn for n in nodes_to_deploy]))
            task_deployment = supertask.create_subtask(TASK_NAMES.deployment)

            # we should have task committed for processing in other threads
            db().commit()
            deployment_message = self._call_silently(task_deployment,
                                                     tasks.DeploymentTask,
                                                     nodes_to_deploy,
                                                     method_name='message')

            # clusterdeploymsg = ClusterdeployMsg(cluster_id=self.cluster.id,cluster_deploymsg='deployment_message')
            # db().add(clusterdeploymsg)
            logger.info(u'执行部署变更,开始操作cluster_deploy_msg表')
            data = {}
            data['cluster_id'] = self.cluster.id
            data['cluster_deploymsg'] = jsonutils.dumps(deployment_message)
            clusterdeploymsg = db().query(ClusterdeployMsg).filter_by(
                cluster_id=self.cluster.id).first()

            if clusterdeploymsg:
                objects.ClusterdeployMsgObject.update(
                    clusterdeploymsg,
                    {'cluster_deploymsg': data['cluster_deploymsg']})
            else:
                objects.ClusterdeployMsgCollection.create(data)

            task_deployment = objects.Task.get_by_uid(task_deployment.id,
                                                      fail_if_not_found=True,
                                                      lock_for_update=True)
            # if failed to generate task message for orchestrator
            # then task is already set to error
            if task_deployment.status == TASK_STATUSES.error:
                return supertask

            task_deployment.cache = deployment_message
            db().commit()
            task_messages.append(deployment_message)
        else:
            pass
        if len(nodes_to_delete) <= 0 and len(nodes_to_deploy) <= 0:
            #这里不能单纯用nodes_to_deploy是否为空来判断是启动或者停止
            #因为nodes_to_delete不为空而nodes_to_deploy为空的话依然会
            #执行下面的代码,此种情况程序会出现异常
            logger.info(u'这里执行的是启动或者停止部署')
            task_deployment = supertask.create_subtask(TASK_NAMES.deployment)

            # we should have task committed for processing in other threads
            # openstack定制化环境点击部署变更和启动,停止按钮没有执行
            # 此程序,而是直接通过调用/opt/start.py执行
            # 目前只有cloudmaster和ebs环境会执行此处代码
            db().commit()
            deployment_message = self.get_task_deploy_msg()
            deploymsg = jsonutils.loads(deployment_message)
            deploymsg['args']['task_uuid'] = task_deployment.uuid
            #deployment_info[]是列表,这个列表中含有的元素都是字典
            #角色下面的label参数就只是在此处添加和修改的.
            deployment_info_list = deploymsg['args']['deployment_info']
            oprolename = web.cookies().get("oprolename")
            opaction = web.cookies().get("opaction")

            #此处删除和启动停止无关的角色信息
            for deployment_info in deployment_info_list:
                if deployment_info["role"] == oprolename:
                    deploymsg['args']['deployment_info'] = []
                    deploymsg['args']['deployment_info'].append(
                        deployment_info)

            for deployment_info in deployment_info_list:  #此处是一个列表
                deployment_info_keys = deployment_info.keys()
                changelable_keys = []
                operationalrole = ""
                for key in deployment_info_keys:
                    if key.lower() == oprolename.lower():
                        operationalrole = key
                    else:
                        changelable_keys.append(key)

                deployment_info[operationalrole]['action'] = opaction
                deployment_info[operationalrole]['label'] = '0'
                for key in changelable_keys:
                    if type(
                            deployment_info[key]
                    ) == dict and deployment_info[key].get('label') != None:
                        deployment_info[key]['label'] = '1'

            logger.info(deployment_info[operationalrole]['action'])
            logger.info(oprolename)

            task_deployment = objects.Task.get_by_uid(task_deployment.id,
                                                      fail_if_not_found=True,
                                                      lock_for_update=True)
            # if failed to generate task message for orchestrator
            # then task is already set to error
            if task_deployment.status == TASK_STATUSES.error:
                return supertask

            task_deployment.cache = deploymsg
            db().commit()
            task_messages.append(deploymsg)

        if nodes_to_provision:
            nodes_to_provision = objects.NodeCollection.lock_nodes(
                nodes_to_provision)
            for node in nodes_to_provision:
                node.status = NODE_STATUSES.provisioning
            db().commit()

        objects.Cluster.get_by_uid(self.cluster.id,
                                   fail_if_not_found=True,
                                   lock_for_update=True)
        self.cluster.status = CLUSTER_STATUSES.deployment
        db().add(self.cluster)
        db().commit()

        if task_messages:
            rpc.cast('naily', task_messages)

        logger.debug(u"Deployment: task to deploy cluster '{0}' is {1}".format(
            self.cluster.name or self.cluster.id, supertask.uuid))
        return supertask
예제 #32
0
 def GET(self):  # pylint:disable=no-self-use,invalid-name
     """ GET """
     session_token = cookies().get('x-rucio-auth-token')
     return finalize_auth(session_token, 'OIDC')
예제 #33
0
파일: utils.py 프로젝트: 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('/')
예제 #34
0
def login_return(user_id):
    sessionid = generate_sessionid(user_id)
    web.setcookie('sessionid', sessionid, path='/')
    cookie_redirect_url = web.cookies().get('current_page')
    redirect_url = cookie_redirect_url if cookie_redirect_url else '/auction/item/56a0dc0d35e9d494bcb25b69'
    raise web.redirect(redirect_url)
예제 #35
0
 def GET(self):
     username = web.cookies().get('name')
     print username
     return render.welcome(username)
예제 #36
0
    def GET(self):
        """
        HTTP Success:
            200 OK

        HTTP Error:
            401 Unauthorized

        :param Rucio-VO: VO name as a string (Multi-VO only)
        :param Rucio-Account: Account identifier as a string.
        :param Rucio-Username: Username as a string.
        :param Rucio-Password: Password as a string.
        :param Rucio-AppID: Application identifier as a string.
        :returns: "X-Rucio-SAML-Auth-URL" 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('Access-Control-Expose-Headers', 'X-Rucio-Auth-Token')

        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')

        if not EXTRA_MODULES['onelogin']:
            header('X-Rucio-Auth-Token', None)
            return "SAML not configured on the server side."

        saml_nameid = cookies().get('saml-nameid')
        vo = ctx.env.get('HTTP_X_RUCIO_VO', 'def')
        account = ctx.env.get('HTTP_X_RUCIO_ACCOUNT')
        appid = ctx.env.get('HTTP_X_RUCIO_APPID')
        if appid is None:
            appid = 'unknown'
        ip = ctx.env.get('HTTP_X_FORWARDED_FOR')
        if ip is None:
            ip = ctx.ip

        if saml_nameid:
            try:
                result = get_auth_token_saml(account,
                                             saml_nameid,
                                             appid,
                                             ip,
                                             vo=vo)
            except AccessDenied:
                raise generate_http_error(
                    401, 'CannotAuthenticate',
                    'Cannot authenticate to account %(account)s with given credentials'
                    % locals())
            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, 'CannotAuthenticate',
                    'Cannot authenticate to account %(account)s with given credentials'
                    % locals())

            header('X-Rucio-Auth-Token', result.token)
            header('X-Rucio-Auth-Token-Expires',
                   date_to_str(result.expired_at))
            return str()

        # Path to the SAML config folder
        SAML_PATH = config_get('saml', 'config_path')

        request = ctx.env
        data = dict(param_input())
        req = prepare_saml_request(request, data)
        auth = OneLogin_Saml2_Auth(req, custom_base_path=SAML_PATH)

        header('X-Rucio-SAML-Auth-URL', auth.login())
        return str()
예제 #37
0
 def GET(self):
     return ",".join(sorted(web.cookies().keys()))
예제 #38
0
  def GET(self):

    #if
    hd = ''
    #if profile = json.loads( web.cookies().get('_profile'))

    #raise web.seeother('/logout')
    #profile = json.loads( web.cookies().get('_profile'))

    if web.cookies().get('_id'):
      
      
      profile = json.loads( web.cookies().get('_profile'))
      
      email = profile['email']
      picture = profile['picture']
      try:
        
      #hd = profile['hd']
         hd = profile['hd']
      except KeyError:
         pass
         web.setcookie('_id', '', 0)
         raise web.seeother('/logout')
      
      
      
      if hd == 'utectulancingo.edu.mx' or 'utec-tgo.edu.mx':
     
     
            verifica = config.model_alumnos.validate_alumno(email)
            if verifica:
                #grupo=config.model_alumnos.validate_id(email)
                #raise config.web.seeother('/alumno/index_alumno')
                
                app.session.loggedin = True
                app.session.user = email
                app.session.privilege = 4
                app.session.picture = picture
                app.session.grupo = ''
                raise config.web.seeother('/alumnos/index_alumno')




                

                ip = web.ctx['ip']
                res = config.model_logs.insert_logs(config.check_secure_val(email), ip)
                #raise web.seeother('/logout')
                now = datetime.datetime.now()
                future = now + datetime.timedelta(minutes = app.expires)
                future_str = str(future).split('.')[0]
                app.session.expires = config.make_secure_val(future_str)

            #ip = web.ctx['ip']

            #config.model_logs.insert_logs(check['user'], ip)
          

            if verifica==None:
                #message = email + ": User not found"
                #app.session.loggedin = True
                #app.session.user = email
                #app.session.privilege = 3
                #app.session.picture = None
                #raise web.seeother('/ingresoclave')
                check = config.model_users.validate_user_google(email)
                if check:
                    app.session.loggedin = True
                    app.session.user = check['user']
                    app.session.privilege = check['privilege']

                    if check['privilege'] == 0:
                       user = app.session.user 
                       privilege = app.session.privilege 
                       params = {}
                       params['user']= user
                       params['privilege']= privilege
                       return config.render.admin(params)
                       #raise config.web.seeother('/admin')

                    if check['privilege'] == 1:
                       user = app.session.user 
                       privilege = app.session.privilege 
                       params = {}
                       params['user']= user
                       params['privilege']= privilege
                       return config.render.admin(params)

                    if check['privilege'] == 2:
                       user = app.session.user 
                       privilege = app.session.privilege 
                       params = {}
                       params['user']= user
                       params['privilege']= privilege
                       return config.render.admin(params)
                     

              
                if check == None:
                    message = email + ": User not found"
                    app.session.loggedin = True
                    app.session.user = email
                    app.session.privilege = 3
                    app.session.picture = None
                    raise web.seeother('/ingresoclave')



            else:
                message = email + ": User not found"
                app.session.loggedin = True
                app.session.user = email
                app.session.privilege = 3
                app.session.picture = None
                raise web.seeother('/ingresoclave')

      if hd == '':
          checks = config.model_users.validate_user_google(email)
          if checks:
              app.session.loggedin = True
              app.session.user = check['user']
              app.session.privilege = check['privilege']

              if checks['privilege'] == 0:
                 user = app.session.user 
                 privilege = app.session.privilege 
                 params = {}
                 params['user']= user
                 params['privilege']= privilege
                 return config.render.admin(params)
                 #raise config.web.seeother('/admin')

              if checks['privilege'] == 1:
                 user = app.session.user 
                 privilege = app.session.privilege 
                 params = {}
                 params['user']= user
                 params['privilege']= privilege
                 return config.render.admin(params)

              if checks['privilege'] == 2:
                 user = app.session.user 
                 privilege = app.session.privilege 
                 params = {}
                 params['user']= user
                 params['privilege']= privilege
                 return config.render.admin(params)
                    
          if checks == None:
             web.setcookie('_id', '', 0)
             raise web.seeother('/logout')
             raise config.web.seeother('/index')#redireccion al index

    else:
      
      #raise web.seeother('/auth/google')
      raise web.seeother('/auth/google')
예제 #39
0
 def is_printdisabled(self):
     return web.cookies().get('pd')
예제 #40
0
파일: i18n.py 프로젝트: purhan/infogami
 def parse_lang_cookie():
     """Parses HTTP_LANG cookie."""
     # Quick check to avoid making cookies call
     if "HTTP_LANG" in web.ctx.get("HTTP_COOKIE", ""):
         cookies = web.cookies()
         return cookies.get('HTTP_LANG')
예제 #41
0
 def GET(self):
     id = web.cookies().get('id')
     name = web.cookies().get('name')
     return render.userinfo(name)
예제 #42
0
 def GET(self):
     if web.cookies().get("userid") == None:
         web.debug("need to set User ID")
         addNewUser()
     return render.form()
예제 #43
0
    def get_cookie_time(self):
        cookies = web.cookies()

        if self.cookie_name in cookies:
            return self.parse_datetime(cookies[self.cookie_name])
예제 #44
0
    def GET(self):
        global Access_token

        #Wechat transfer the data to the server
        dataFromWeXin = web.input()
        logging.info("WeXin Send = |%s|" % dataFromWeXin)

        userid = ''
        username = ''
        position = ''
        stateOC = ''
        department = ''
        if (dataFromWeXin.get('code')):
            code = dataFromWeXin.code
            page = 'menu'
            if (dataFromWeXin.state == 'close'):
                stateOC = 'close'
            else:
                if (dataFromWeXin.state == 'open'):
                    stateOC = 'open'
                else:
                    workflowdata = workflow.get(
                        workflow.id == dataFromWeXin.state)
                    page = 'url'
                    stateOC = workflowdata.state
            web.setcookie('stateOC', stateOC, holdtime)
            url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=' \
                  + Access_token + '&code=' + code + '&agentid=0'

            logging.info("We Send URL= |%s|" % url)

            resp = urllib2.urlopen(url)
            result = json.loads(resp.read())

            logging.info('WeXin Response = |%s|' % result)
            if (result.has_key('UserId')):
                userid = result['UserId']
                url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=' \
                              + Access_token + '&userid=' + userid
                resp = urllib2.urlopen(url)
                result = json.loads(resp.read())

                logging.info("We send URL = |%s|" % url)
                logging.info("WeXin response = |%s|" % result)

                username = result['name']

                if (result.has_key('position')):
                    position = result['position']
                else:
                    position = ''

                if (result.has_key('department')):
                    department = result['department']
                else:
                    department = ''
                web.setcookie('userid', userid, holdtime)
                web.setcookie('username', username, holdtime)
                web.setcookie('position', position, holdtime)
                web.setcookie('department', set(department), holdtime)

        if (userid.strip() == ''):
            cookies = web.cookies()
            if (cookies.get('userid')):
                userid = cookies.userid
                username = cookies.username
                position = cookies.position
                department = cookies.department
                stateOC = cookies.stateOC
            else:
                return render.closepage()
        newlist = set([])
        oldlist = set([])
        url = 'https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=' + Access_token + '&department_id=1&fetch_child=1&status=0'
        resp = urllib2.urlopen(url)
        result = json.loads(resp.read())
        for userinf in result['userlist']:
            newlist.add(userinf['userid'])
        for userinf in userlist().select(userlist.userid):
            oldlist.add(userinf.userid)
        for user in newlist:
            if (user not in oldlist):
                logging.info("add employeeList = |%s|" % user)
                employeeList = userlist()
                employeeList.userid = user
                employeeList.list = ''
                employeeList.looker = ''
                employeeList.remark = ''
                employeeList.save()
        employeeList = userlist.get(userlist.userid == userid)
        logging.info(
            "userID = |%s|,userName = |%s| ,position = |%s|,department = |%s|,stateOC = |%s|"
            % (userid, username, position, department, stateOC))
        if (position == '领导'):
            for departmentid in department:
                try:
                    departmentList = userlist.get(
                        userlist.userid == departmentid)
                    if (not departmentList.list.strip() == ''):
                        logging.info("department=|%s|,list=|%s|" %
                                     (departmentid, departmentList.list))
                        list = departmentList.list.split(';')
                        for id in list:
                            employeeList.list = AddList(employeeList.list, id)
                    logging.info(
                        "after add department's list,userID=|%s|,list=|%s|" %
                        (userid, employeeList.list))
                    employeeList.save()
                except DoesNotExist:
                    departmentList = userlist()
                    departmentList.userid = departmentid
                    departmentList.list = ''
                    departmentList.looker = ''
                    departmentList.remark = ''
                    departmentList.save()
        if (page == 'menu'):
            if (stateOC == 'close'):
                return render.checkcloseflow(LoadWFdetails(userid, stateOC))
            else:
                return render.checkworkflow(LoadWFdetails(userid, stateOC))
        else:
            userlistdata = userlist.get(userlist.userid == userid)
            if (str(workflowdata.id) not in set(userlistdata.list.split(';'))):
                return render.closepage()
            if (stateOC == 'close'):
                return render.closeflowdetail(
                    LoadWFTdetails(workflowdata.id, userid, username, stateOC),
                    workflowdata.flowname)
            else:
                if (workflowdata.userid == userid):
                    hidden = 'btn-danger'
                else:
                    hidden = 'hidden'
                return render.workflowdetail(
                    LoadWFTdetails(workflowdata.id, userid, username,
                                   stateOC), workflowdata.id,
                    workflowdata.flowname, hidden, workflowdata.state,
                    Clostwf(workflowdata.id))
예제 #45
0
def export(config=None, base_dir=None, quiet=False, files_only=False):

    log_handler = configure_logging(logging.WARN if quiet else logging.INFO,
                                    log_path=os.path.abspath(
                                        os.path.join(base_dir, '.log')))
    try:
        if not config:
            raise BadRequest("No configuration specified.")
        server = dict()
        try:
            # parse host/catalog params
            catalog_config = config["catalog"]
            host = catalog_config["host"]
            if host.startswith("http"):
                url = urlparse(host)
                server["protocol"] = url.scheme
                server["host"] = url.netloc
            else:
                server["protocol"] = "https"
                server["host"] = host
            server["catalog_id"] = catalog_config.get('catalog_id', "1")

            # parse credential params
            token = catalog_config.get("token", None)
            username = catalog_config.get("username", "Anonymous")
            password = catalog_config.get("password", None)

            # sanity-check some bag params
            if "bag" in config:
                if files_only:
                    del config["bag"]
                else:
                    if not config["bag"].get("bag_archiver"):
                        config["bag"]["bag_archiver"] = "zip"

        except (KeyError, AttributeError) as e:
            raise BadRequest('Error parsing configuration: %s' %
                             format_exception(e))

        try:
            auth_token = token if token else web.cookies().get("webauthn")
            credentials = format_credential(token=auth_token,
                                            username=username,
                                            password=password)
        except ValueError as e:
            raise Unauthorized(format_exception(e))

        try:
            identity = get_client_identity()
            user_id = username if not identity else identity.get(
                'display_name', identity.get('id'))
            create_access_descriptor(
                base_dir,
                identity=username if not identity else identity.get('id'))
            wallet = get_client_wallet()
        except (KeyError, AttributeError) as e:
            raise BadRequest(format_exception(e))

        try:
            sys_logger.info("Creating export at [%s] on behalf of user: %s" %
                            (base_dir, user_id))
            downloader = GenericDownloader(server,
                                           output_dir=base_dir,
                                           config=config,
                                           credentials=credentials)
            return downloader.download(identity=identity, wallet=wallet)
        except DerivaDownloadAuthenticationError as e:
            raise Unauthorized(format_exception(e))
        except DerivaDownloadAuthorizationError as e:
            raise Forbidden(format_exception(e))
        except DerivaDownloadConfigurationError as e:
            raise Conflict(format_exception(e))
        except Exception as e:
            raise BadGateway(format_exception(e))

    finally:
        logger.removeHandler(log_handler)
예제 #46
0
    def POST(self):
        cookies = web.cookies()
        logging.info("cookies data: |%r|" % cookies)
        if (cookies.get('userid') and cookies.get('username')
                and cookies.get('stateOC')):
            userid = cookies.userid
            username = cookies.username
            stateOC = cookies.stateOC
        else:
            return render.closepage()

        global Access_token
        i = web.input(data=[])
        logging.info("web.input data: |%r|" % i)
        nowtime = time.strftime('%Y-%m-%d %X', time.localtime(time.time()))
        workflowdata = workflow.get(workflow.id == i.data[3])

        workflowdata.updatetime = nowtime
        workflowdata.save()
        workflowtree._meta.db_table = workflowdata.workflowtreename
        bz = 0
        if (i.data[0] == 'change'):
            workflowtreedataold = workflowtree.get(
                workflowtree.id == i.data[4])
            if (workflowtreedataold.state == '发起'):
                workflowdata.flowdetails = i.data[2]
                workflowdata.flowdate = i.data[1]
                workflowdata.save()
                bz = 1
            workflowtreedataold.state = '失效'
            workflowtreedataold.save()

        workflowtreedata = workflowtree()
        workflowtreedata.subworkflowid = 0
        workflowtreedata.workflowid = i.data[3]
        workflowtreedata.userid = userid
        workflowtreedata.username = username
        workflowtreedata.remark = ''
        workflowtreedata.transmit = ''
        workflowtreedata.writetime = nowtime

        workflowtreedata.date = i.data[1]
        workflowtreedata.details = i.data[2]
        if (bz):
            workflowtreedata.state = '发起'
        else:
            workflowtreedata.state = ''
        k = web.input(option=[])
        addlist = k.option
        newlist = []
        if (i.data[0] == 'change'):
            if (workflowtreedataold.transmit.strip() == ''):
                oldlist = []
            else:
                oldlist = workflowtreedataold.transmit.split(';')

            newlist = list(set(k.option))
            addlist = list(set(newlist).difference(set(oldlist)))
            dellist = list(set(oldlist).difference(set(newlist)))
            for sendee in dellist:
                if (sendee.strip() != ''):
                    workflowdata.looker = DelList(workflowdata.looker,
                                                  sendee.split('-')[0])
                    user = userlist.get(
                        userlist.userid == sendee.split('-')[0])
                    user.list = DelList(user.list, str(i.data[3]))
                    user.looker = DelList(user.looker, str(i.data[3]))
                    user.save()
        for sendee in addlist:
            if (sendee.strip() != ''):
                workflowdata.looker = AddList(workflowdata.looker,
                                              sendee.split('-')[0])
                Transmit(workflowtreedata, sendee, nowtime, userid)
                AddDepartment(sendee.split('-')[0], str(i.data[3]))
        workflowtreedata.transmit = ';'.join(newlist)
        workflowtreedata.save()

        if (not workflowdata.looker.strip() == ''):
            lists = workflowdata.looker.split(';')
            for everyone in lists:
                if (not userid == everyone):
                    content = username + ':项目《' + workflowdata.flowname + '》进展为「' + i.data[
                        2] + '」' + '\n' + workflowdata.tinyurl

                    url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + Access_token + '&debug=1'
                    data = '{\"touser\":\"' + str(
                        everyone
                    ) + '\",\"msgtype\":\"text\",\"agentid\":\"0\",\"text\":{\"content\": \"' + str(
                        content) + '\"},\"safe\":\"0\"}'
                    Post(url, data)
        if (workflowdata.userid == userid):
            hidden = 'btn-danger'
        else:
            hidden = 'hidden'
        return render.workflowdetail(
            LoadWFTdetails(i.data[3], userid, username, stateOC), i.data[3],
            workflowdata.flowname, hidden, workflowdata.state,
            Clostwf(i.data[3]))
예제 #47
0
def get_score():
    return int(web.cookies(score=0).score)
예제 #48
0
def saml_auth(method, data=None):
    """
    Login with SAML
    :param method: method type, GET or POST
    :param data: data object containing account string can be provided
    :param rendered_tpl: page to be rendered
    :returns: rendered final page or a page with error message
    """
    SAML_PATH = join(dirname(__file__), 'saml/')
    req = prepare_saml_request(ctx.env, dict(input()))
    samlauth = OneLogin_Saml2_Auth(req, custom_base_path=SAML_PATH)
    saml_user_data = cookies().get('saml-user-data')
    if not MULTI_VO:
        ui_vo = 'def'
    elif hasattr(data, 'vo') and data.vo:
        ui_vo = data.vo
    else:
        ui_vo = None
    if hasattr(data, 'account') and data.account:
        ui_account = data.account
    else:
        ui_account = None

    if method == "GET":
        # If user data is not present, redirect to IdP for authentication
        if not saml_user_data:
            return seeother(samlauth.login())
        # If user data is present but token is not valid, create a new one
        saml_nameid = cookies().get('saml-nameid')
        if ui_account is None and ui_vo is None:
            ui_account, ui_vo = select_account_name(saml_nameid, 'saml', ui_vo)
        elif ui_account is None:
            ui_account, _ = select_account_name(saml_nameid, 'saml', ui_vo)
        elif ui_vo is None:
            _, ui_vo = select_account_name(saml_nameid, 'saml', ui_vo)

        # Try to eliminate VOs based on the account name (if we have one), if we still have multiple options let the user select one
        if type(ui_vo) is list:
            if ui_account:
                valid_vos = []
                for vo in ui_vo:
                    if account_exists(ui_account, vo):
                        valid_vos.append(vo)
                if len(valid_vos) == 0:
                    return RENDERER.problem((
                        'Cannot find any Rucio account %s associated with identity %s at any VO.'
                        % (html_escape(ui_account), html_escape(saml_nameid))))
                elif len(valid_vos) == 1:
                    ui_vo = valid_vos[0]
                else:
                    vos_with_desc = get_vo_descriptions(valid_vos)
                    return RENDERER.select_login_method(
                        AUTH_ISSUERS, SAML_SUPPORT, vos_with_desc)
            else:
                vos_with_desc = get_vo_descriptions(ui_vo)
                return RENDERER.select_login_method(AUTH_ISSUERS, SAML_SUPPORT,
                                                    vos_with_desc)

        if not ui_account:
            if MULTI_VO:
                msg = 'Cannot get find any account associated with %s identity at VO %s.' % (
                    html_escape(saml_nameid), html_escape(ui_vo))
            else:
                msg = 'Cannot get find any account associated with %s identity.' % (
                    html_escape(saml_nameid))
            if ADDITIONAL_ERROR_MSG:
                msg += ADDITIONAL_ERROR_MSG
            return RENDERER.problem(msg)

        token = get_token(auth.get_auth_token_saml,
                          acc=ui_account,
                          vo=ui_vo,
                          idt=saml_nameid)
        if not token:
            if MULTI_VO:
                msg = 'Cannot get auth token. It is possible that the presented identity %s is not mapped to any Rucio account %s at VO %s.' % (
                    html_escape(saml_nameid), html_escape(ui_account),
                    html_escape(ui_vo))
            else:
                msg = 'Cannot get auth token. It is possible that the presented identity %s is not mapped to any Rucio account %s.' % (
                    html_escape(saml_nameid), html_escape(ui_account))
            if ADDITIONAL_ERROR_MSG:
                msg += ADDITIONAL_ERROR_MSG
            return RENDERER.problem(msg)
        return finalize_auth(token, 'saml')

    # If method is POST, check the received SAML response and redirect to home if valid
    samlauth.process_response()
    errors = samlauth.get_errors()
    if not errors:
        if samlauth.is_authenticated():
            saml_nameid = samlauth.get_nameid()
            cookie_extra = {'saml-nameid': saml_nameid}
            cookie_extra['saml-user-data'] = samlauth.get_attributes()
            cookie_extra['saml-session-index'] = samlauth.get_session_index()
            # WHY THIS ATTEMPTS TO GET A NEW TOKEN ?
            # WE SHOULD HAVE IT/GET IT FROM COOKIE OR DB AND JUST REDIRECT, NO ?
            if ui_account is None and ui_vo is None:
                ui_account, ui_vo = select_account_name(
                    saml_nameid, 'saml', ui_vo)
            elif ui_account is None:
                ui_account, _ = select_account_name(saml_nameid, 'saml', ui_vo)
            elif ui_vo is None:
                _, ui_vo = select_account_name(saml_nameid, 'saml', ui_vo)

            # Try to eliminate VOs based on the account name (if we have one), if we still have multiple options let the user select one
            if type(ui_vo) is list:
                if ui_account:
                    valid_vos = []
                    for vo in ui_vo:
                        if account_exists(ui_account, vo):
                            valid_vos.append(vo)
                    if len(valid_vos) == 0:
                        return RENDERER.problem((
                            'Cannot find any Rucio account %s associated with identity %s at any VO.'
                            % (html_escape(ui_account),
                               html_escape(saml_nameid))))
                    elif len(valid_vos) == 1:
                        ui_vo = valid_vos[0]
                    else:
                        vos_with_desc = get_vo_descriptions(valid_vos)
                        return RENDERER.select_login_method(
                            AUTH_ISSUERS, SAML_SUPPORT, vos_with_desc)
                else:
                    vos_with_desc = get_vo_descriptions(ui_vo)
                    return RENDERER.select_login_method(
                        AUTH_ISSUERS, SAML_SUPPORT, vos_with_desc)

            if not ui_account:
                if MULTI_VO:
                    msg = 'Cannot get find any account associated with %s identity at VO %s.' % (
                        html_escape(saml_nameid), html_escape(ui_vo))
                else:
                    msg = 'Cannot get find any account associated with %s identity.' % (
                        html_escape(saml_nameid))
                if ADDITIONAL_ERROR_MSG:
                    msg += ADDITIONAL_ERROR_MSG
                return RENDERER.problem(msg)
            token = get_token(auth.get_auth_token_saml,
                              acc=ui_account,
                              vo=ui_vo,
                              idt=saml_nameid)
            if not token:
                if MULTI_VO:
                    msg = 'Cannot get auth token. It is possible that the presented identity %s is not mapped to any Rucio account %s at VO %s.' % (
                        html_escape(saml_nameid), html_escape(ui_account),
                        html_escape(ui_vo))
                else:
                    msg = 'Cannot get auth token. It is possible that the presented identity %s is not mapped to any Rucio account %s.' % (
                        html_escape(saml_nameid), html_escape(ui_account))
                if ADDITIONAL_ERROR_MSG:
                    msg += ADDITIONAL_ERROR_MSG
                return RENDERER.problem(msg)
            return finalize_auth(token, 'saml', cookie_extra)

        return RENDERER.problem("Not authenticated")

    return RENDERER.problem("Error while processing SAML")
예제 #49
0
    def POST(self):
        cookies = web.cookies()
        logging.info("cookies data: |%r|" % cookies)
        if (cookies.get('userid') and cookies.get('username')
                and cookies.get('stateOC')):
            userid = cookies.userid
            username = cookies.username
            stateOC = cookies.stateOC
        else:
            return render.closepage()

        i = web.input(data=[])
        logging.info("web.input data: |%r|" % i)
        workflowdata = workflow()
        nowtime = time.strftime('%Y-%m-%d %X', time.localtime(time.time()))
        nowtimetable = time.strftime('%Y%m%d%H%M%S',
                                     time.localtime(time.time()))
        workflowdata.userid = userid
        workflowdata.username = username
        workflowdata.state = 'open'
        workflowdata.flowname = i.data[0]
        workflowdata.flowdate = i.data[1]
        workflowdata.flowdetails = i.data[2]
        workflowdata.updatetime = nowtime
        workflowdata.writetime = nowtime
        workflowdata.looker = AddList('', userid)
        workflowdata.remark = ''
        tablename = str(nowtimetable) + '_' + userid
        workflowdata.workflowtreename = tablename
        workflowdata.fatherid = i.data[3]
        workflowdata.tinyurl = ''
        workflowdata.save()

        workflowid = db.last_insert_id(db.get_cursor(), workflow)
        data = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0af1900070a3ea37&redirect_uri=http%3a%2f%2f120.25.145.20%3a8080%2fsys&response_type=code&scope=snsapi_base&state=' + str(
            workflowid) + '#wechat_redirect'
        data = urllib.urlencode({'url': data})
        url = 'http://dwz.cn/create.php'
        result = Post(url, data)
        logging.info("short url result=|%r|" % result)
        if (result['status'] == 0):
            workflowdata.tinyurl = result['tinyurl']
            logging.info("workflowid=|%r|,short url=|%r|" %
                         (workflowid, workflowdata.tinyurl))
        else:
            workflowdata.tinyurl = ''
            logging.error("workflowid=|%r|,short url=|%r|" %
                          (workflowid, 'NULL'))
        workflowdata.save()
        AddDepartment(userid, str(workflowid))
        userlistdata = userlist.get(userlist.userid == userid)
        userlistdata.list = AddList(userlistdata.list, str(workflowid))
        userlistdata.looker = AddList(userlistdata.looker, str(workflowid))
        userlistdata.save()

        workflowtree._meta.db_table = tablename
        if (not workflowtree.table_exists()):
            workflowtree.create_table()
        workflowtreedata = workflowtree()
        workflowtreedata.date = i.data[1]
        workflowtreedata.userid = userid
        workflowtreedata.username = username
        workflowtreedata.details = i.data[2]
        workflowtreedata.workflowid = workflowid
        workflowtreedata.writetime = nowtime
        workflowtreedata.subworkflowid = 0
        workflowtreedata.remark = ''
        workflowtreedata.transmit = ''
        workflowtreedata.state = '发起'
        workflowtreedata.save()

        if (i.data[3] != '0'):
            fatherworkflow = workflow.get(workflow.id == i.data[3])
            workflowtree._meta.db_table = fatherworkflow.workflowtreename
            detailsWFT = workflowtree()
            detailsWFT.date = i.data[1]
            detailsWFT.userid = userid
            detailsWFT.username = username
            detailsWFT.details = i.data[0]
            detailsWFT.workflowid = i.data[3]
            detailsWFT.transmit = ''
            detailsWFT.writetime = nowtime
            detailsWFT.remark = ''
            detailsWFT.subworkflowid = workflowid
            detailsWFT.state = '子项目'
            detailsWFT.save()

        i = web.input(option=[])
        workflowtreedata.transmit = ';'.join(i.option)
        for option in i.option:
            workflowdata.looker = AddList(workflowdata.looker,
                                          option.split('-')[0])
            Transmit(workflowtreedata, option, nowtime, userid)
            AddDepartment(option.split('-')[0], str(workflowid))
        workflowdata.save()
        workflowtree._meta.db_table = tablename
        workflowtreedata.save()
        return render.checkworkflow(LoadWFdetails(userid, stateOC))
예제 #50
0
    def GET(self):
        #i = config.web.input()
        #def GET(self):
        # check '_id' in the cookie to see if the user already sign in
        if web.cookies().get('_id'):
            # user already sign in, retrieve user profile
            #transformacion de archivo json para leer y obtener perfil de usuario
            profile = json.loads(web.cookies().get('_profile'))
            #Obtencion de valor email del archivo json
            user = profile['email']
            #emision de valor email de archivo json para ver html
            obtencion_email = profile['email'], json.dumps(user)
            #obtenido = json.dumps(email)
            #profiless = profile['email']

            #return """<html><head></head><body>
            # <a href="/logout">Salir de la aplicacion</a><br />
            #Hello <b><i>%s</i></b> Sus Datos son correctos usted registrado en cuenta GMAIL el correo obtenido de su cuenta es el siguiente:<br/>
            #%s<br />
            #</body></html>
            #"""  % (obtencion_email) #impresion en html del correo obtenido

            check = config.model.validate_user(user)
            if check:
                app.session.loggedin = True
                app.session.user = check['user']
                app.session.privilege = check['privilege']
                app.session.picture = picture

                # get time now and N minutes
                now = datetime.datetime.now()
                future = now + datetime.timedelta(minutes=app.expires)
                future_str = str(future).split('.')[0]
                app.session.expires = config.make_secure_val(future_str)

                ip = web.ctx['ip']

                config.model_logs.insert_logs(check['user'], ip)

                params = {}
                params['user'] = app.session.user
                params['privilege'] = app.session.privilege
                params['picture'] = app.session.picture

                if check['privilege'] == 1:
                    return config.render.admin(params)

                # Estado usuario desactivado
                if check['status'] == 0:
                    message = check['user'] + ": User account disabled!!!!"
                    app.session.loggedin = False
                    app.session.user = '******'
                    app.session.privilege = -1  #asignar privilegio solo para pagina de introduccion
                    app.session.picture = None
                    app.session.kill()  #destruir la session de kuorra
                    web.setcookie('_id', '', 0)  #cierre de session en google
                    print message
                    return config.render.login(message)
                else:
                    raise config.web.seeother('/')

            # usuario no registrado
            if check == None:
                message = user + ": User not found"
                app.session.loggedin = False
                app.session.user = '******'
                app.session.privilege = -1  #asignar privilegio solo para pagina de introduccion
                app.session.picture = None
                app.session.kill()  #destruir la session de kuorra
                web.setcookie('_id', '', 0)  #cierre de session en google

                print message
                return config.render.login(message)
                # raise config.web.seeother('/logout')

        else:
            raise web.seeother('/auth/google')
예제 #51
0
 def get_cookie(self):
     return web.cookies().get('open_id')
예제 #52
0
파일: utils.py 프로젝트: zlion/rucio
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()
    policy = config_get('policy', 'permission')

    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')

    if not dn.startswith('/'):
        dn = '/%s' % '/'.join(dn.split(',')[::-1])

    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')).token
            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')).token
            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)

    set_cookies(token, cookie_accounts, attribs, ui_account)

    return render.base(js_token, js_account, rucio_ui_version, policy,
                       rendered_tpl)
예제 #53
0
파일: utils.py 프로젝트: 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")
예제 #54
0
 def GET(self, name):
     web.setcookie('name', name)
     yield 'Hello, ' + name + '!\n'
     yield 'input.name = %s\n' % web.input()["name"]
     yield 'cookie.name = %s\n' % web.cookies()["name"].value
예제 #55
0
 def GET(self):
     uid = web.cookies().get('uid')
     if uid:
         web.setcookie('uid', '', -1)
     return render.index()
예제 #56
0
def getCookieID():
    try:
        return web.cookies().get(cookieID)
    except:
        # Do whatever handling you need to, etc. here.
        return None
 def GET(self):
     vm_env.attachCurrentThread()
     user = web.cookies().get('name')
     user_data = web.input()
     text = user_data.keyword
     return render.text_res(text, user, 0, 0, 0)
 def GET(self):
     user = web.cookies().get('name')
     user_data = web.input()
     index = user_data.index
     return render.recommand(index, user)
예제 #59
0
 def GET(self):
     c = web.cookies(age="25")
     print c
     web.setcookie('age', '19', 3600000)
     return "Age set in your cookie"
예제 #60
0
 def GET(self):
     cookies = web.cookies(tag='unknown')
     return 'welcome, user = {}, privilege = {}, tag = {}'.format(
         session.user, session.privilege, cookies.tag)