def post_login(self): """ Handle logic post a user's login I want to create a login_handler that's redirected to after login. This would check - if user was logged in, if not then send back to login - if user is admin, go to job list - if user can add joblist then go to * - if user is read only go to job list that's trimmed down a bit On the post login page adjust the max age on the existing cookie to XX remember me timeframe """ if auth.check(not_anonymous()): log.debug('checked auth') else: # login failed, redirect back to login log.debug('failed auth') redirect(url(controller="accounts", action="login", login_failed=True) ) # expire this cookie into the future ck = request.cookies['authtkt'] response.set_cookie('authtkt', ck, max_age=60 * 60 * 24 * 7, path='/' ) redirect(url('/page/test'))
def harviewer(self): """HAR Viewer iframe""" # HAR Viewer customization via cookie response.set_cookie("phaseInterval", "-1", max_age=365 * 24 * 3600) return render("/harviewer.html")
def post_login(self): """ Handle logic post a user's login I want to create a login_handler that's redirected to after login. This would check - if user was logged in, if not then send back to login - if user is admin, go to job list - if user can add joblist then go to * - if user is read only go to job list that's trimmed down a bit On the post login page adjust the max age on the existing cookie to XX remember me timeframe """ if auth.check(not_anonymous()): log.debug('checked auth') else: # login failed, redirect back to login log.debug('failed auth') redirect( url(controller="accounts", action="login", login_failed=True)) # expire this cookie into the future ck = request.cookies['authtkt'] response.set_cookie('authtkt', ck, max_age=60 * 60 * 24 * 7, path='/') redirect(url('/page/test'))
def localize(f, *args, **kwargs): if 'lang' in session: lang = session['lang'] set_lang(lang) else: suport_lang = ['ru','en','uk'] suport_domain = ['cleverad.yt:5000','10.0.0.8:5000'] default_lang = 'ru' lang_cookie = request.cookies.get('lang', None) if not lang_cookie in suport_lang: lang_cookie = None domain = request.environ.get('HTTP_HOST', None) if not domain in suport_domain: domain = None if lang_cookie != None: lang = lang_cookie else: if domain == 'cleverad.yt:5000': lang = 'en' elif domain == '10.0.0.8:5000': lang = 'uk' elif domain == '10.0.0.8': lang = 'ru' else: lang = default_lang session['lang'] = lang session.save() set_lang(lang) response.set_cookie('lang', lang, max_age=360*24*3600 ) return f(*args, **kwargs)
def add_transient_message(cookie_name, message_title, message_text): """Add a message dict to the serialized list of message dicts stored in the named cookie. If there is no existing cookie, create one. If there is an existing cookie, assumes that it will de-serialize into a list object. """ time = datetime.now().strftime('%H:%M, %B %d, %Y') msg = dict( time = time, title = message_title, text = message_text, ) old_data = request.cookies.get(cookie_name, None) if old_data is not None: response.delete_cookie(cookie_name) if old_data: msgs = simplejson.loads(unquote(old_data)) else: msgs = [] msgs.append(msg) new_data = quote(simplejson.dumps(msgs)) response.set_cookie(cookie_name, new_data, path='/')
def harviewer(self): """HAR Viewer iframe""" # HAR Viewer customization via cookie response.set_cookie("phaseInterval", "-1", max_age=365*24*3600 ) return render("/harviewer.html")
def _upload(self): if request.POST['type']: response.set_cookie('source_type', request.POST['type']) try: file = request.POST['source'] if request.POST['type'] != '*': file.filename += "."+request.POST['type'] size = len(file.value) fileName = file.filename.replace(" ", "_").encode('ascii', 'ignore') fileValue = file.value except: if request.POST['code'] != '' and request.POST['type'] != '*': fileName = b16encode(request.POST['code'])[:16]+"."+request.POST['type'] fileValue = request.POST['code'] size = len(fileValue) else: return False if size>1024*10: # 10 kB return False if not self.source: self.source = Source(self.task.contest_id, self.task.id, self.user.id, fileName) Session.add(self.source) self.source.file = fileName self.source.source = fileValue self.source.commit() return True
def try_pagecache(self): # check content cache if request.method.upper() == "GET" and not c.user_is_loggedin: r = g.pagecache.get(self.request_key()) if r: r, c.cookies = r response = c.response response.headers = r.headers response.content = r.content for x in r.cookies.keys(): if x in cache_affecting_cookies: cookie = r.cookies[x] response.set_cookie( key=x, value=cookie.value, domain=cookie.get("domain", None), expires=cookie.get("expires", None), path=cookie.get("path", None), secure=cookie.get("secure", False), httponly=cookie.get("httponly", False), ) response.status_code = r.status_code request.environ["pylons.routes_dict"]["action"] = "cached_response" c.request_timer.name = request_timer_name("cached_response") # make sure to carry over the content type c.response_content_type = r.headers["content-type"] c.used_cache = True # response wrappers have already been applied before cache write c.response_wrappers = []
def me(self): if (request.method == "GET"): cookie = request.cookies.get("GFB_Cookie") if(cookie == None): return '' else: decode = Cookie.decryptCookie(cookie) return json.dumps(decode) else: #open host site cookie = request.cookies.get("GFB_Cookie") if(cookie == None): return '' else: encode = {} decode = Cookie.decryptCookie(cookie) encode['role'] = decode['role'] encode['user_name'] = decode['user_name'] encode['email'] = decode['email'] if (request.params['changed'] == 'true'): encode['host_site'] = request.params['siteID'] else: encode['host_site'] = '' cookie = Cookie(encode['user_name'],encode['email'], encode['role'], encode['host_site']) response.delete_cookie('GFB_Cookie') response.set_cookie("GFB_Cookie", cookie.encryptCookie(), max_age=180*24*3600) return render('/tools/distOrders.mako')
def tw_callback(self): log.info('request %s' % request) verifier = request.GET.get('oauth_verifier') log.info('verifier [%s] session[%s]' % (verifier, session)) auth = tweepy.OAuthHandler(TW_KEY, TW_SECRET) if 'request_token' in session: token = session['request_token'] session['request_token'] = None else: log.error('oops request token not foudn in the session') #session.delete('request_token') auth.set_request_token(token[0], token[1]) try: auth.get_access_token(verifier) except Exception: log.exception('Veifier error') raise log.info('Ok. got the request token key[%s] and secret[%s]' % (auth.access_token.key, auth.access_token.secret)) #check if user exists with given screen name #new_auth.set_access_token(auth.access_token.key, auth.access_token.secret) auth.set_access_token(auth.access_token.key, auth.access_token.secret) api = tweepy.API(auth) #api.update_status('testing' + 'tweepy' + 'oauth') tw_user = api.me() log.info('User info[%s] tw_id[%s]' % (tw_user.screen_name, tw_user.id)) user = user_service.get_or_create_user(screen_name = tw_user.screen_name, \ tw_id = str(tw_user.id), key = auth.access_token.key,\ secret = auth.access_token.secret) #workflow to see if user exists or it is a first time user response.set_cookie(USER_INFO_COOKIE, tw_user.screen_name, max_age = 60*60*24) return 'Hi %s, your details token:[%s] and secret[%s]' % (tw_user.screen_name, auth.access_token.key, auth.access_token.secret)
def try_pagecache(self): #check content cache if request.method.upper() == 'GET' and not c.user_is_loggedin: r = g.pagecache.get(self.request_key()) if r: r, c.cookies = r response.headers = r.headers response.content = r.content for x in r.cookies.keys(): if x in cache_affecting_cookies: cookie = r.cookies[x] response.set_cookie(key=x, value=cookie.value, domain=cookie.get('domain', None), expires=cookie.get('expires', None), path=cookie.get('path', None), secure=cookie.get('secure', False), httponly=cookie.get('httponly', False)) response.status_code = r.status_code request.environ['pylons.routes_dict']['action'] = 'cached_response' c.request_timer.name = request_timer_name("cached_response") # make sure to carry over the content type response.content_type = r.headers['content-type'] c.used_cache = True # response wrappers have already been applied before cache write c.response_wrapper = None
def login(self): if request.cookies.get('userid'): return render('login.mako') else: db = dbConnect() dbCursor = db.cursor() if 'username' in request.params: username = request.params['username'] password = request.params['password'] else: username = '' password = '' dbCursor.execute("""SELECT count(*) as numRows FROM users where username=%s AND password=%s""", (username, password)) data = dbCursor.fetchone() if data[0] != 0: response.set_cookie('userid', username, max_age=180*24*3600 ) return render('login.mako') else: c.loginError = 1 c.deleteAll = 0 c.toDelete = 0 c.newUserSet = 0 c.userAdded = 0 c.userDeleted = 0 c.addError = '' c.user = getUsers(db) return render('users.mako')
def me(self): if (request.method == "GET"): cookie = request.cookies.get("GFB_Cookie") if (cookie == None): return '' else: decode = Cookie.decryptCookie(cookie) return json.dumps(decode) else: #open host site cookie = request.cookies.get("GFB_Cookie") if (cookie == None): return '' else: encode = {} decode = Cookie.decryptCookie(cookie) encode['role'] = decode['role'] encode['user_name'] = decode['user_name'] encode['email'] = decode['email'] if (request.params['changed'] == 'true'): encode['host_site'] = request.params['siteID'] else: encode['host_site'] = '' cookie = Cookie(encode['user_name'], encode['email'], encode['role'], encode['host_site']) response.delete_cookie('GFB_Cookie') response.set_cookie("GFB_Cookie", cookie.encryptCookie(), max_age=180 * 24 * 3600) return render('/tools/distOrders.mako')
def get_user(cls): username = get_current_user().username # 315569260 seconds = 10 years response.set_cookie('local', username, httponly=False, max_age=315569260) return {'ok': True, 'data': {'username': username}}
def touch_beta_cookie(): cookie_name = 'beta_' + c.beta response.set_cookie( key=cookie_name, value='1', domain=g.domain, expires=datetime.now() + timedelta(days=7), )
def forget(controller_result, raised=None): """ Check if the form's inputs can be forgotten, and set the cookie to forget if so. :param res: the result of the controller action :param raised: any error (redirect or exception) raised by the controller action """ if _ok_to_forget(response, controller_result, raised): response.set_cookie('memorable_forget', request.path)
def sign_in_user(user, long_session=False): set_geolocation(user) session['login'] = user.id session['cookie_secret'] = ''.join(Random().sample(string.ascii_lowercase, 20)) expiration_time = 3600*24*30 if long_session else None response.set_cookie('ututi_session_lifetime', session['cookie_secret'], max_age = expiration_time) session.save()
def _setPersistentCookie(self, username): # TODO Generar una cookie "segura" cookieName = 'popego_user' if cookieName not in request.cookies or request.cookies[ cookieName] != username: response.set_cookie(cookieName, username, expires=3600 * 24 * 365 * 10)
def set_cookie_user(user_id): thyme = time.time() secret_str = '%s:%d:%d' % (get_cookie_secret(user_id, thyme), thyme, user_id) user = model.User.get(user_id) user.token = secret_str model.Session.add(user) model.Session.commit() # expires in 15 days response.set_cookie('user_id', secret_str, max_age=1296000)
def login(self): sql = 'SELECT * FROM users WHERE BINARY username = "******" AND BINARY password = "******";' cur.execute(sql) row = cur.fetchone() if row: response.set_cookie("usernameCIS3210" , request.POST.get('userName'), max_age=180*24*3600) return json.dumps({'code': render("/manageUsers.mako")}) else: return json.dumps({'error':'Authentication error.'})
def delete_beta_cookie(): cookie_name = 'beta_' + c.beta beta_cookie = request.cookies.get(cookie_name) if beta_cookie: response.set_cookie( key=cookie_name, value='', domain=g.domain, expires=DELETE_COOKIE, )
def cookie_set(key, value, max_age=3600*24*365, secure=None, sub_domain=None, domain=None): """ duration in seconds """ #print "COOKIE setting %s:%s" %(key, value) if secure == None: secure = (current_protocol() == "https") if sub_domain != None: domain = sub_domain+'.'+(domain or get_domain()) response.set_cookie(key, value, max_age=max_age, secure=secure, path='/', domain=domain) #, domain=request.environ.get("HTTP_HOST", "") # AllanC - domain remarked because firefox 3.5 was not retaining the logged_in cookie with domain localhost
def checkLogedIn(self): if request.POST.get('username'): if request.POST.get('username') == request.cookies.get("usernameCIS3210"): return render("/manageUsers.mako") else: response.set_cookie("usernameCIS3210" , request.cookies.get("usernameCIS3210"), max_age= -1) return render("/login.mako") else: response.set_cookie("usernameCIS3210" , request.cookies.get("usernameCIS3210"), max_age= -1) return render("/login.mako")
def signin(self): if request.method == "GET": return render("sign_in.mako") email = self.form_result.get("email") password = self.form_result.get("password") pers = self.person_q.filter_by(email=email, password=md5(password)).first() if pers: response.set_cookie("email", email) response.set_cookie("password", md5(password)) redirect("/chanel/main") return "Invalid user name and/or password %s" % dir
def login(self): global db global user if 'username' in request.params and 'password' in request.params: uname = request.params['username'] passwd = request.params['password'] if (user.login(uname, passwd, db)): response.set_cookie( "authenticated" , uname, max_age=180*24*3600 ) return "Valid" else: return "Invalid"
def auth(self): try: cursor.execute("select password from tbaronUsers where username = %s;", (request.params["username"])) conn.commit() result = cursor.fetchone() if result[0] == request.params["password"]: response.set_cookie("username", request.params["username"], max_age=180 * 24 * 3600) return {"success": True} else: return {"error": True} except: return {"error": True}
def login_user(self, username_lower): with self.lock: if username_lower in self.users: user = self.users[username_lower] else: try: user = self._add_user(username_lower) self._write_users() except ValueError as e: raise BadRequest(str(e)) # 315569260 seconds = 10 years response.set_cookie('local', username_lower, httponly=False, max_age=315569260) return user
def get_user(self): if c.user_id: redirect(url(controller='action', action='feeds')) else: email_id = request.params.get('email') password = request.params.get('password') u = User.objects(email_id=email_id, password=password) if u: u = u[0] log.info("User Created Successfully with id:%s" % u.id) c.user_id = "%s" % u.id response.set_cookie('login', '%s' % c.user_id, max_age=18000) redirect(url(controller='action', action='feeds')) else: return "Some Error While Login."
def create_user(self): name = request.params.get('name') email = request.params.get('email') password = request.params.get('password') uni_name = request.params.get('university') log.info("Params are:%s %s %s %s" %(name, email, password, uni_name)) new_user = User(email=email, name=name, password=password, uni_name = uni_name).save() c.user_id = "%s" %new_user.id if new_user: log.info("User Created Successfully with id:%s" %c.user_id) #return "User Created..." response.set_cookie('login', 'present', max_age = 18000) return "User Created..." else: return "Error while creating user.."
def get_server_token(): if request.environ["webob.adhoc_attrs"].has_key("server_token"): token = request.server_token elif request.cookies.has_key(TOKEN_FIELD_NAME): token = request.cookies.pop(TOKEN_FIELD_NAME) else: import binascii, os token = binascii.hexlify(os.urandom(32)) response.set_cookie(TOKEN_FIELD_NAME, token, max_age=600, httponly=True) if token is None or token.strip() == "": csrf_fail("Server token is blank") request.server_token = token return token
def auth(self): db = DB() if (request.method == "GET"): # Check if user's email and password are matched success = db.authUser(request.params['email'], request.params['password']) if(success): # Setup the cookie (encrypted) with useful information user = db.getUser(request.params['email']) cookie = Cookie(user.get('first_name'), user.get('email'), user.get('fk_credentials'), user.get('fk_hostsite_id')) response.set_cookie("GFB_Cookie", cookie.encryptCookie(), max_age=180*24*3600) return self.trueString else: return "{\"success\" : \"false\", \"message\" : \"Unable to login: bad username or password\"}" else: return "{\"success\" : \"false\", \"message\" : \"Bad request.\"}"
def auth(self): try: cursor.execute( "select password from tbaronUsers where username = %s;", (request.params['username'])) conn.commit() result = cursor.fetchone() if result[0] == request.params['password']: response.set_cookie('username', request.params['username'], max_age=180 * 24 * 3600) return {"success": True} else: return {"error": True} except: return {"error": True}
def handle_request(request, tmpl_context): ''' Set the language for the request ''' lang = request.environ.get('CKAN_LANG') or \ config.get('ckan.locale_default', 'en') if lang != 'en': i18n.set_lang(lang) tmpl_context.language = lang # set ckan_lang cookie if we have changed the language. We need to # remember this because repoze.who does it's own redirect. try: if request.cookies.get('ckan_lang') != lang: response.set_cookie('ckan_lang', lang) except AttributeError: # when testing FakeRequest does not have cookies pass return lang
def signup(self): if request.method == "GET": redirect("/") email = self.form_result.get("email") name = self.form_result.get("name") password = self.form_result.get("password") result = self.person_q.filter_by(name=name).first() if result: return "This nickname is used by another one" result2 = self.person_q.filter_by(email=email).first() if result2: return "This email registered yet. Do u forget your password?" pers = Person(name=name, email=email, password=md5(password)) Session.add(pers) Session.commit() response.set_cookie("email", email) response.set_cookie("password", md5(password)) redirect("/chanel/main")
def auth(self): db = DB() if (request.method == "GET"): # authenticate with the database controller, assume that login is setting request params with username and password # I want the role # success = authUser(email, password) success = True if(success): # role, username, password # user = db.getUser() # cookie = Cookie(email, password, user.get('role')) cookie = Cookie('miakilborn', 'thisismypassword!', '1') response.set_cookie("FCS_GFB_Cookie", cookie.encryptCookie(), max_age=180*24*3600) return true_string else: return "{\"success\" : \"false\", \"message\" : \"Unable to login: bad username or password\"}" else: return "{\"success\" : \"false\", \"message\" : \"\"}"
def get_site_notification(self): from pylons import request, response from allura.model.notification import SiteNotification note = SiteNotification.current() if note is None: return None cookie = request.cookies.get('site-notification', '').split('-') if len(cookie) == 3 and cookie[0] == str(note._id): views = asint(cookie[1]) + 1 closed = asbool(cookie[2]) else: views = 1 closed = False if closed or note.impressions > 0 and views > note.impressions: return None response.set_cookie( 'site-notification', '-'.join(map(str, [note._id, views, closed])), max_age=timedelta(days=365)) return note
def get_site_notification(self): from pylons import request, response from allura.model.notification import SiteNotification note = SiteNotification.current() if note is None: return None cookie = request.cookies.get('site-notification', '').split('-') if len(cookie) == 3 and cookie[0] == str(note._id): views = asint(cookie[1])+1 closed = asbool(cookie[2]) else: views = 1 closed = False if closed or note.impressions > 0 and views > note.impressions: return None response.set_cookie( 'site-notification', '-'.join(map(str, [note._id, views, closed])), max_age=timedelta(days=365)) return note
def create_user(self): if c.user_id: redirect(url(controller='action', action='feeds')) else: name = request.params.get('name') email_id = request.params.get('email') password = request.params.get('password') university = request.params.get('university') log.info("Params are:%s %s %s %s" % (name, email_id, password, university)) new_user = User(email_id=email_id, name=name, password=password, university=university).save() c.user_id = "%s" % new_user.id if new_user: log.info("User Created Successfully with id:%s" % c.user_id) response.set_cookie('login', '%s' % c.user_id, max_age=18000) redirect(url(controller='action', action='feeds')) else: return "Error while creating user.."
def auth(self): db = DB() if (request.method == "GET"): # Check if user's email and password are matched success = db.authUser(request.params['email'], request.params['password']) if (success): # Setup the cookie (encrypted) with useful information user = db.getUser(request.params['email']) cookie = Cookie(user.get('first_name'), user.get('email'), user.get('fk_credentials'), user.get('fk_hostsite_id')) response.set_cookie("GFB_Cookie", cookie.encryptCookie(), max_age=180 * 24 * 3600) return self.trueString else: return "{\"success\" : \"false\", \"message\" : \"Unable to login: bad username or password\"}" else: return "{\"success\" : \"false\", \"message\" : \"Bad request.\"}"
def tw_callback(self): log.info('request %s' % request) verifier = request.GET.get('oauth_verifier') log.info('verifier [%s] session[%s]' % (verifier, session)) auth = tweepy.OAuthHandler(TW_KEY, TW_SECRET) if 'request_token' in session: token = session['request_token'] session['request_token'] = None else: log.error('oops request token not foudn in the session') #session.delete('request_token') auth.set_request_token(token[0], token[1]) try: auth.get_access_token(verifier) except Exception: log.exception('Veifier error') raise log.info('Ok. got the request token key[%s] and secret[%s]' % (auth.access_token.key, auth.access_token.secret)) #check if user exists with given screen name #new_auth.set_access_token(auth.access_token.key, auth.access_token.secret) auth.set_access_token(auth.access_token.key, auth.access_token.secret) api = tweepy.API(auth) #api.update_status('testing' + 'tweepy' + 'oauth') tw_user = api.me() log.info('User info[%s] tw_id[%s]' % (tw_user.screen_name, tw_user.id)) user = user_service.get_or_create_user(screen_name = tw_user.screen_name, \ tw_id = str(tw_user.id), key = auth.access_token.key,\ secret = auth.access_token.secret) #workflow to see if user exists or it is a first time user response.set_cookie(USER_INFO_COOKIE, tw_user.screen_name, max_age=60 * 60 * 24) return 'Hi %s, your details token:[%s] and secret[%s]' % ( tw_user.screen_name, auth.access_token.key, auth.access_token.secret)
def set_auth_cookie(user): auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'], user.username, user.level)).hexdigest() response.set_cookie('auth', auth, max_age=3600) response.set_cookie('username', user.username, max_age=3600) response.set_cookie('level', str(user.level), max_age=3600)
def set_auth_cookie(user): auth = hashlib.md5('%s:%s:%s' % (config['COOKIE_SECRET'], user.username, user.level)).hexdigest() response.set_cookie('auth', auth, max_age=2592000) response.set_cookie('username', user.username, max_age=2592000) response.set_cookie('level', str(user.level), max_age=2592000)
def store_transient_message(cookie_name, text, time=None, path='/', **kwargs): """Store a JSON message dict in the named cookie. The cookie will expire at the end of the session, but should be explicitly deleted by whoever reads it. :param cookie_name: The cookie name for this message. :param text: Message text :param time: Optional time to report. Defaults to now. :param path: Optional cookie path :param kwargs: Passed into the JSON dict :returns: The message python dict :rtype: dict """ time = datetime.now().strftime('%H:%M, %B %d, %Y') msg = kwargs msg['text'] = text msg['time'] = time or datetime.now().strftime('%H:%M, %B %d, %Y') new_data = quote(simplejson.dumps(msg)) response.set_cookie(cookie_name, new_data, path=path) return msg
def submit(self): """ Verify username and password """ # Both fields filled? form_username = str(request.params.get('username')) form_password = str(request.params.get('password')) # Get user data from database s = Session() rset = s.query(User).filter(User.username == form_username).all() if len(rset) < 1: # User does not exist return render('/login/loginindex.mako') usr = rset[0] cparts = usr.password.split('$') salt = cparts[2] oldmd = funcs.md5crypt(form_password, salt) # Wrong password? (MD5 hashes used here) if oldmd != usr.password: c.loginerror = True return render('/login/loginindex.mako') cookie_string = funcs.simplemd5(form_username + request.environ['REMOTE_ADDR']) # should set the cookie based here response.set_cookie('discsleftnet', cookie_string, expires='3600') # Mark user as logged in session['user'] = form_username session['custid'] = usr.id session['cur_cookie'] = cookie_string session.save() # Send user back to the page he originally wanted to get to if session.get('path_before_login'): redirect(session['path_before_login']) else: # if previous target is unknown just send the user to a welcome page return render('/login/loggedin.mako')
def auth(self): db = DB() if (request.method == "GET"): # authenticate with the database controller, assume that login is setting request params with username and password # I want the role # success = authUser(email, password) success = True if (success): # role, username, password # user = db.getUser() # cookie = Cookie(email, password, user.get('role')) cookie = Cookie('miakilborn', 'thisismypassword!', '1') response.set_cookie("FCS_GFB_Cookie", cookie.encryptCookie(), max_age=180 * 24 * 3600) return true_string else: return "{\"success\" : \"false\", \"message\" : \"Unable to login: bad username or password\"}" else: return "{\"success\" : \"false\", \"message\" : \"\"}"
def token(self): """ Return a session token, one-time hash and password hash for the user. """ # Ensure Content-type is text/xml if request.headers.get("Content-Type", "").startswith("text/xml") is False: return self._auth_abort(417, 'Invalid Parameter') # Retrieve request XML body payload = request.body if payload is None: log.error('Empty payload in auth:token()') return self._auth_abort(417, 'Invalid Parameter') # Retrieve the salt from the model authModel = AuthenticateModel.AuthenticateModel() login = authModel.getTokenLogin(payload) if login is None: return self._auth_abort(417, 'Invalid Parameter') salt = authModel.getTokenLoginSalt(login) if salt is None: log.debug('Invalid user %s', login) salt = encode(hashlib.sha1(os.urandom(4)).digest()) session['token'] = encode(hashlib.sha1(os.urandom(8)).digest()) session['token_salt'] = encode(hashlib.sha1(os.urandom(8)).digest()) session['salt'] = salt session['login'] = login session.save() c.token_salt = session['token_salt'] c.salt = salt response.set_cookie('token', session['token']) response.headers['content-type'] = 'text/xml; charset=utf-8' return render('/token.xml')
def ok(self): import traceback msg = str() try: id = getDic(request.params, "id") pw = getDic(request.params, "pw") if (id and pw): msg = sv.Login.LoginEntry(id, pw) else: msg = u"잘못된 정보전달" except Exception as err: exc_info = sys.exc_info() print "".join( traceback.format_exception(exc_info[0], exc_info[1], exc_info[2]) ) #return "EEEE", str(err) if (msg == "OK"): encodeName = convCookieHangul(session["UserName"]) response.set_cookie('userid', session["UserID"], max_age=86400) response.set_cookie('username', encodeName, max_age=86400) response.set_cookie('usertype', session["UserType"], max_age=86400) response.set_cookie('lastlogin', session["LastLogin"], max_age=86400) response.set_cookie('userlevel', session["UserLevel"], max_age=86400) if "preurl" in request.params and not IsBlank(request.params["preurl"]): preurl = request.params["preurl"] else: preurl = "/private/" redirect( str(preurl) ) else: return self.index(msg)
def token(self): """ Return a session token, one-time hash and password hash for the user. """ # Ensure Content-type is text/xml if request.headers.get("Content-Type", "").startswith("text/xml") is False: return self._auth_abort(417, "Invalid Parameter") # Retrieve request XML body payload = request.body if payload is None: log.error("Empty payload in auth:token()") return self._auth_abort(417, "Invalid Parameter") # Retrieve the salt from the model authModel = AuthenticateModel.AuthenticateModel() login = authModel.getTokenLogin(payload) if login is None: return self._auth_abort(417, "Invalid Parameter") salt = authModel.getTokenLoginSalt(login) if salt is None: log.debug("Invalid user %s", login) salt = encode(hashlib.sha1(os.urandom(4)).digest()) session["token"] = encode(hashlib.sha1(os.urandom(8)).digest()) session["token_salt"] = encode(hashlib.sha1(os.urandom(8)).digest()) session["salt"] = salt session["login"] = login session.save() c.token_salt = session["token_salt"] c.salt = salt response.set_cookie("token", session["token"]) response.headers["content-type"] = "text/xml; charset=utf-8" return render("/token.xml")
def getsession(self): ''' This generates a session key and sets it as a cookie set_cookie is defined in python-webob:: def set_cookie(self, key, value='', max_age=None, path='/', domain=None, secure=None, httponly=False, version=None, comment=None, expires=None, overwrite=False): ''' import binascii try: web_host = request.environ.get('HTTP_HOST') # HTTP_HOST also contains the port number. We need to stript this! web_host = web_host.split(':')[0] log.debug("[getsession] environment: %s" % request.environ) log.debug("[getsession] found this web_host: %s" % web_host) random_key = os.urandom(SESSION_KEY_LENGTH) cookie = binascii.hexlify(random_key) log.debug( "[getsession] adding session cookie %s to response." % cookie) # we send all three to cope with IE8 response.set_cookie('helpdesk_session', value=cookie, domain=web_host) # this produces an error with the gtk client # response.set_cookie('admin_session', value=cookie, domain=".%" % web_host ) response.set_cookie('helpdesk_session', value=cookie, domain="") return sendResult(response, True) except Exception as e: log.exception( "[getsession] unable to create a session cookie: %r" % e) Session.rollback() return sendError(response, e) finally: Session.close()
def check(self): ''' This function is used to login method: openid/check arguments: user - user to login realm - in which realm the user should login pass - password returns: JSON response ''' ok = False param = {} do_redirect = None message = None try: param.update(request.params) same_user = True passw = getParam(param, "pass", optional) ## getUserFromParam will return default realm if no realm is ## provided via @ append or extra parameter realm ## if the provided realm does not exist, the realm is left empty user = getUserFromParam(param, optional) ## if the requested user has a realm specified (via @realm append) ## and this is not the same as the user from getUserFromParam ## the requested user is not a valid one! p_user = param.get('user', '') if "@" in p_user: if p_user != "%s@%s" % (user.login, user.realm): same_user = False c.audit['user'] = user.login c.audit['realm'] = user.realm or getDefaultRealm() if same_user is True: (ok, opt) = checkUserPass(user, passw) c.audit['success'] = ok if ok: ## if the user authenticated successfully we need to set the cookie aka ## the ticket and we need to remember this ticket. user = "******" % (user.login, c.audit['realm']) log.debug("[check] user=%s" % user) token = self.storage.set_user_token(user, expire=self.COOKIE_EXPIRE) log.debug("[check] token=%s" % token) cookie = "%s:%s" % (user, token) log.debug("[check] cookie=%s" % cookie) response.set_cookie(COOKIE_NAME, cookie, max_age=self.COOKIE_EXPIRE) else: message = "Your login attempt was not successful!" Session.commit() # Only if we logged in successfully we redirect to the original # page (Servive Provider). Otherwise we will redirect to the # status page p = {} redirect_to = getParam(param, "redirect_to", optional) if redirect_to and ok: p = {} for k in [ 'openid.return_to', "openid.realm", "openid.ns", "openid.claimed_id", "openid.mode", "openid.identity" ]: p[k] = param[k] else: if message is not None: p["message"] = message redirect_to = "/openid/status" do_redirect = url(str("%s?%s" % (redirect_to, urlencode(p)))) except Exception as exx: log.error("[check] openid/check failed: %r" % exx) log.error("[__before__] %s" % traceback.format_exc()) Session.rollback() return sendError(response, "openid/check failed: %r" % exx, 0) finally: Session.close() log.debug('[check] done') if do_redirect: log.debug("[check] now redirecting to %s" % do_redirect) redirect(do_redirect)
def index(self): """Magicaltastic front page. Plugins can register a hook called 'frontpage_updates_<type>' to add updates to the front page. `<type>` is an arbitrary string indicating the sort of update the plugin knows how to handle; for example, spline-forum has a `frontpage_updates_forum` hook for posting news from a specific forum. Hook handlers should return a list of FrontPageUpdate objects. Standard hook parameters are: `limit`, the maximum number of items that should ever be returned. `max_age`, the number of seconds after which items expire. `title`, a name for the source. `icon`, an icon to show next to its name. `limit` and `max_age` are also global options. Updates are configured in the .ini like so: spline-frontpage.sources.foo = updatetype spline-frontpage.sources.foo.opt1 = val1 spline-frontpage.sources.foo.opt2 = val2 Note that the 'foo' name is completely arbitrary and is only used for grouping options together. This will result in a call to: run_hooks('frontpage_updates_updatetype', opt1=val1, opt2=val2) Plugins may also respond to the `frontpage_extras` hook with other interesting things to put on the front page. There's no way to customize the order of these extras or which appear and which don't, at the moment. Such hooks should return an object with at least a `template` attribute; the template will be called with the object passed in as its `obj` argument. Local plugins can override the fairly simple index.mako template to customize the front page layout. """ updates = [] global_limit = config['spline-frontpage.limit'] global_max_age = max_age_to_datetime( config['spline-frontpage.max_age']) c.sources = config['spline-frontpage.sources'] for source in c.sources: new_updates = source.poll(global_limit, global_max_age) updates.extend(new_updates) # Little optimization: once there are global_limit items, anything # older than the oldest cannot possibly make it onto the list. So, # bump global_max_age to that oldest time if this is ever the case. updates.sort(key=lambda obj: obj.time, reverse=True) del updates[global_limit:] if updates and len(updates) == global_limit: global_max_age = updates[-1].time # Find the oldest unseen item, to draw a divider after it. # If this stays as None, the divider goes at the top c.last_seen_item = None # Could have a timestamp in the stash if this is a user, or in a cookie # if this session has ever been logged out... times = [] for source in (c.user.stash, request.cookies): try: times.append(int(source['frontpage-last-seen-time'])) except (KeyError, ValueError): pass if times: last_seen_time = datetime.datetime.fromtimestamp(max(times)) for update in updates: if update.time > last_seen_time: c.last_seen_item = update else: break # Save ~now~ as the last-seen time now = datetime.datetime.now().strftime('%s') if c.user: c.user.stash['frontpage-last-seen-time'] = now meta.Session.add(c.user) else: response.set_cookie('frontpage-last-seen-time', now) # Done! Feed to template c.updates = updates # Hook for non-update interesting things to put on the front page. # This hook should return objects with a 'template' attribute, and # whatever else they need c.extras = run_hooks('frontpage_extras') ret = render('/index.mako') # Commit AFTER rendering the template! Committing invalidates # everything in the session, undoing any eagerloading that may have # been done by sources meta.Session.commit() return ret
def logout(self): response.set_cookie("usernameCIS3210" , request.cookies.get("usernameCIS3210"), max_age= -1) return render("/login.mako")
def post(self): c.request_timer.intermediate("action") # if the action raised an HTTPException (i.e. it aborted) then pylons # will have replaced response with the exception itself. c.is_exception_response = getattr(response, "_exception", False) if c.response_wrapper and not c.is_exception_response: content = flatten_response(response.content) wrapped_content = c.response_wrapper(content) response.content = wrapped_content if c.user_is_loggedin and not c.allow_loggedin_cache: response.headers['Cache-Control'] = 'no-cache' response.headers['Pragma'] = 'no-cache' if c.deny_frames: response.headers["X-Frame-Options"] = "DENY" # save the result of this page to the pagecache if possible. we # mustn't cache things that rely on state not tracked by request_key # such as If-Modified-Since headers for 304s or requesting IP for 429s. if (g.page_cache_time and request.method.upper() == 'GET' and c.can_use_pagecache and not c.used_cache and response.status_int not in (304, 429) and not response.status.startswith("5") and not c.is_exception_response): try: g.pagecache.set(self.request_key(), (response._current_obj(), c.cookies), g.page_cache_time) except MemcachedError as e: # this codepath will actually never be hit as long as # the pagecache memcached client is in no_reply mode. g.log.warning( "Ignored exception (%r) on pagecache " "write for %r", e, request.path) pragmas = [ p.strip() for p in request.headers.get("Pragma", "").split(",") ] if g.debug or "x-reddit-pagecache" in pragmas: if c.can_use_pagecache: pagecache_state = "hit" if c.used_cache else "miss" else: pagecache_state = "disallowed" response.headers["X-Reddit-Pagecache"] = pagecache_state # send cookies for k, v in c.cookies.iteritems(): if v.dirty: response.set_cookie(key=k, value=quote(v.value), domain=v.domain, expires=v.expires, secure=getattr(v, 'secure', False), httponly=getattr(v, 'httponly', False)) if self.should_update_last_visit(): c.user.update_last_visit(c.start_time) hooks.get_hook("reddit.request.end").call() # this thread is probably going to be reused, but it could be # a while before it is. So we might as well dump the cache in # the mean time so that we don't have dead objects hanging # around taking up memory g.reset_caches() c.request_timer.intermediate("post") # push data to statsd c.request_timer.stop() g.stats.flush()
def dropsession(self): response.set_cookie('helpdesk_session', None, expires=1) return sendResult(response, True)
def post(self): c.request_timer.intermediate("action") # if the action raised an HTTPException (i.e. it aborted) then pylons # will have replaced response with the exception itself. c.is_exception_response = getattr(response, "_exception", False) if c.response_wrapper and not c.is_exception_response: content = flatten_response(response.content) wrapped_content = c.response_wrapper(content) response.content = wrapped_content if c.user_is_loggedin and not c.allow_loggedin_cache: response.headers['Cache-Control'] = 'no-cache' response.headers['Pragma'] = 'no-cache' if c.deny_frames: response.headers["X-Frame-Options"] = "DENY" #set content cache if (g.page_cache_time and request.method.upper() == 'GET' and (not c.user_is_loggedin or c.allow_loggedin_cache) and not c.used_cache and response.status_int != 429 and not response.status.startswith("5") and not c.is_exception_response): try: g.pagecache.set(self.request_key(), (response._current_obj(), c.cookies), g.page_cache_time) except MemcachedError as e: # this codepath will actually never be hit as long as # the pagecache memcached client is in no_reply mode. g.log.warning("Ignored exception (%r) on pagecache " "write for %r", e, request.path) # send cookies for k, v in c.cookies.iteritems(): if v.dirty: response.set_cookie(key=k, value=quote(v.value), domain=v.domain, expires=v.expires, secure=getattr(v, 'secure', False), httponly=getattr(v, 'httponly', False)) if self.should_update_last_visit(): c.user.update_last_visit(c.start_time) hooks.get_hook("reddit.request.end").call() # this thread is probably going to be reused, but it could be # a while before it is. So we might as well dump the cache in # the mean time so that we don't have dead objects hanging # around taking up memory g.reset_caches() c.request_timer.intermediate("post") # push data to statsd c.request_timer.stop() g.stats.flush()