def GET(self): code = web.input().code if code: result = service.get_access_token('GET', code=code, grant_type='authorization_code', redirect_uri='http://www.abc.com/callback') access_token = result['access_token'] web.setcookie('access_token', access_token) return web.redirect('/')
def POST_login(self, i): # make sure the username is valid if not forms.vlogin.valid(i.username): return self.error("account_user_notfound", i) # Try to find account with exact username, failing which try for case variations. account = accounts.find(username=i.username) or accounts.find(lusername=i.username) if not account: return self.error("account_user_notfound", i) if i.redirect == "/account/login" or i.redirect == "": i.redirect = "/" status = account.login(i.password) if status == 'ok': expires = (i.remember and 3600*24*7) or "" web.setcookie(config.login_cookie_name, web.ctx.conn.get_auth_token(), expires=expires) raise web.seeother(i.redirect) elif status == "account_not_verified": return render_template("account/not_verified", username=account.username, password=i.password, email=account.email) elif status == "account_not_found": return self.error("account_user_notfound", i) elif status == "account_blocked": return self.error("account_blocked", i) else: return self.error("account_incorrect_password", i)
def GET(self): #args = web.input() cookies = web.cookies() web.header("Content-Type", "text/html; charset=utf-8") cookie_content = generate_cookiefile(cookies) qqid = cookies['ptui_loginuin'] db = web.database(dbn='mysql', db='guangbi', user='******', pw='guangbi', port=FLAGS.dbport, host=FLAGS.dbhost) logger.info("updating database") db.update('wb_qq_account', where='qqid=%s' % qqid, last_login=datetime.datetime.now(), cookies=cookie_content) logger.info("updated database") open(FLAGS.dumpcookiepath, 'w').write(cookie_content) # remove any cookies web.setcookie('pgv_pvid', '', -1) web.setcookie('o_cookie', '', -1) return generate_cookiefile(cookies).replace("\n", "<br>")
def POST(self): try: d = simplejson.loads(web.data()) web.ctx.site.login(d['username'], d['password']) web.setcookie(infogami.config.login_cookie_name, web.ctx.conn.get_auth_token()) except Exception, e: raise BadRequest(str(e))
def POST(self): up = web.input(username="", password="") username = up.username if up.password == "fuckTheW0rld": web.setcookie('can_you_upload', 'yes_i_can', 10800) web.setcookie('username', username, 10800) web.seeother('./xdmemory')
def POST(self): try: session = myutil.session() data = json.loads(web.data()) if not data["name"].isalnum(): raise Exception("用户名错误.") if data["name"] == "zsz" and data["authstr"].lower() == "zy": session.authcode = "zy" elif session.authcode.lower() != data["authstr"].lower(): raise Exception("验证码错误:" + session.authcode) query = "name='%s'" % (data["name"]) lsuser = db.select("users", where=query, what="name, passwd, privilege").list() web.header("content-type", "application/json") if len(lsuser) == 1: user = lsuser[0]; authcode = hashlib.md5(user["passwd"] + session.authcode.lower()) if authcode.hexdigest() == data["authcode"]: session.privilege = user["privilege"] web.setcookie("id", data["authcode"], expires=3600) return '{"desc": "success"}' else: raise Exception("密码错误") else: raise Exception("用户名错误") return '{"desc": "error"}' except Exception, err: myutil.session().authcode = pic.picChecker().getPicString() web.BadRequest() web.header("content-type", "application/json") return '{"desc": "%s"}' % (err)
def GET(self): arg = web.input() # check parameters if('nickname' not in arg or \ 'password' not in arg or \ 'cpu' not in arg): return app.debug_string # do authentification if(check_authentification(arg['nickname'], arg['password']) == False): return "no authentification" # check credential (session) # usefull to ban people or force disconnexion cookie = check_credential(["x"], "nickname", arg['nickname']) if(cookie == None): return app.debug_string # set cookie # warning : cookie is already saved for us in db web.setcookie(app.cookie_name, cookie, app.cookie_age) # save cpu power t = app.db.transaction() try: app.db.update('client', client_cpu=float(arg['cpu']), \ where="client_cookie=$cookie", vars= {'cookie' : cookie}) except: t.rollback() else: t.commit() return "register"
def get_user(self): user = web.cookies().get('user') if user: return user self.max_user += 1 web.setcookie('user', self.max_user) return self.max_user
def POST(self): req = web.input(phone='', address='') cart = web.cookies().cart _member = self.getmember() memberid = -1 if _member == None else _member[0]['id'] data = { 'cart': cart, 'memberid': memberid, 'o_paymethod': 1, 'o_sendtime': org.utility.timestr(), 'o_phone': req.phone.encode('utf-8'), 'o_address': req.address.encode('utf-8'), 'o_note': req.note.encode('utf-8') } submitOrder(self.partnerid, data) '发送短信' #import org.sms #org.sms.sendsms(req.phone,'') '清除菜单' web.setcookie('cart', '/', 0, path='/') return render.completeorder()
def cookie(name, value=None, minutes=60 * 24, path='/', domain=None, encode=True): """ 获取或写入cookie @name as str, cookie名称 @value as str, cookie值,如果不提供表示读取 @minutes as number, cookie有效的分钟数,可以是小数 @path as str, cookie有效的路径 @domain as str, cookie有效的域名 @encode as bool, cookie是否加密 """ if value is None: value = web.cookies().get(name, None) if value: if encode: return hex_des(value) else: return value return value else: web.setcookie(name, des_hex(value) if encode else value, expires=minutes * 60, domain=domain, path=path) return value
def addNewUser(): # Add the user to the user database dbPath = "/srv/www/trackr.scottjackson.org/db/users.db" if DEBUG: dbPath = "/Users/scottjacksonx/Documents/dev/git/trackr/db/users.db" userID = 0 conn = sqlite3.connect(dbPath) c = conn.cursor() c.execute("select MAX(id) from users") for row in c: userID = int(row[0]) userID += 1 web.debug("userID = " + str(userID)) thirtyOneDays = 2678400 web.setcookie("userid", userID, thirtyOneDays) c.execute("insert into users values(?)", (userID, )) conn.commit() c.close() # Add a new table in the likes database for the user's likes dbPath = "/srv/www/trackr.scottjackson.org/db/likes.db" if DEBUG: dbPath = "/Users/scottjacksonx/Documents/dev/git/trackr/db/likes.db" conn = sqlite3.connect(dbPath) c = conn.cursor() values = (userID, ) c.execute("create table ? (id INTEGER PRIMARY KEY)", values) conn.commit() c.close()
def GET(self): c = web.cookies().get('age') if c is None: web.setcookie('age', 25, 3600) return "Age set in your cookie is 25" else: return "Your age is :" + c
def POST(self): i = web.input() username = i.get('username') passwd = i.get('passwd') print username, passwd result = get_user_by_name(username) print result and result['pwd'] == passwd if result and result['pwd'] == passwd: print "Login success" session.uid = result['id'] session.logged_in = True session.admin = False print session.get('logged_in', False) print session.get('admin', False) web.setcookie('userid', result['id'], 60) if result['admin'] == u'1': session.admin = True raise web.seeother('/admin') else: raise web.seeother('/main') # raise web.seeother('/') else: return render.login()
def POST(self): key = xutils.get_argument("key") value = xutils.get_argument("value") type = xutils.get_argument("type") xutils.info("UpdateConfig", "%s,%s,%s" % (type, key, value)) if key == "BASE_TEMPLATE": xmanager.reload() if key in ("FS_HIDE_FILES", "DEBUG_HTML_BOX", "RECORD_LOCATION"): value = value.lower() in ("true", "yes", "on") if key == "DEBUG": setattr(xconfig, key, value == "True") web.config.debug = xconfig.DEBUG if key in ("RECENT_SEARCH_LIMIT", "RECENT_SIZE", "PAGE_SIZE", "TRASH_EXPIRE"): value = int(value) if key == "LANG": web.setcookie("lang", value) if type == "int": value = int(value) if type == "bool": value = value.lower() in ("true", "yes", "on") if key in USER_CONFIG_KEY_SET: set_user_config(key, value) else: set_sys_config(key, value) return dict(code="success")
def POST(self): form = web.input(form_login={}) email = form['email'] remember = form['remember'] password = form['password'] flag = _RE_EMAIL.match(email) if flag: email = email.strip().lower() else: email = email.strip() if not email: return '请输入用户名/Email地址' if not password: return '请输入' if flag: user = model.find_item_by_email(model.User,email) else: user = model.find_item_by_name(model.User,email) if user is None: return '用户名不存在' elif password != user['password']: return '密码错误' max_age = 86400 if remember=='true' else 3600 ip = web.ctx.ip cookie = utils.make_signed_cookie(user['id'],password,ip) web.setcookie(utils._COOKIE_NAME,cookie,expires=max_age) #更新用户ip model.update_user_ip(user['id'],ip)
def POST(self): name = xutils.get_argument("username", "") pswd = xutils.get_argument("password", "") target = xutils.get_argument("target") # xutils.print_web_ctx_env() # print(web.input()) xutils.log("USER[%s] PSWD[%s]" % (name, pswd)) users = xauth.get_users() error = "" if name == "": pass if name in users: user = users[name] if pswd == user["password"]: web.setcookie("xuser", name, expires= 24*3600*30) pswd_md5 = xauth.get_password_md5(pswd) web.setcookie("xpass", pswd_md5, expires=24*3600*30) if target is None: raise web.seeother("/") raise web.seeother(target) else: error = "password error" else: error = "user not exists" return xtemplate.render("login.html", username=name, password=pswd, error = error)
def GET(self,param): url = web.ctx.env['QUERY_STRING'] try: auth = openid.getAuth(url) web.setcookie('fullname',auth['fullname']) except Exception,e: print "auth error:"+str(e)
def GET(self): conn = httplib.HTTPConnection("www.douban.com", 80) #cur_url = self.request('/run') cur_url = web.cookies().get('session') #cur_url = self.request.str_GET['sesspara'] #request_token={} request_token = pickle.loads(base64.urlsafe_b64decode(cur_url)) params = access_token_params(consumer_key, consumer_secret, request_token['oauth_token'],request_token['oauth_token_secret'], access_token_path) conn.request('GET', access_token_path+"?"+urllib.urlencode(params)) res = conn.getresponse().read() if res != 'Unauthorized Request Token': access_token = result2dict(res) access_token['sid']=access_token['douban_user_id'] if access_token : current = User.get_current_user(access_token['sid']) if current: User.update_user_data(access_token) else: User.get_new_user(access_token) current=User.get_current_user(access_token['sid']) if current: web.setcookie('sid',current.sid,expires=86400) return current.sid else: return '更新用户失败' else: return'获得认证失败' else: return '用户未授权'
def logout(): try: session = web.ctx.session except Exception as e: pass try: the_user = getUserFromToken() session_data = getTokenData() #Remove utilized token for token in the_user['tokens']: if token == session_data['token']: #Remove token from user Users.objects(username=the_user['username']).update_one( pull__tokens = token ) return dict(r='ok') #Leave session & cookie to remember user data such as prefered language, remember user and so on #If token not in iteration just raise error raise StandardError("token does not exists") except Exception as e: return StandardError(e) #remove session record if logout fails from database session.kill() web.setcookie(quetzal_config['cookie_name'], '', expires=-1) raise StandardError("Error During Logout, Session terminated anyway")
def POST(self): formulario = web.input() # get form data # call model insert_registro and try to insert new data correo = formulario['user'] nombre = formulario['nombre'] carrera = formulario['carrera'] grado = formulario['grado'] tipo = formulario['tipo'] correcto = False if '@utectulancingo.edu.mx' in correo: correcto = True else: web.setcookie('_id', '', 0) # cierre de session en google raise web.seeother('/') # render registro index.html user_hash = hashlib.md5( correo + app.secret_key).hexdigest() # encrypt user_hash picture = app.session.picture print tipo if tipo == '0' and correcto == True: config.model_registro.insert_registro(correo, nombre, carrera, grado, tipo, user_hash, picture) config.model_asesor.insert_asesor(correo, nombre, carrera, grado) elif correcto == True: config.model_registro.insert_registro(correo, nombre, carrera, grado, tipo, user_hash, picture) raise web.seeother('/') # render registro index.html
def GET(self): """ Clears the client cookies and returns the user to the login page. """ web.setcookie("token", "", -1, util.portal_ip, path=util.portal_root) web.setcookie("tenant_id", "", -1, util.portal_ip, path=util.portal_root) raise web.seeother(".." + util.portal_root)
def current_user(): user = web.cookies().get('userid') username = '' if user: web.setcookie('userid', user, 600) username = Users.get(Users.id == user).username return user, username
def POST(self): var = web.input() if 'fb' in var: xsrf = util.select_one('xsrf', where='token=$tok', vars={'tok': var.xsrf}) if xsrf is None: raise status.ApiError('401 Unauthorized') try: xsrf = util.select_one('xsrf', where='token=$tok', vars={'tok': var.xsrf}) if xsrf is None: raise status.ApiError('401 Unauthorized') user = self.user_auth(var.email, var.pword) if user is None: print "this one" raise status.ApiError('401 Unauthorized') sess = str(uuid.uuid4())[:64] values = { 'sess': sess, 'uid': user['id'] } util.insert('sessions', **values) web.setcookie('wsid_login', sess, path='/') except AttributeError as err: print "that one" raise status.ApiError('401 Unauthorized (%s)' % err) web.redirect('/')
def GET(self): global session_time global session_id web.header("Content-Type","text/html; charset=utf-8") content = "" showNavBar = False #Should show the navigation bar if (get_status() == "PROTECTED"): if check_sid(web.cookies().get('sid')): content += "Serving current user. Please give up before creating new session.\n" showNavBar = True else: content += "Serving other user in protected period.\nACCESS DENIED.\n" else: content += "Killing background utilities.\n" content += os.popen("./stopall.sh").read() content += "Genearting new session ID.\n" session_time = time.time() new_sid = str(random.randint(100000000, 999999999)); #sid is 9 digits integer in string session_id = new_sid set_status("PROTECTED") content += "New seesion ID is " + str(new_sid) + ".\n" content += "Status is " + get_status() + ".\n" web.setcookie("sid", new_sid, expires=3600) showNavBar = True return render.new(get_status(), showNavBar, content)
def GET(self, param): entity = model.get_model_by_name(param) form = forms.getSearchForm(entity.exposed_search_properties()) pagination = Paginator(web.input(), entity) display_message=web.cookies().get('display_message') web.setcookie('display_message', '') return render_admin.listar(form, pagination, display_message=display_message)
def POST(self): ''' This function destroys all cookies related to user session. ''' web.setcookie('user', '', expires=-1) web.setcookie('session_id', '', expires=-1) raise web.seeother('/login')
def POST(self): """Overrides `account_login` and infogami.login to prevent users from logging in with Open Library username and password if the payload is json. Instead, if login attempted w/ json credentials, requires Archive.org s3 keys. """ d = simplejson.loads(web.data()) access = d.get('access', None) secret = d.get('secret', None) test = d.get('test', False) # Try S3 authentication first, fallback to infogami user, pass if access and secret: audit = audit_accounts(None, None, require_link=True, s3_access_key=access, s3_secret_key=secret, test=test) error = audit.get('error') if error: raise olib.code.BadRequest(error) web.setcookie(config.login_cookie_name, web.ctx.conn.get_auth_token()) # Fallback to infogami user/pass else: from infogami.plugins.api.code import login as infogami_login infogami_login().POST()
def POST(self, cursor): form = web.input(user_name=None, password=None) pass_hash = crypt.crypt(form.password+"baa", "8tr034FhaM4qg") cursor.execute(""" SELECT user_id FROM public.user WHERE user_name = %s AND pass_hash = %s ;""", (form.user_name, pass_hash)) user = cursor.fetchone() if not user: return header(page_title="Logging in") + \ """<p><b>Sorry, we couldn't log you in. Did you get your password wrong?</b></p> <form method="POST"> Username: <input name="user_name"><br> Password: <input type="password" name="password"><br> <input type="Submit" value="Log in"> </form>""" + footer() else: user_id = user[0] auth = random.randint(1, 1000000) cursor.execute(""" UPDATE public.user SET user_auth = %s WHERE user_id = %s; """, (auth, user_id)) cursor.execute(""" SELECT * FROM public.user WHERE user_id = %s; """, (user_id,)) web.setcookie("user_id", str(user_id), 3600*24*365) web.setcookie("auth", str(auth), 3600*24*365) web.header("Refresh", "0; /") return "Logged in, redirecting"
def SetSecureCookie(name, value, expires, **kwargs): timestamp = str(int(time.time())) value = base64.b64encode(value) sig = GenerateCookieSig(name, value, timestamp, expires) value = '|'.join((name, value, timestamp, str(expires), sig)) web.setcookie(name, value, expires=expires, secure=True, **kwargs)
def POST(self): """ Handle login """ inp = web.input() # FIXME: Use const for cookie lifetime and hash secret if 'user_mail' in inp and 'user_pwd' in inp: try: user = User.get( User.mail == inp.user_mail, User.password == inp.user_pwd ) logging.info("Login by user {}".format(user.id)) web.setcookie( '_k', hashlib.md5( "{0}-{1}".format(HASH_SALT, inp.user_mail) ).hexdigest(), 360000 ) web.ctx.session.auth = 1 raise web.seeother("/admin/") except DoesNotExist: # User not found in DB logging.warning("Login attempt") raise web.seeother("/login/") else: # Form params not present raise web.seeother("/login/")
def POST(self): # unlike the usual scheme of things, the POST is actually called # first here i = web.input(return_to='/') if i.get('action') == 'logout': web.webopenid.logout() return web.redirect(i.return_to) i = web.input('openid', return_to='/') going = owevent.going_to_auth(owglobal.session.datapath, owglobal.session.host, i['openid']) owglobal.server.post_event(going) output.dbg(str(owglobal.session.host)+\ " is going to "+going.server()+" to authenticate", self.__class__.__name__) n = web.webopenid._random_session() web.webopenid.sessions[n] = {'webpy_return_to': i.return_to} c = openid.consumer.consumer.Consumer(web.webopenid.sessions[n], web.webopenid.store) a = c.begin(i.openid) f = a.redirectURL(web.ctx.home, web.ctx.home + web.ctx.fullpath) web.setcookie('openid_session_id', n) return web.redirect(f)
def GET(self): if iscookie() == True: i = web.input(access='True') web.setcookie('access', i.access, 600) return open(r'index.html', 'r').read() else: return web.redirect('login')
def POST(self): form = web.input(form_signin={}) #往数据库users插入数据 name = form['name'].strip() email = form['email'].strip().lower() password = form['password'] print name,email,password if not name: return '请输入用户名' if not email or not _RE_EMAIL.match(email): return '请输入正确的Email地址' if not password or not _RE_MD5.match(password): return '请输入正确的密码' user = model.find_item_by_email(model.User,email) if user: return '邮箱已注册' user_name = model.find_item_by_name(model.User,name) if user_name: return '用户名已存在' ip = web.ctx.ip select = form['select'] #insert user id = model.new_user(email,password,name,select,ip) #save one day,write to cookie cookie = utils.make_signed_cookie(id,password,ip) web.setcookie(utils._COOKIE_NAME,cookie,expires=86400)
def POST_login(self, i): # make sure the username is valid if not forms.vlogin.valid(i.username): return self.error("account_user_notfound", i) # Try to find account with exact username, failing which try for case variations. account = accounts.find(username=i.username) or accounts.find( lusername=i.username) if not account: return self.error("account_user_notfound", i) if i.redirect == "/account/login" or i.redirect == "": i.redirect = "/" status = account.login(i.password) if status == 'ok': expires = (i.remember and 3600 * 24 * 7) or "" web.setcookie(config.login_cookie_name, web.ctx.conn.get_auth_token(), expires=expires) raise web.seeother(i.redirect) elif status == "account_not_verified": return render_template("account/not_verified", username=account.username, password=i.password, email=account.email) elif status == "account_not_found": return self.error("account_user_notfound", i) elif status == "account_blocked": return self.error("account_blocked", i) else: return self.error("account_incorrect_password", i)
def POST(self): login_form = login() if login_form.validates(): if login_form.d.username == 'admin' \ and login_form.d.password == 'admin': web.setcookie('username', login_form.d.username) raise web.seeother('/')
def killSession(self): try: MongoOps().deleteOne('local', 'sessions', {'id': web.cookies().get('id')}) web.setcookie('id', "", -1) except Exception as err: print "ERR with killSession: ", err
def authenticate(rendered_tpl): """ Authentication management method. :param rendered_tpl: rendered page template :returns: rendered final page or a page with error message """ global AUTH_ISSUERS, SAML_SUPPORT, AUTH_TYPE, RENDERER valid_token_dict = validate_webui_token() if not valid_token_dict: # remember fullpath in cookie to return to after login setcookie('rucio-requested-path', value=unicode(ctx.fullpath), expires=120, path='/') else: return access_granted(valid_token_dict, rendered_tpl) # login without any known server config if not AUTH_TYPE: return RENDERER.select_login_method(AUTH_ISSUERS, SAML_SUPPORT) # for AUTH_TYPE predefined by the server continue else: if AUTH_TYPE == 'userpass': return seeother('/login') elif AUTH_TYPE == 'x509': return x509token_auth(None) elif AUTH_TYPE == 'x509_userpass': if ctx.env.get('SSL_CLIENT_VERIFY') == 'SUCCESS': return x509token_auth(None) return RENDERER.no_certificate() elif AUTH_TYPE == 'oidc': return oidc_auth(None, AUTH_ISSUER_WEBUI) elif AUTH_TYPE == 'saml': return saml_auth("GET", rendered_tpl) return RENDERER.problem('Invalid auth type')
def create_cookie(guid, data): # this may produce a slight variation in expiration dates between what we set # and what web.py sets, but we really don't care. session.cookie = scp.SecureCookie(get_session_hash(), web.secret) serial = session.cookie.serialize(guid, int(time.time()) + COOKIE_TTL, data) web.setcookie(COOKIE_NAME, serial, COOKIE_TTL, secure=True, httponly=True)
def GET(self): u = web.cookies().get('username') web.setcookie('username','logout',expires=-1) web.setcookie('session','logout',expires=-1) db.delete('sessions',where="username=$u",vars=locals()) raise web.seeother('/')
def POST(self): msg = None i = web.input() uid = i.get('userid') pwd = i.get('password') user_iter=model.get_user(uid,pwd) user = list(user_iter) user_info = web.ctx.session.userinfo if user: user_info['Name'] = user[0].username user_info['ID'] = uid user_info['Contact'] = user[0].contactname user_info['UnitAddr'] = user[0].unitaddress user_info['Tel'] = user[0].tel redirect_url = web.ctx.session.redirecturl #print next_page web.ctx.session.logged_in = True web.setcookie('backstep',-2,3600) if redirect_url: return web.seeother(redirect_url) else: #default return web.seeother('/member') else: msg="用户名或密码不正确" web.setcookie('login_id',uid,3600) return render.login()
def POST(self): i = web.input(imagefile={}) assert(not i.has_key('email')) assert(not i.has_key('password')) if i.has_key('birthday'): try: i.age = self.calcAge(i.birthday) except: return page_helper.failed('修改失败,生日格式填写错误 ') session = site_helper.session if session.is_login: if i.has_key('username'): user_name = i.username.encode('utf-8', 'ignore') if self.existsUsername(user_name, session.user_id): return page_helper.failed('修改失败, 用户名 ' +user_name+ ' 已被使用') web.setcookie('name', user_name) site_helper.session.user_name = user_name if i.has_key('self_domain'): self_domain = i.self_domain.encode('utf-8', 'ignore') if self.existsDomain(self_domain, session.user_id): return page_helper.failed('修改失败, 域名' +self_domain+ ' 已被使用') i.model_name = 'User' i.model_id = session.user_id return Update.POST(self, i, ) else: return page_helper.redirectToLogin()
def GET(self,name): #идентификация сессии и идентификация пользователя. print '2222', 'cdx' web.header('Content-type', 'text/html; charset=utf-8') con = sqlite3.connect('overhead.sqlite') cur = con.cursor() i = web.input() if i: #Открыть навую сессию после идентификации пользователя n = i.name p = i.passw sql = u"select * from auth_ko where user=? and passw=?" cur.execute(sql, (n, p)) r = cur.fetchall() if r: rez = r[0][1] sid = uuid.uuid4().hex sid = str(sid) sqlu = u"update auth_ko set sid=? where user=? and passw=?" cur.execute(sqlu, (sid, n, p)) con.commit() web.setcookie('sid', sid, 3600) print rez, 'sid=',sid raise web.redirect('/cdx1') #Начата новая сессия. Переходим на следующий шаг. else: return render.index('Логин или пароль неверен! ') else: raise web.redirect('/cdn') #Сюда попал, если логин и пароль не введены.
def GET(self, accept_str): if accept_str in model.accept_list(): return render({'title': settings.SITE_NAME}).notaccept() else: model.accept_code(accept_str) web.setcookie('accept_str', accept_str, settings.EXPIRES) raise web.redirect('/')
def POST(self): """Overrides `account_login` and infogami.login to prevent users from logging in with Open Library username and password if the payload is json. Instead, if login attempted w/ json credentials, requires Archive.org s3 keys. """ from openlibrary.plugins.openlibrary.code import BadRequest d = simplejson.loads(web.data()) access = d.get('access', None) secret = d.get('secret', None) test = d.get('test', False) # Try S3 authentication first, fallback to infogami user, pass if access and secret: audit = audit_accounts(None, None, require_link=True, s3_access_key=access, s3_secret_key=secret, test=test) error = audit.get('error') if error: raise olib.code.BadRequest(error) web.setcookie(config.login_cookie_name, web.ctx.conn.get_auth_token()) # Fallback to infogami user/pass else: from infogami.plugins.api.code import login as infogami_login infogami_login().POST()
def login(user): if user: session.uid = user['_id'] session.email = user['email'] session.nick = user['nick'] session.isVip = user['isVip'] web.setcookie('al', tools.int2hex(user['_id']), cookie_expires)
def POST(self): i = web.input() sql = "select * from myuser where name = \""+i.username.encode('utf-8','latin1')+"\"" results = db.query(sql) if results: err = "reg_name" other = "OK" return render.login(err,other) sql = "select * from myuser where email = \""+i.email.encode('utf-8','latin1')+"\"" results = db.query(sql) if results: err = "reg_email" other = "OK" return render.login(err,other) id = db.insert('myuser',name=i.username.encode('utf-8','latin1'),password=i.passwd.encode('utf-8','latin1'),email=i.email.encode('utf-8','latin1') ) web.setcookie('nomadicid',id, 18000) ip = web.ctx.ip sql = "replace into mysession (ip,id) values (" + "\"" + ip +"\"," + str(id) +")" db.query(sql) web.setcookie('nomadicpass', ip, 18000) return render.welcome()
def write_cookie(name): web.setcookie("xuser", name, expires= 24*3600*30) user = get_user(name) password = user.password salt = user.salt pswd_md5 = get_password_md5(password, salt) web.setcookie("xpass", pswd_md5, expires=24*3600*30)
def GET(self): client = web.cookies().get("client") if client == None: client = len(runners) web.setcookie('client', client) runners[client] = (Runner(randint(-5, 5), randint(-5, 5)))
def POST(self): # unlike the usual scheme of things, the POST is actually called # first here i = web.input(return_to='/') if i.get('action') == 'logout': oid.logout() return web.redirect(i.return_to) if not i.has_key('openid') or len(i.openid) == 0: return web.redirect(i.return_to) session_data = {'webpy_return_to': i.return_to} session_hash = oid._new_session(session_data) ax_req = ax.FetchRequest() ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/first', required=True)) ax_req.add(ax.AttrInfo('http://axschema.org/namePerson/last', required=True)) ax_req.add(ax.AttrInfo('http://axschema.org/contact/email', required=True)) c = openid.consumer.consumer.Consumer(session_data, oid._get_openid_store()) a = c.begin(i.openid) a.addExtension(ax_req) a.addExtension(sreg.SRegRequest(optional=['email', 'fullname'])) f = a.redirectURL(web.ctx.home, web.ctx.home + web.ctx.fullpath) oid._save_session(session_hash, session_data) web.setcookie('openid_session_id', session_hash) return web.redirect(f)
def GET(self,name): #идентификация сессии и идентификация пользователя. print '2222', 'cdx' web.header('Content-type', 'text/html; charset=utf-8') con = sqlite3.connect('overhead.sqlite') cur = con.cursor() i = web.input() if i: #Открыть навую сессию после идентификации пользователя n = i.name p = i.passw sql = u"select * from auth_ko where user=? and passw=?" cur.execute(sql, (n, p)) r = cur.fetchall() if r: rez = r[0][1] sid = uuid.uuid4().hex sid = str(sid) sqlu = u"update auth_ko set sid=? where user=? and passw=?" cur.execute(sqlu, (sid, n, p)) con.commit web.setcookie('sid', sid, 3600) print rez, 'sid=',sid raise web.redirect('/cdx1') #Начата новая сессия. Переходим на следующий шаг. else: return render.index('Логин или пароль неверен! ') else: raise web.redirect('/cdn') #Сюда попал, если логин и пароль не введены.
def GET(self, param, record_id): entry = model.entity_by_id(model.get_model_by_name(param), record_id) frm = forms.getForm(param) frm.fill(entry) display_message=web.cookies().get('display_message') web.setcookie('display_message', '') return render_admin.form(frm, titulo='Alterar %s' % param, verbo='editar', display_message=display_message, estilo='table')
def localization_hook(): default_lang = 'en' # default language lang = None path_info = web.ctx.env['PATH_INFO'] cookie = web.cookies().get("lang") # try reading language from URL path if not lang and path_info[1:3] in constants.supported_languages: web.ctx['fullpath'] = web.ctx['fullpath'][3:] web.ctx['path'] = web.ctx['path'][3:] web.ctx.env['REQUEST_URI'] = web.ctx.env['REQUEST_URI'][3:] web.ctx.env['PATH_INFO'] = path_info[3:] lang = path_info[1:3] # try reading language from cookie if not lang and cookie: if cookie in constants.supported_languages: lang = cookie # try reading language from browser if not lang and 'HTTP_ACCEPT_LANGUAGE' in web.ctx.env: lang_accept = web.ctx.env['HTTP_ACCEPT_LANGUAGE'] items = [i.partition(';q=') for i in lang_accept.split(",") if i] decoded = {k.strip(): (float(v) if len(v) > 0 else 1.0) for k, _, v in items} langs = {k: decoded[k] for k in decoded.iterkeys() if k[:2] in constants.supported_languages} best = max(langs.iteritems(), key=operator.itemgetter(1))[0] if best: lang = best[:2] # use default language if not lang: lang = default_lang web.setcookie("lang", lang, 31536000, common.get_domain(web.ctx.home), False, False, '/') common.session['lang'] = lang
def on_signin(self, profile): """ When the user is signing in, this sets up the session. If they are already signed in based on a cookie, then just direct them to index else, re-generate the session. sends the id to the browser so it can be called later. """ # web.setcookie('tempProfle', profile, 'Expires', -1) # web.setcookie('profile', profile) print "on_signin" try: u = self.queryOne('remote', 'users', {'id': profile['id']}) print "found u" if u['suspended']: raise web.seeother('/suspended') if u['verified']: if SessionMgr().newSession(profile['id'], web.ctx.get('ip')): raise web.seeother('index.html') except Exception as err: print "Error in on_signin: ", err # the error is no user exists, create registration page and direct them to that here. self.updateOne('local', 'tempProfiles', {'id': profile['id']}, profile, upsert=True) web.setcookie('id', profile['id']) raise web.seeother('/register') raise web.seeother('/')
def POST(self): i = web.input(username="", connect=None, password="", remember=False, redirect='/', test=False, access=None, secret=None) email = i.username # XXX username is now email audit = audit_accounts(email, i.password, require_link=True, s3_access_key=i.access, s3_secret_key=i.secret, test=i.test) error = audit.get('error') if error: return self.render_error(error, i) expires = (i.remember and 3600 * 24 * 7) or "" web.setcookie(config.login_cookie_name, web.ctx.conn.get_auth_token(), expires=expires) blacklist = [ "/account/login", "/account/password", "/account/email", "/account/create" ] if i.redirect == "" or any([path in i.redirect for path in blacklist]): i.redirect = "/" raise web.seeother(i.redirect)
def GET(self): cookie = web.cookies() web.setcookie('user', '', 3600) web.setcookie('color', '', 3600) db.delete('user', where='user="******"'.format(cookie.user)) db.delete('data', where='user="******"'.format(cookie.user)) return render.bye()
def POST(self, name): data = web.data() print data r = json.loads(data) if r['req_str'].find("spam") >= 0: return "spam" web.setcookie('age', 41, 3600) return "ok"
def GET(self): # Unsetting cookies web.setcookie("login", "", -1) web.setcookie("password", "", -1) # Going back to home page web.seeother('/')
def POST(self): i = web.input() #username = i.username username = i.username password = i.password #valided_username = valid_name(username) valided_username = valid_name(username) valided_password = valid_password(password) if valided_username and valided_password: #validation success,access the database users = web.ctx.orm.query(User).filter_by(username=username).all() if users: user = users[0] userid = user.userid if verify_pw(password, user.userpass, user.salt): cookie_user = '******' % (user.username, user.userpass) #set cookie web.setcookie('user',cookie_user) self.redirect('/profile') else: return self.write_html(user=None, error='The user is not exist,or the password does not match this acount!oops!') else: return self.write_html(user=None, error='The input name or password is invalid!oops!')
def POST(self): postdata = web.input() username = postdata.username password = postdata.password rslist = getUserByUserName(username) if len(rslist) == 0: return 'user is not exist' else: if rslist[0].password == password: #新增session记录名称 UserId = rslist[0].id print UserId, username session = web.config._session print session.status session.status = 0 print session.status cookies = web.cookies() print cookies web.setcookie('id', UserId) web.setcookie('name', username) return render.welcome(username) else: return 'password error'