def _clearSession(self): if not self.uid is None: session['uid'] = None del(session['uid']) session.invalidate() session.save() session.delete()
def logout(self, **kw): try: if 'user' in session: session.invalidate() del session['user'] except: pass return self.login()
def delete(self): """DELETE /accounts: Delete an existing item""" # url('account') user = meta.Session.query(User).get(int(session['user_id'])) user.delete() session.invalidate() session.save() redirect(url("main"))
def login(self, **kw): try: if 'user' in session: session.invalidate() del session['user'] except: pass session.invalidate() return render('pbx/login.html')
def check(self): if "user" in session: user = User.query.filter(User.id == session["user_id"]).filter_by(session_id=session.id).first() if not user: session.invalidate() raise AuthenticationError(self.error_msg) for perm in user.permissions: for cred in self.credentials: if str(cred) == str(perm.name): return True raise AuthenticationError(self.error_msg) else: redirect("/admin/logout")
def check(self): if 'user' in session: row = User.query.filter(User.id==session['user_id']).filter_by(session_id=session.id).first() if not row: session.invalidate() raise AuthenticationError(self.error_msg) c.perms = row.permissions for p in c.perms: for cred in self.credentials: if str(cred) == str(p): return True raise AuthenticationError(self.error_msg) else: redirect("/admin/logout")
def check(self): try: if 'user' in session: row = AdminUser.query.filter_by(id=session['user_id']).filter_by(session_id=session.id).first() if not row: session.invalidate() redirect("/admin/logout") c.perms = row.permissions for p in c.perms: if 'superuser' in p: return True raise AuthenticationError("You have no rights here.") else: redirect("/admin/logout") except: redirect("/admin/logout")
def signout(self): user = session.get('user') or request.environ.get('REMOTE_USER') if user: log.info("%s signed out." % user) # Hack to confirm logout of user. session.clear() session.save() if request.environ.has_key('REMOTE_USER'): del request.environ['REMOTE_USER'] # The actual removal of the AuthKit cookie occurs when the response passes # through the AuthKit middleware, we simply need to display a page # confirming the user is signed out session.invalidate() redirect(url(controller='homepage', action='index'))
def index(self): _default_came_from = url('home') came_from = self._validate_came_from(request.GET.get('came_from')) c.came_from = came_from or _default_came_from not_default = self.authuser.username != User.DEFAULT_USER ip_allowed = self.authuser.ip_allowed # redirect if already logged in if self.authuser.is_authenticated and not_default and ip_allowed: raise HTTPFound(location=c.came_from) if request.POST: # import Login Form validator class login_form = LoginForm() try: session.invalidate() c.form_result = login_form.to_python(dict(request.POST)) # form checks for username/password, now we're authenticated headers = self._store_user_in_session( username=c.form_result['username'], remember=c.form_result['remember']) raise HTTPFound(location=c.came_from, headers=headers) except formencode.Invalid, errors: defaults = errors.value # remove password from filling in form again del defaults['password'] return htmlfill.render( render('/login.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8", force_defaults=False) except UserCreationError, e: # container auth or other auth functions that create users on # the fly can throw this exception signaling that there's issue # with user creation, explanation should be provided in # Exception itself h.flash(e, 'error')
def index(self): _default_came_from = url('home') came_from = self._validate_came_from(request.GET.get('came_from')) c.came_from = came_from or _default_came_from not_default = self.authuser.username != User.DEFAULT_USER ip_allowed = self.authuser.ip_allowed # redirect if already logged in if self.authuser.is_authenticated and not_default and ip_allowed: raise HTTPFound(location=c.came_from) if request.POST: # import Login Form validator class login_form = LoginForm() try: session.invalidate() c.form_result = login_form.to_python(dict(request.POST)) # form checks for username/password, now we're authenticated headers = self._store_user_in_session( username=c.form_result['username'], remember=c.form_result['remember']) raise HTTPFound(location=c.came_from, headers=headers) except formencode.Invalid, errors: defaults = errors.value # remove password from filling in form again del defaults['password'] return htmlfill.render(render('/login.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8", force_defaults=False) except UserCreationError, e: # container auth or other auth functions that create users on # the fly can throw this exception signaling that there's issue # with user creation, explanation should be provided in # Exception itself h.flash(e, 'error')
def document(self): """Render the error document""" '''Change below for your liking!''' #abort(500, 'Internal Server Error') request = self._py_object.request resp = request.environ.get('pylons.original_response') script = request.environ.get('PATH_INFO', '') error_code = cgi.escape(request.GET.get('code', str(resp.status_int))) content = literal(resp.body) or cgi.escape( request.GET.get('message', '')) remote_ip = request.environ.get("HTTP_REMOTE_EU", "No IP?") c.status_code = str(resp.status_int) if c.status_code == "404": c.message = "The document you are looking or was not found. The administrator has been notified of this event." elif c.status_code == "500": c.message = "An internal server error has occurred. The administrator has been notified of this event." else: c.message = "Sorry, an error has occurred. The administrator has been notified of this event." from_email = "*****@*****.**" to_email = '*****@*****.**' subject = "Error code " + error_code + " has happened from " + remote_ip message = content + "\n\n" from_name = "Errors" msg = from_name + "Error was:\n\n" + "Script: " + script + "\n\nMessage:" + message p = PbxSMTP(to_email, from_email, subject, msg) p.send_message() try: if 'user' in session: session.invalidate() del session['user'] except: pass return render("errors/error.html")
def get_auth_user(environ): ip_addr = get_ip_addr(environ) # make sure that we update permissions each time we call controller _auth_token = (request.GET.get('auth_token', '') or request.GET.get('api_key', '')) if _auth_token: # when using API_KEY we are sure user exists. auth_user = AuthUser(api_key=_auth_token, ip_addr=ip_addr) authenticated = False else: cookie_store = CookieStoreWrapper(session.get('rhodecode_user')) try: auth_user = AuthUser(user_id=cookie_store.get('user_id', None), ip_addr=ip_addr) except UserCreationError as e: h.flash(e, 'error') # container auth or other auth functions that create users # on the fly can throw this exception signaling that there's # issue with user creation, explanation should be provided # in Exception itself. We then create a simple blank # AuthUser auth_user = AuthUser(ip_addr=ip_addr) if password_changed(auth_user, session): session.invalidate() cookie_store = CookieStoreWrapper( session.get('rhodecode_user')) auth_user = AuthUser(ip_addr=ip_addr) authenticated = cookie_store.get('is_authenticated') if not auth_user.is_authenticated and auth_user.is_user_object: # user is not authenticated and not empty auth_user.set_authenticated(authenticated) return auth_user
def document(self): """Render the error document""" '''Change below for your liking!''' #abort(500, 'Internal Server Error') request = self._py_object.request resp = request.environ.get('pylons.original_response') script = request.environ.get('PATH_INFO', '') error_code=cgi.escape(request.GET.get('code', str(resp.status_int))) content = literal(resp.body) or cgi.escape(request.GET.get('message', '')) remote_ip = request.environ.get("HTTP_REMOTE_EU", "No IP?") c.status_code = str(resp.status_int) if c.status_code == "404": c.message = "The document you are looking or was not found. The administrator has been notified of this event." elif c.status_code == "500": c.message = "An internal server error has occurred. The administrator has been notified of this event." else: c.message = "Sorry, an error has occurred. The administrator has been notified of this event." from_email = "*****@*****.**" to_email = '*****@*****.**' subject = "Error code "+error_code+" has happened from "+remote_ip message = content+"\n\n" from_name = "Errors" msg = from_name+"Error was:\n\n"+"Script: "+script+"\n\nMessage:"+message p = PbxSMTP(to_email, from_email, subject, msg) p.send_message() try: if 'user' in session: session.invalidate() del session['user'] except: pass return render("errors/error.html")
def signin_user(user, login_provider=None): """ Perform the sigin for a user """ # Copy old session data session_old = {} for key, value in session.iteritems(): session_old[key] = value #log.debug('Copying session keys to secure session %s:%s' % (key,value)) # Destroy old session session.invalidate() # Instate new session with old vars under the new session id for key, value in session_old.iteritems(): session[key] = value session_set( 'logged_in_user', user.username ) # Set server session username so we know the actual user regardless of persona #session_set('logged_in_persona_path', user.id ) cookie_set("logged_in", "True", secure=False) user_log.info("logged in with %s" % login_provider) # Log user login
def log_in_user(user, remember, is_external_auth): """ Log a `User` in and update session and cookies. If `remember` is True, the session cookie is set to expire in a year; otherwise, it expires at the end of the browser session. Returns populated `AuthUser` object. """ user.update_lastlogin() meta.Session().commit() auth_user = AuthUser(dbuser=user, is_external_auth=is_external_auth) # It should not be possible to explicitly log in as the default user. assert not auth_user.is_default_user auth_user.is_authenticated = True # Start new session to prevent session fixation attacks. session.invalidate() session['authuser'] = cookie = auth_user.to_cookie() # If they want to be remembered, update the cookie. # NOTE: Assumes that beaker defaults to browser session cookie. if remember: t = datetime.datetime.now() + datetime.timedelta(days=365) session._set_cookie_expires(t) session.save() log.info('user %s is now authenticated and stored in ' 'session, session attrs %s', user.username, cookie) # dumps session attrs back to cookie session._update_cookie_out() return auth_user
def index(self): # redirect if already logged in c.came_from = request.GET.get('came_from') not_default = self.rhodecode_user.username != 'default' ip_allowed = self.rhodecode_user.ip_allowed if self.rhodecode_user.is_authenticated and not_default and ip_allowed: return redirect(url('home')) if request.POST: # import Login Form validator class login_form = LoginForm() try: session.invalidate() c.form_result = login_form.to_python(dict(request.POST)) # form checks for username/password, now we're authenticated username = c.form_result['username'] user = User.get_by_username(username, case_insensitive=True) auth_user = AuthUser(user.user_id) auth_user.set_authenticated() cs = auth_user.get_cookie_store() session['rhodecode_user'] = cs user.update_lastlogin() Session().commit() # If they want to be remembered, update the cookie if c.form_result['remember']: _year = (datetime.datetime.now() + datetime.timedelta(seconds=60 * 60 * 24 * 365)) session._set_cookie_expires(_year) session.save() log.info('user %s is now authenticated and stored in ' 'session, session attrs %s' % (username, cs)) # dumps session attrs back to cookie session._update_cookie_out() # we set new cookie headers = None if session.request['set_cookie']: # send set-cookie headers back to response to update cookie headers = [('Set-Cookie', session.request['cookie_out'])] allowed_schemes = ['http', 'https'] if c.came_from: parsed = urlparse.urlparse(c.came_from) server_parsed = urlparse.urlparse(url.current()) if parsed.scheme and parsed.scheme not in allowed_schemes: log.error( 'Suspicious URL scheme detected %s for url %s' % (parsed.scheme, parsed)) c.came_from = url('home') elif server_parsed.netloc != parsed.netloc: log.error('Suspicious NETLOC detected %s for url %s' 'server url is: %s' % (parsed.netloc, parsed, server_parsed)) c.came_from = url('home') raise HTTPFound(location=c.came_from, headers=headers) else: raise HTTPFound(location=url('home'), headers=headers) except formencode.Invalid, errors: return htmlfill.render( render('/login.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8")
def index(self): # redirect if already logged in c.came_from = request.GET.get('came_from') not_default = self.rhodecode_user.username != 'default' ip_allowed = self.rhodecode_user.ip_allowed if self.rhodecode_user.is_authenticated and not_default and ip_allowed: return redirect(url('home')) if request.POST: # import Login Form validator class login_form = LoginForm() try: session.invalidate() c.form_result = login_form.to_python(dict(request.POST)) # form checks for username/password, now we're authenticated username = c.form_result['username'] user = User.get_by_username(username, case_insensitive=True) auth_user = AuthUser(user.user_id) auth_user.set_authenticated() cs = auth_user.get_cookie_store() session['rhodecode_user'] = cs user.update_lastlogin() Session().commit() # If they want to be remembered, update the cookie if c.form_result['remember']: _year = (datetime.datetime.now() + datetime.timedelta(seconds=60 * 60 * 24 * 365)) session._set_cookie_expires(_year) session.save() log.info('user %s is now authenticated and stored in ' 'session, session attrs %s' % (username, cs)) # dumps session attrs back to cookie session._update_cookie_out() # we set new cookie headers = None if session.request['set_cookie']: # send set-cookie headers back to response to update cookie headers = [('Set-Cookie', session.request['cookie_out'])] allowed_schemes = ['http', 'https'] if c.came_from: parsed = urlparse.urlparse(c.came_from) server_parsed = urlparse.urlparse(url.current()) if parsed.scheme and parsed.scheme not in allowed_schemes: log.error( 'Suspicious URL scheme detected %s for url %s' % (parsed.scheme, parsed)) c.came_from = url('home') elif server_parsed.netloc != parsed.netloc: log.error('Suspicious NETLOC detected %s for url %s' 'server url is: %s' % (parsed.netloc, parsed, server_parsed)) c.came_from = url('home') raise HTTPFound(location=c.came_from, headers=headers) else: raise HTTPFound(location=url('home'), headers=headers) except formencode.Invalid, errors: return htmlfill.render( render('/login.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8") except UserCreationError, e: # container auth or other auth functions that create users on # the fly can throw this exception signaling that there's issue # with user creation, explanation should be provided in # Exception itself h.flash(e, 'error')
def delete(self): session.invalidate() redirect(url("main"))
def __before__(self): # If this is a multiple call to base then abort # Result is always set, so if it is not set then we know this is first call # This is needed because methods like member_actions.py:groups calls members.py:index. This would trigger 2 calls to base if hasattr(c, 'result'): return # AllanC - useful for debug #from pylons import session #print "" #print "CALL" #print request.environ.get("pylons.routes_dict") #print "GET" #print request.GET #print "POST" #print request.POST #print "SESSION" #print session #print "COOKIES" #print request.cookies # Setup globals variables ---------------------------------------------- c.result = action_ok() # Default return object # Request global - have the system able to easly view request details as globals current_request = request.environ.get("pylons.routes_dict") c.controller = current_request.get("controller") c.action = current_request.get("action") c.id = current_request.get("id") #print "controller=%s action=%s id=%s" % (c.controller, c.action, c.id) c.format = current_request.get("format") or "html" c.subformat = get_subdomain_format() c.auto_format_top_call = False # Used as a flag to the auto_formatter to only output the top level decorator c.authenticated_form = None # if we want to call a controler action internaly from another action we get errors because the auth_token is delted, this can be set by the authenticated_form decorator so we allow subcall requests c.web_params_to_kwargs = None c.html_action_fallback_url = None # Some actions like 'follow' and 'accept' do not have templates - a fallback can be set and @auto_format interperits this as a redirect fallback c.host = request.environ.get('HTTP_HOST', request.environ.get('SERVER_NAME')) c.etag_master_generated = False request.environ['app_version'] = app_globals.version request.environ['node_name'] = platform.node() # Detect and redirect to mobile ---------------------------------------- # # For development we cant fake a subdomain call when acessing 127.0.0.1 :( # In the same way as we toggle_cache we can toogle_force_mobile # or # We detect that the host is an ip address and enable mobile subdomain if mobile if request.environ.get('is_mobile') and request.environ.get("HTTP_HOST", "").replace(".","").isdigit(): log.debug('local mobile detected - auto mobile subdomain') c.subformat = 'mobile' elif cookie_get("force_mobile") and not cookie_get('force_web'): log.debug('force_mobile cookie present') c.subformat = 'mobile' # If we are not forcing mobile - attempt to redirect first time mobile viewers to the correct subdomain # Redirect to mobile site if needed if not cookie_get("force_mobile") and cookie_get('force_web') and c.subformat=='mobile': # If user is forcing m. then remove the force_web cookie log.debug('removing force_web cookie') cookie_delete('force_web') if c.format=='html' and c.subformat=='web' and request.environ.get('is_mobile') and not cookie_get('force_web') and request.environ['REQUEST_METHOD']=='GET': mobile_url = url('current', sub_domain='m', **request.GET) log.debug('redirecting mobile user to %s' % mobile_url) redirect(mobile_url) # Widget default settings ---------------------------------------------- widget_theme = request.params.get(config['setting.widget.var_prefix']+'theme') if widget_theme not in widget_defaults: widget_theme = config['setting.widget.default_theme'] c.widget = dict(widget_defaults[widget_theme]) if get_subdomain_format() == 'widget': setup_widget_env() c.widget['theme'] = widget_theme # Set the widget theme to the one requested (this is needed because theme 'light' could be set, it does not exist so gets 'basic', then overwrites theme with 'light' again from set_env) # Log out if missing logged_in ------------------------------- # The cache is active if logged_in is false. If the cookie is # missing (deleted, expired, something else) but the main session cookie # is still there then caching could activate by accident. As such, if # the logged_in cookie is missing, force a logout. if session_get('logged_in_user') and not request.cookies.get("logged_in"): log.warning("logged_in_user is set, but logged_in is missing") session.invalidate() # Login ---------------------------------------------------------------- # Fetch logged in user from session id (if present) login_session_fields = ['logged_in_user', 'logged_in_persona', 'logged_in_persona_path', 'logged_in_persona_role'] logged_in = {} for field in login_session_fields: logged_in[field] = session_get(field) setattr(c, field, logged_in[field]) c.logged_in_user = _get_member(logged_in['logged_in_user']) c.logged_in_persona = c.logged_in_user if c.logged_in_user and not c.logged_in_persona_role: c.logged_in_persona_role = 'admin' if logged_in['logged_in_user'] != logged_in['logged_in_persona']: group_persona = _get_group(logged_in['logged_in_persona']) if group_persona: # and group_persona.id == c.logged_in_persona_path[-1]: #Wanted to double check group permissions matched the group being set role = get_lowest_role_for_user() if role: c.logged_in_persona = group_persona c.logged_in_persona_role = role # Set Env - In the event of a server error these will be visable for field in login_session_fields: request.environ[field] = str(getattr(c, field)) #print request.environ[field] if c.logged_in_user: request.environ['logged_in_user_email'] = c.logged_in_user.email_normalized # Setup Langauge ------------------------------------------------------- # - there is a way of setting fallback langauges, investigate? if 'lang' in request.params: _lang = request.params['lang'] # If lang set in URL session_set('lang', request.params['lang']) elif session_get('lang'): _lang = session_get('lang') # Lang set for this users session #elif c.logged_in_persona has lang: # self._set_lang(c.logged_in_persona.?) # Lang in user preferences #elif request.environ.get("Accept-Language"): # langs = request.environ.get("Accept-Language").split(";")[0] # for lang in langs: # ... else: _lang = config['lang'] # Default lang in config file try: set_lang(_lang) formencode.api.set_stdtranslation(domain="civicboom", languages=[_lang]) c.lang = _lang # only do this if the above succeeded except Exception: # LanguageError pass # User pending regisration? -------------------------------------------- # redirect to complete registration process if c.logged_in_user and c.logged_in_user.status == 'pending' and deny_pending_user(url('current')): set_flash_message(_('Please complete the registration process')) try: redirect(url(controller='register', action='new_user', id=c.logged_in_user.id)) except RedirectException as e: abort(403, detail='user_registration_incomplete') # Session Flash Message ------------------------------------------------ flash_message_session = session_remove('flash_message') if flash_message_session: try: overlay_status_message(c.result, json.loads(flash_message_session)) except ValueError: overlay_status_message(c.result, flash_message_session )