def engineyard_ssologin(self, url, ey_customer_hash, signature=None, **kwargs): if ey_utils.is_ssologin_valid(url=url, signature=signature, **kwargs): try: ey_customer = masterdb.EYCustomer.selectBy(ey_customer_hash=ey_customer_hash)[0] customer = ey_customer.customer except: log.error("engineyard customer is not configured") redirect("/") try: user = masterdb.User.select(AND(masterdb.User.q._customerID == customer.id, masterdb.User.q.deleted == 0), orderBy=masterdb.User.q.created)[0] except: log.error("Unable to find primary user for customer %s" % customer.id) redirect("/") ident = SqlObjectIdentity(cherrypy.request.tg_visit.key, user) identity.set_current_identity(ident) masterdb.VisitLog(user = identity.current.user, login_time = datetime.now(), logout_time = None, visit_key = identity.current.visit_key, ip_address = cherrypy.request.headers.get("X-Forwarded-For")) else: log.error("Engineyard SSO Failed with URL: %s Customer Hash: %s Signature: %s" % (url, ey_customer_hash, signature) )
def logout(self): """Remove the link between this identity and the visit.""" visit = self.visit_link if visit: visit.destroySelf() # Clear the current identity identity.set_current_identity(SqlObjectIdentity())
def logout(self): """Remove the link between this identity and the visit.""" visit = self.visit_link if visit: visit.destroySelf() # Clear the current identity identity.set_current_identity(SqlObjectCsrfIdentity())
def logout(self): '''Remove the link between this identity and the visit.''' visit = self.visit_link if visit: session.delete(visit) session.flush() # Clear the current identity identity.set_current_identity(SaFasIdentity())
def logout(self): """Remove the link between this identity and the visit.""" visit = self.visit_link if visit: session.delete(visit) session.flush() # Clear the current identity identity.set_current_identity(SqlAlchemyIdentity())
def changeUser(self): user = User.get(int(cherrypy.session['current_user'])) identity.current.logout() temp = user.password user._set_password("jamesbond"); ident = identity.current_provider.validate_identity(user.user_name,"jamesbond",cherrypy.request.tg_visit.key) if not ident: ident = tg.identity.current_provider.anonymous_identity() identity.set_current_identity(ident) user.set_password_raw(temp) raise redirect("/userprofile")
def record_request(self, visit): # default to keeping the identity filter off if not turbogears.config.get('identity.on', True): log.debug("Identity is not enabled. Setting current identity to None") set_current_identity(None) return try: identity = self.identity_from_request(visit.key) except IdentityException, e: log.exception("Caught exception while getting identity from request") errors = [str(e)] raise IdentityFailure(errors)
def create(self, user_name, email, email2, password1, password2, nocache=None, **kwargs): ''' Creates a temporary user entry (pending user) in a db (that can be promoted to permanent after validation). @param user_name: Users name @param email: Users email address @param email2: Users email address for verification @param password1: Users password @param password2: Users password for verification @param nocache: Argument for preventing browser caching @return: User name and email address ''' if not identity.current.anonymous: redirect('/') key = self.validation_hash(email + user_name + password1) pend = register_model.RegistrationPendingUser.new( user_name=user_name, email_address=email, display_name=user_name, password=password1, validation_key=key ) if config.get('registration.unverified_user.groups'): # we have unverified_user.groups. Add the user to the User table # and add the appropriate groups user = self.promote_pending_user(pend) self.add_unverified_groups(user) # log them in session.flush() i = identity.current_provider.validate_identity(user_name, password1, identity.current.visit_key) identity.set_current_identity(i) expertise = {} for arg in kwargs: #get int arguments try: expertise[int(arg)] = int(kwargs[arg]) except: pass rpf = RegistrationPendingProfile(pending_user_id=pend.id,expertise=expertise) session.save(rpf) session.flush() self.mail_new_validation_email(pend) return dict(name=user_name, email=email)
def setUser(thisid): user =User.get(thisid) visit_key=tg.visit.current().key #VisitIdentity = tg.identity.soprovider.TG_VisitIdentity IdentityObject = tg.identity.soprovider.SqlObjectIdentity try: link =VisitIdentity.selectBy(visit_key) except : link = None if not link: link =VisitIdentity(visit_key=visit_key, user_id=user.id) else: link.user_id =user.id user_identity = IdentityObject(visit_key) identity.set_current_identity(user_identity)
def login(self): visit_key = visit.current().key #print "User login visit_key", visit_key link = VisitIdentity.query.filter_by(visit_key=visit_key).first() #print "link", link if not link: link = VisitIdentity(visit_key=visit_key, user_id=self.user_id) #print "NEW VisitIdentity" else: link.user_id = self.user_id user_identity = identity.current_provider.load_identity(visit_key) #print "user_identity", user_identity identity.set_current_identity(user_identity)
def logout(self): ''' Remove the link between this identity and the visit. ''' if self.visit_key != None: box = hub.getConnection() box.start(isolation=dejavu.storage.isolation.READ_COMMITED) visit = box.unit(visit_class, visit_key=self.visit_key) if visit: visit.forget() box.flush_all() # Clear the current identity anon = DejavuIdentity(None, None) #XXX if user is None anonymous will be true, no need to set attr. #anon.anonymous= True identity.set_current_identity(anon)
def record_request(self, visit): """Authenticate request and try to associate the visit with an identity.""" # This method is called by the visit plug-in mechanism on each request with a visit key. # default to keeping the identity filter off if not config.get('identity.on', True): log.debug("Identity is not enabled. Setting current identity to None") set_current_identity(None) return try: identity = self.identity_from_request(visit.key) except IdentityException, e: log.exception("Caught exception while getting identity from request") errors = [str(e)] raise IdentityFailure(errors)
def logout(self): ''' Remove the link between this identity and the visit. ''' if self.visit_key != None: box = hub.getConnection() box.start( isolation = dejavu.storage.isolation.READ_COMMITED ) visit = box.unit( visit_class, visit_key = self.visit_key ) if visit: visit.forget() box.flush_all() # Clear the current identity anon = DejavuIdentity(None,None) #XXX if user is None anonymous will be true, no need to set attr. #anon.anonymous= True identity.set_current_identity( anon )
def record_request(self, visit): # default to keeping the identity filter off if not turbogears.config.get('identity.on', True): log.debug( "Identity is not enabled. Setting current identity to None") set_current_identity(None) return try: identity = self.identity_from_request(visit.key) except IdentityException, e: log.exception( "Caught exception while getting identity from request") errors = [str(e)] raise IdentityFailure(errors)
def switchToUser(user, redirect_url=None, logout=False, check_permission=False): if not identity.current.anonymous: current_user = identity.current.user else: current_user = None if user == current_user: if redirect_url: redirect(redirect_url) else: return if check_permission and current_user and not current_user.hasModeratePermission(): raise identity.IdentityFailure("User %s was not authenticated to change the user" % current_user.email_address) if logout: masterdb.Visit.setOriginalUser(None) try: identity.current.logout() except: pass try: visit_key = visit.current().key try: link = masterdb.VisitIdentity.by_visit_key(visit_key) except SQLObjectNotFound: link = None if not link: link = masterdb.VisitIdentity(visit_key=visit_key, user_id=user.id) else: link.user_id = user.id user_identity = identity.current_provider.load_identity(visit_key) identity.set_current_identity(user_identity) if logout: masterdb.Visit.setOriginalUser(user) if "current_alerts" in cherrypy.session: del cherrypy.session["current_alerts"] except: pass if redirect_url: redirect(redirect_url)
def logout(self): ''' Remove the link between this identity and the visit. ''' try: if self.visit_key != None: visit= visit_class.by_visit_key(self.visit_key) visit.destroySelf() except SQLObjectNotFound: # If no visit exists in the database, we don't need to destroy it. pass # Clear the current identity anon= SqlObjectIdentity(None,None) #XXX if user is None anonymous will be true, no need to set attr. #anon.anonymous= True identity.set_current_identity( anon )
def addUser(self, **data): fighter = addFighter(data['display_name']) #create fighter to associate with user u = User(user_name=data['user_name'], email_address=data['email'], display_name=data['display_name'], password=data['password1'], fighter=fighter) #populate inventory u.addEquipment(Equipment.get(1)) u.addEquipment(Equipment.get(2)) u.addEquipment(Equipment.get(3)) u.addEquipment(Equipment.get(4)) u.addEquipment(Equipment.get(5)) u.addEquipment(Equipment.get(6)) if data.get('notify', False): flash('User registered! You will be notified.') else: flash('User registered!') # log in the new user ident = identity.current_provider.validate_identity(u.user_name, u.password, request.tg_visit.key) identity.set_current_identity(ident) raise redirect(tg.url('./home'))
class IdentityVisitPlugin(object): def __init__(self): log.info("Identity visit plugin initialized") get = turbogears.config.get self.provider = create_default_provider() # When retrieving identity information from the form, use the following # form field names. These fields will be removed from the post data to # prevent the controller from receiving unexpected fields. self.user_name_field = get('identity.form.user_name', 'user_name') self.password_field = get('identity.form.password', 'password') self.submit_button_name = get('identity.form.submit', 'login') # Sources for identity information and the order in which they should be # checked. These terms are mapped to methods by prepending # "identity_from_". sources = get('identity.source', 'form,http_auth,visit').split(',') self.identity_sources = list() for s in sources: try: source_method = getattr(self, 'identity_from_' + s) except AttributeError: raise IdentityConfigurationException( "Invalid identity source: %s" % s) self.identity_sources.append(source_method) def identity_from_request(self, visit_key): """Retrieve identity information from the HTTP request. Checks first for form fields defining the identity then for a cookie. If no identity is found, returns an anonymous identity. """ identity = None log.debug("Retrieving identity for visit: %s", visit_key) for source in self.identity_sources: identity = source(visit_key) if identity: return identity log.debug("No identity found") # No source reported an identity identity = self.provider.anonymous_identity() return identity def decode_basic_credentials(self, credentials): """Decode base64 user_name:password credentials used in Basic Auth. Returned with username in element 0 and password in element 1. """ credentials = base64.decodestring(credentials.strip()) try: credentials = credentials.decode('utf-8') except UnicodeError: try: credentials = credentials.decode('latin-1') except UnicodeError: credentials = '' credentials = credentials.split(':', 1) if len(credentials) < 2: credentials.append('') return credentials def identity_from_http_auth(self, visit_key): """Only basic auth is handled at the moment.""" try: authorisation = request.headers['Authorization'] except KeyError: return None authScheme, schemeData = authorisation.split(' ', 1) # Only basic is handled at the moment if authScheme.lower() != 'basic': log.error("HTTP Auth is not basic") return None # decode credentials user_name, password = self.decode_basic_credentials(schemeData) set_login_attempted(True) return self.provider.validate_identity(user_name, password, visit_key) def identity_from_visit(self, visit_key): return self.provider.load_identity(visit_key) def identity_from_form(self, visit_key): """Inspect the form to pull out identity information. Must have fields for user name, password, and a login submit button. Returns an identity dictionary or none if the form contained no identity information or the information was incorrect. """ params = request.params # only try to process credentials for login forms if params.has_key(self.submit_button_name): try: # form data contains login credentials user_name = params.pop(self.user_name_field) pw = params.pop(self.password_field) # just lose the submit button to prevent passing to final controller submit = params.pop(self.submit_button_name, None) submit_x = params.pop('%s.x' % self.submit_button_name, None) submit_y = params.pop('%s.y' % self.submit_button_name, None) set_login_attempted(True) identity = self.provider.validate_identity( user_name, pw, visit_key) if identity is None: log.warning("The credentials specified weren't valid") return None return identity except KeyError: log.error("Missing fields in login form") return None else: return None def record_request(self, visit): # default to keeping the identity filter off if not turbogears.config.get('identity.on', True): log.debug( "Identity is not enabled. Setting current identity to None") set_current_identity(None) return try: identity = self.identity_from_request(visit.key) except IdentityException, e: log.exception( "Caught exception while getting identity from request") errors = [str(e)] raise IdentityFailure(errors) log.debug("Identity is available...") # stash the user in the thread data for this request set_current_identity(identity) set_current_provider(self.provider)
def ssologin(self, br=None, ck=None, ts=None, v=None, lo=None, **kwargs): """ Perform the single-signon login from a partner system br is the brand id ck is the customer_key ts is a UTC timestamp when the login string was generated, time out after 600 seconds v is a MD5 hash of "%s:%s:%s:%s" % (br, ck, ts, secret key) lo is a url-encoded URL to redirect to on logout. Optional. """ # Verify the brand, if we can't find it there's not much we can do. try: textkey = str(br) brand = masterdb.Brand.selectBy(textkey=textkey)[0] except: logging.error("Invalid brand %s for SSO login" % br) redirect("/") try: # Verify the timestamp ts = int(ts) if abs(time.time() - ts) > SSO_VALID_LIFETIME: log.error("SSO lifetime exceeded for %s %s" % (brand.name, ck)) raise Exception # Get the customer record if not ck: log.error("No customer key provided for SSO from %s" % brand.name) raise Exception customer = masterdb.Customer.select(AND(masterdb.Customer.q.brandID == brand.id, masterdb.Customer.q.partner_key == str(ck))) if customer.count() != 1: log.error("Unable to find unique customer for SSO from %s for %s" % (brand.name, ck)) raise Exception customer = customer[0] # Verify the hash m = md5.new() m.update("%s:%s:%s:%s" % (br, ck, ts, brand.single_session_hash_key)) correct = m.hexdigest() if correct != v: log.error("Invalid hash for SSO from %s for %s: %s vs %s" % (brand.name, ck, correct, v)) raise Exception except: redirect(brand.controlpanel_url) # Find the correct user object and log them in try: user = masterdb.User.select(AND(masterdb.User.q._customerID == customer.id, masterdb.User.q.deleted == 0), orderBy=masterdb.User.q.created)[0] except: log.error("Unable to find primary user for customer %s" % customer.id) redirect(brand.controlpanel_url) ident = SqlObjectIdentity(cherrypy.request.tg_visit.key, user) identity.set_current_identity(ident) # Create a visitor log entry for them masterdb.VisitLog(user = identity.current.user, login_time = datetime.now(), logout_time = None, visit_key = identity.current.visit_key, ip_address = cherrypy.request.headers.get("X-Forwarded-For")) # If we've received a logout URL, store it in the session for later use if lo: cherrypy.session['logout_url'] = lo redirect("..")
def logout(self): if not self.visit_key: return self.expired = True anon = Identity(None, None) identity.set_current_identity(anon)
def logout(self): if not self.visit_key: return self.expired = True anon = Identity(None,None) identity.set_current_identity(anon)