def __call__(self): oauthWorkFlow = OauthWorkFlow(oauthServerName="twitter") client_id, client_secret, scope, redirect_uri = oauthWorkFlow.getRegistryValue( ) scope = scope.split(',') code = getattr(self.request, 'code', None) twitter = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scope) if code == None: if hasattr(self.request, 'error'): self.request.response.redirect("/") return authorization_url, state = twitter.authorization_url( self.authorization_base_url) self.request.response.redirect(authorization_url) return user = oauthWorkFlow.getUserInfo(twitter, self.token_url, client_secret, code, self.getUrl).json() # check has id, if True, is a relogin user, if False, is a new user userid = safe_unicode("gg%s") % user["id"] if api.user.get(userid=userid) is not None: self.context.acl_users.session._setupSession( userid.encode("utf-8"), self.context.REQUEST.RESPONSE) self.request.RESPONSE.redirect("/") # notify event hander userObject = api.user.get(userid=userid) notify(UserLoggedInEvent(userObject)) return userInfo = dict( fullname=safe_unicode(user.get("name", "")), location=safe_unicode(user.get("locale", "")), fbGender=safe_unicode(user.get("gender", "")), home_page=safe_unicode(user.get("link", "")), family_name=safe_unicode(user.get("family_name", "")), picture=safe_unicode(user.get("picture", "")), verified_email=safe_unicode(user.get("verified_email", False)), ) oauthWorkFlow.createUser(userid, safe_unicode((user.get("email", ""))), userInfo) self.context.acl_users.session._setupSession( userid.encode("utf-8"), self.context.REQUEST.RESPONSE) self.request.RESPONSE.redirect("/") # notify event hander userObject = api.user.get(userid=userid) notify(UserLoggedInEvent(userObject)) return
def _loginUser(self, login): """Handle login for the given user """ mtool = getToolByName(self, 'portal_membership') user = mtool.getUser(login) member = mtool.getMemberById(login) # Set login times first_login = False default = DateTime('2000/01/01') login_time = member.getProperty('login_time', default) if login_time == default: first_login = True login_time = DateTime() member.setMemberProperties( dict(login_time=mtool.ZopeTime(), last_login_time=login_time)) # Fire login event if first_login: event.notify(UserInitialLoginInEvent(user)) else: event.notify(UserLoggedInEvent(user)) # Expire the clipboard if self.REQUEST.get('__cp', None) is not None: self.REQUEST.RESPONSE.expireCookie('__cp', path='/') # Create member area mtool.createMemberArea(member_id=login)
def __call__(self): portal = api.portal.get() oauthWorkFlow = OauthWorkFlow(oauthServerName="facebook") client_id, client_secret, scope, redirect_uri = oauthWorkFlow.getRegistryValue( ) code = getattr(self.request, 'code', None) facebook = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scope) facebook = facebook_compliance_fix(facebook) if code == None: if hasattr(self.request, 'error'): self.request.response.redirect("/") return authorization_url, state = facebook.authorization_url( self.authorization_base_url) self.request.response.redirect(authorization_url) return user = oauthWorkFlow.getUserInfo(facebook, self.token_url, client_secret, code, self.getUrl).json() # check has id, if True, is a relogin user, if False, is a new user userid = safe_unicode("fb%s") % user["id"] if api.user.get(userid=userid) is not None: self.context.acl_users.session._setupSession( userid.encode("utf-8"), self.context.REQUEST.RESPONSE) self.request.RESPONSE.redirect("%s?auth" % portal.absolute_url()) # notify event hander userObject = api.user.get(userid=userid) notify(UserLoggedInEvent(userObject)) return userInfo = dict( fullname=safe_unicode(user.get("name", "")), description=safe_unicode(user.get("about", "")), location=safe_unicode(user.get("locale", "")), fbGender=safe_unicode(user.get("gender", "")), home_page=safe_unicode(user.get("link", "")), ) oauthWorkFlow.createUser(userid, safe_unicode((user.get("email", ""))), userInfo) self.context.acl_users.session._setupSession( userid.encode("utf-8"), self.context.REQUEST.RESPONSE) self.request.RESPONSE.redirect("%s?auth" % portal.absolute_url()) # notify event hander userObject = api.user.get(userid=userid) notify(UserLoggedInEvent(userObject)) return
def test_user_login(self): event = UserLoggedInEvent(self.request) with LogCapture('collective.fingerpointing', level=INFO) as log: notify(event) log.check( ('collective.fingerpointing', 'INFO', 'user=test_user_1_ ip=None action=login '), # noqa: E501 )
def loginUser(self, REQUEST=None): """ Handle a login for the current user. This method takes care of all the standard work that needs to be done when a user logs in: - clear the copy/cut/paste clipboard - PAS credentials update - sending a logged-in event - storing the login time - create the member area if it does not exist """ user = getSecurityManager().getUser() if user is None: return res = self.setLoginTimes() if res: event.notify(UserInitialLoginInEvent(user)) else: event.notify(UserLoggedInEvent(user)) if REQUEST is None: REQUEST = getattr(self, 'REQUEST', None) if REQUEST is None: return # Expire the clipboard if REQUEST.get('__cp', None) is not None: REQUEST.RESPONSE.expireCookie('__cp', path='/') # import pdb # pdb.set_trace() self.createMemberArea() try: pas = getToolByName(self, 'acl_users') pas.credentials_cookie_auth.login() if res: event.notify(MemberAreaCreatedEvent(user)) #set the cookie __ac so that client can remember it myresponse = REQUEST.RESPONSE if getattr(REQUEST, "ac_persistent", None): cookiename = '__ac' cookie = myresponse.cookies.get(cookiename) if cookie: cookievalue = cookie.pop('value') new_date = DateTime() + 7 cookie['expires'] = new_date.strftime( "%a, %d-%h-%y %H:%m:%S GMT+8") myresponse.setCookie(cookiename, cookievalue, **cookie) except AttributeError: # The cookie plugin may not be present pass try: pass # event.notify(AddloginlogsEvent(user)) except AttributeError: pass
def test_new_user(self): username = '******' member = api.user.create(email='*****@*****.**', username=username) login(self.portal, username) event.notify(UserLoggedInEvent(member)) brains = api.portal.get_tool('membrane_tool').searchResults() self.assertEqual(len(brains), 1) obj = brains[0].getObject() self.assertIsInstance(getattr(obj, 'last_sync', None), datetime)
def test_susbcriber_ignored_when_package_not_installed(self): # authentication events should not raise errors # if package is not installed self.uninstall() # BBB: QI compatibility event = UserLoggedInEvent(self.request) notify(event) event = UserLoggedOutEvent(self.request) notify(event) event = PrincipalCreated('foo') notify(event) event = PrincipalDeleted('foo') notify(event)
def login_user(self, userid, properties): uf = getToolByName(self.context, 'acl_users') mtool = getToolByName(self, 'portal_membership') member = mtool.getMemberById(userid) settings = self.sp_settings() if member is None and settings.autoprovision_users: plugins = uf._getOb('plugins') enumerators = plugins.listPlugins(IUserEnumerationPlugin) plugin = None for id_, enumerator in enumerators: if enumerator.meta_type == "collective.saml2auth plugin": plugin = enumerator break if plugin is None: logger.warning( 'Missing PAS plugin. Cannot autoprovision user %s.' % userid) return plugin.addUser(userid) member = mtool.getMemberById(userid) # Setup session uf.updateCredentials(self.request, self.request.response, userid, '') # Update login times and other member properties first_login = False default = DateTime('2000/01/01') login_time = member.getProperty('login_time', default) if login_time == default: first_login = True login_time = DateTime() member.setMemberProperties( dict(login_time=mtool.ZopeTime(), last_login_time=login_time, **properties)) # Fire login event user = member.getUser() if first_login: event.notify(UserInitialLoginInEvent(user)) else: event.notify(UserLoggedInEvent(user)) # Expire the clipboard if self.request.get('__cp', None) is not None: self.request.response.expireCookie('__cp', path='/') # Create member area mtool.createMemberArea(member_id=userid)
def login(self, account, remember): pas = getToolByName(self.context, "acl_users") pas.updateCredentials( self.request, self.request.RESPONSE, account.loginname, account.password, ) notify(UserLoggedInEvent(account)) if remember: self.request.RESPONSE.cookies["__ac"][ "expires"] = cookie_expiration_date(120) # noqa: E501 self.request.RESPONSE.cookies["__ac"]["max_age"] = ( 120 * 24 * 60 * 60) # noqa: E501
def authenticate(self, username=None, password=None, country=None): """ return true if successfull """ if not self.is_zope_root: manager = LockoutManager(self.context, username) if manager.maxed_number_of_attempts(): raise AuthenticationMaxedLoginAttempts() manager.add_attempt() for acl_users in self.get_acl_users(): # if not root, could be more than one to check against user = acl_users.authenticate(username, password, self.request) if user: break if user is None: return False, user if not self.is_zope_root: manager.clear() if user.getRoles() == ['Authenticated']: raise AuthenticationUserDisabled() if self.registry: allowed_countries = self.registry.get( 'plone.restrict_logins_to_countries') if allowed_countries and country: if country not in allowed_countries: if not self.country_exception_granted(user.getId()): raise AuthenticationCountryBlocked() if not self.is_zope_root: member = api.user.get(user.getId()) reset_password = member.getProperty( 'reset_password_required', False) reset_time = member.getProperty('reset_password_time', None) if reset_password and reset_time: if reset_time + (24 * 60 * 60) < time.time(): raise AuthenticationPasswordResetWindowExpired() acl_users.session._setupSession(user.getId(), self.request.response) notify(UserLoggedInEvent(user)) return True, user
def test_susbcriber_ignored_when_package_not_installed(self): # authentication events should not raise errors # if package is not installed portal = self.layer['portal'] qi = portal['portal_quickinstaller'] with api.env.adopt_roles(['Manager']): qi.uninstallProducts(products=[PROJECTNAME]) event = UserLoggedInEvent(self.request) notify(event) event = UserLoggedOutEvent(self.request) notify(event) event = PrincipalCreated('foo') notify(event) event = PrincipalDeleted('foo') notify(event)
def __call__(self): context = self.context request = self.request portal = api.portal.get() if not api.user.is_anonymous(): request.response.redirect(portal.absolute_url()) return if request.form: user = self.registryAccount(request) if user: context.acl_users.session._setupSession(user.id, context.REQUEST.RESPONSE) request.response.redirect(portal.absolute_url()) notify(UserLoggedInEvent(user)) request.response.redirect(portal.absolute_url()) return self.template()
def __call__(self): context = self.context request = self.request portal = api.portal.get() url = RECAPTCHA_URL data = urllib.urlencode({ 'secret': RECAPTCHA_SECRET, 'response': request.form.get('g-recaptcha-response'), }) req = urllib2.Request(url, data) response = urllib2.urlopen(req) recaptResult = response.read() if json.loads(recaptResult).get('success'): userId = request.form.get('member_id') userPwd = request.form.get('member_pwd') conn = ENGINE.connect() execStr = "select password from member where userId = '%s'" % userId query = conn.execute(execStr) result = query.fetchall() # 登入失敗:f, 成功:s if not result: request.response.redirect('%s/members/@@member_login_menu?r=f' % portal.absolute_url()) return pwd = result[0][0] if userPwd == pwd: # 登入成功 self.context.acl_users.session._setupSession(userId.encode("utf-8"), self.context.REQUEST.RESPONSE) request.response.redirect('%s?auth' % portal.absolute_url()) userObject = api.user.get(userid=userId) notify(UserLoggedInEvent(userObject)) else: request.response.redirect('%s/members/@@member_login_menu?r=f' % portal.absolute_url()) conn.close() return else: request.response.redirect('%s/members/@@member_login_menu?r=f' % portal.absolute_url()) return return
def _auto_login(self, userid, password): aclu = getToolByName(self.context, 'acl_users') for name, plugin in aclu.plugins.listPlugins(ICredentialsUpdatePlugin): plugin.updateCredentials(self.request, self.request.response, userid, password) user = getSecurityManager().getUser() login_time = user.getProperty('login_time', None) if login_time is None: notify(UserInitialLoginInEvent(user)) else: notify(UserLoggedInEvent(user)) IStatusMessage(self.request).addStatusMessage( _( 'password_reset_successful', default='Password reset successful, ' 'you are logged in now!', ), 'info', ) url = INavigationRoot(self.context).absolute_url() self.request.response.redirect(url) return
def loginUser(self, REQUEST=None): """ Handle a login for the current user. This method takes care of all the standard work that needs to be done when a user logs in: - clear the copy/cut/paste clipboard - PAS credentials update - sending a logged-in event - storing the login time - create the member area if it does not exist """ user = getSecurityManager().getUser() if user is None: return if self.setLoginTimes(): event.notify(UserInitialLoginInEvent(user)) else: event.notify(UserLoggedInEvent(user)) if REQUEST is None: REQUEST = getattr(self, 'REQUEST', None) if REQUEST is None: return # Expire the clipboard if REQUEST.get('__cp', None) is not None: REQUEST.RESPONSE.expireCookie('__cp', path='/') self.createMemberArea() try: pas = getToolByName(self, 'acl_users') pas.credentials_cookie_auth.login() except AttributeError: # The cookie plugin may not be present pass
def authenticate(self, username=None, password=None, country=None, login=True): """return true if successfull login: if a successful authentication should result in the user being logged in """ if not self.is_zope_root: manager = LockoutManager(self.context, username) if manager.maxed_number_of_attempts(): raise AuthenticationMaxedLoginAttempts() manager.add_attempt() for acl_users in self.get_acl_users(): # if not root, could be more than one to check against user = acl_users.authenticate(username, password, self.request) if user: break if user is None: return False, user if not self.is_zope_root: manager.clear() if user.getRoles() == ['Authenticated']: raise AuthenticationUserDisabled() if self.registry: allowed_countries = self.registry.get( 'plone.restrict_logins_to_countries') if allowed_countries and country: if country not in allowed_countries: if not self.country_exception_granted(user.getId()): raise AuthenticationCountryBlocked() if not self.is_zope_root: member = api.user.get(user.getId()) reset_password = member.getProperty('reset_password_required', False) reset_time = member.getProperty('reset_password_time', None) if reset_password and reset_time: if reset_time + (24 * 60 * 60) < time.time(): raise AuthenticationPasswordResetWindowExpired() if login: acl_users.session._setupSession(user.getId(), self.request.response) try: notify(UserLoggedInEvent(user)) except ConnectionStateError: # On root login, it's possible no db state # is loaded but the key ring needs to be rotated. # This can cause an difficult to reproduce error. # Really, we don't care so much if we see this # error here. It'll get rotated another time. pass return True, user
def fire_login_event(self, member): user = member.getUser() if self.first_login: event.notify(UserInitialLoginInEvent(user)) else: event.notify(UserLoggedInEvent(user))
def loginUser(self, REQUEST=None): """ Handle a login for the current user. This method takes care of all the standard work that needs to be done when a user logs in: - clear the copy/cut/paste clipboard - PAS credentials update - sending a logged-in event - storing the login time - create the member area if it does not exist """ user = getSecurityManager().getUser() if user is None: return try: home = self.getHomeFolder(user.getId()) except: home = None res = self.setLoginTimes() res = res and not home loginEvent = NormalUserloginEvent( userid=getfullname_orid(user), datetime=datetime.datetime.now().strftime(fmt), ip=get_ip(), type=0, description="", result=1) if loginEvent.available(): if loginEvent.is_normal_user(): event.notify(loginEvent) else: loginEvent = AddloginEvent( adminid=getfullname_orid(user), userid=" ", datetime=datetime.datetime.now().strftime(fmt), ip=get_ip(), type=0, description="", result=1) event.notify(loginEvent) if res: event.notify(UserInitialLoginInEvent(user)) self.createMemberArea() event.notify(MemberAreaCreatedEvent(user)) else: event.notify(UserLoggedInEvent(user)) if REQUEST is None: REQUEST = getattr(self, 'REQUEST', None) if REQUEST is None: return # Expire the clipboard if REQUEST.get('__cp', None) is not None: REQUEST.RESPONSE.expireCookie('__cp', path='/') try: pas = getToolByName(self, 'acl_users') pas.credentials_cookie_auth.login() except AttributeError: # The cookie plugin may not be present pass
def fire_login_events(self, first_login, user): if first_login: notify(UserInitialLoginInEvent(user)) else: notify(UserLoggedInEvent(user))