def sso(id): log.info('SSO for organization "%s"' % id) session['organization_id'] = id session.save() log.info('redirecting to login page') login_url = url_for('ozwillo-pyoidc.ozwillo_login') return ozwillo_login()
def logged_in(self): # we need to set the language via a redirect lang = session.pop('lang', None) session.save() came_from = request.params.get('came_from', '') # we need to set the language explicitly here or the flash # messages will not be translated. i18n.set_lang(lang) if c.user: context = None data_dict = {'id': c.user} user_dict = get_action('user_show')(context, data_dict) h.flash_success(_("%s is now logged in") % user_dict['display_name']) if came_from: return h.redirect_to(str(came_from)) return self.me() else: err = _('Login failed. Bad username or password.') if g.openid_enabled: err += _(' (Or if using OpenID, it hasn\'t been associated ' 'with a user account.)') if h.asbool(config.get('ckan.legacy_templates', 'false')): h.flash_error(err) h.redirect_to(locale=lang, controller='user', action='login', came_from=came_from) else: return self.login(error=err)
def login(self, error=None): lang = session.pop('lang', None) if lang: session.save() return h.redirect_to(locale=str(lang), controller='user', action='login') # Do any plugin login stuff for item in p.PluginImplementations(p.IAuthenticator): item.login() if 'error' in request.params: h.flash_error(request.params['error']) if request.environ['SCRIPT_NAME'] and g.openid_enabled: # #1662 restriction log.warn('Cannot mount CKAN at a URL and login with OpenID.') g.openid_enabled = False if not c.user: came_from = request.params.get('came_from', '') c.login_handler = h.url_for( self._get_repoze_handler('login_handler_path'), came_from=came_from) if error: vars = {'error_summary': {'': error}} else: vars = {} return render('user/login.html', extra_vars=vars) else: return render('user/logout_first.html')
def ozwillo_login(): for cookie in request.cookies: value = request.cookies.get(cookie) Response().set_cookie(cookie, value, secure=True, httponly=True) if 'organization_id' in session: g_ = model.Group.get(session['organization_id']) client = Clients.get_client(g_) url, ht_args, state = client.create_authn_request(conf.ACR_VALUES) session['state'] = state session['from_login'] = True session.save() if ht_args: request.headers.update(ht_args) # Redirect URI should not include language info init. # Returns: `invalid_request: Invalid parameter value: redirect_uri` url = url.replace('en%2F', '').replace('en/', '') return redirect_to(url) else: return redirect_to('/') extra_vars = {} if g.user: return base.render(u'user/logout_first.html', extra_vars) came_from = request.params.get(u'came_from') if not came_from: came_from = h.url_for(u'user.logged_in') g.login_handler = h.url_for(_get_repoze_handler(u'login_handler_path'), came_from=came_from) return base.render(u'user/login.html', extra_vars)
def identify(self): if 'emailauth_user' in session: tk.c.user = session['emailauth_user'] return if 'login' not in tk.request.GET: # Not a login request return # Digest the login key src_email = urllib.unquote(tk.request.GET['email']) to_digest = (tk.request.GET['login'] + src_email).encode('utf-8') key = hashlib.sha256(to_digest).hexdigest() # Clear expired and pop db.AutoLoginKey.remove_expired(expiry_hrs=tk.config.get( 'ckan.emailauth.login_key_expiry_hrs', 48)) user_id = db.AutoLoginKey.pop_key(key=key, src_email=src_email) if user_id is None: # Invalid log.warn('Auto login key miss with email %s' % src_email) session['emailauth_fail'] = True session.save() tk.redirect_to(tk.url_for(controller='user', action='login')) else: # Valid user_name = model.Session.query( model.User).filter(model.User.id == user_id).first().name session['emailauth_user'] = user_name session.save() tk.c.user = user_name
def logged_in(self): # we need to set the language via a redirect lang = session.pop('lang', None) session.save() came_from = request.params.get('came_from', '') # we need to set the language explicitly here or the flash # messages will not be translated. i18n.set_lang(lang) if c.user: context = None data_dict = {'id': c.user} user_dict = get_action('user_show')(context, data_dict) h.flash_success( _("%s is now logged in") % user_dict['display_name']) if came_from: return h.redirect_to(str(came_from)) return self.me() else: err = _('Login failed. Bad username or password.') if g.openid_enabled: err += _(' (Or if using OpenID, it hasn\'t been associated ' 'with a user account.)') if h.asbool(config.get('ckan.legacy_templates', 'false')): h.flash_error(err) h.redirect_to(locale=lang, controller='user', action='login', came_from=came_from) else: return self.login(error=err)
def callback(self): try: token = self.oauth2helper.get_token() user_name = self.oauth2helper.identify(token) self.oauth2helper.remember(user_name) self.oauth2helper.update_token(user_name, token) self.oauth2helper.redirect_from_callback() except Exception as e: session.save() # If the callback is called with an error, we must show the message error_description = toolkit.request.GET.get('error_description') if not error_description: if e.message: error_description = e.message elif hasattr(e, 'description') and e.description: error_description = e.description elif hasattr(e, 'error') and e.error: error_description = e.error else: error_description = type(e).__name__ toolkit.response.status_int = 302 redirect_url = oauth2.get_came_from(toolkit.request.params.get('state')) redirect_url = '/' if redirect_url == constants.INITIAL_PAGE else redirect_url toolkit.response.location = redirect_url helpers.flash_error(error_description)
def login(self): params = toolkit.request.params if 'id_token' in params: try: mail_verified = self.verify_email(params["id_token"]) except GoogleAuthException, e: toolkit.abort(500) user_account = email_to_ckan_user(mail_verified) user_ckan = self.get_ckanuser(user_account) if not user_ckan: user_ckan = toolkit.get_action('user_create')( context={ 'ignore_auth': True }, data_dict={ 'email': mail_verified, 'name': user_account, 'password': self.get_ckanpasswd() }) session['ckanext-google-user'] = user_ckan['name'] session['ckanext-google-email'] = mail_verified #to revoke the Google token uncomment the code below session['ckanext-google-accesstoken'] = params['token'] session.modified = True session.save() self.identify()
def identify(self): log.debug('identify') # Create session if it does not exist. Workaround to show flash messages session.save() def _refresh_and_save_token(user_name): new_token = self.oauth2helper.refresh_token(user_name) if new_token: toolkit.c.usertoken = new_token environ = toolkit.request.environ apikey = toolkit.request.headers.get(self.authorization_header, '') user_name = None # This API Key is not the one of CKAN, it's the one provided by the OAuth2 Service if apikey: try: token = {'access_token': apikey} user_name = self.oauth2helper.identify(token) except Exception: pass # If the authentication via API fails, we can still log in the user using session. if user_name is None and 'repoze.who.identity' in environ: user_name = environ['repoze.who.identity']['repoze.who.userid'] log.info('User %s logged using session' % user_name) # If we have been able to log in the user (via API or Session) if user_name: toolkit.c.user = user_name toolkit.c.usertoken = self.oauth2helper.get_stored_token(user_name) # toolkit.c.usertoken_refresh = partial(_refresh_and_save_token, user_name) else: log.warn('The user is not currently logged...')
def callback(self): try: token = self.oauth2helper.get_token() user_name = self.oauth2helper.identify(token) self.oauth2helper.remember(user_name) self.oauth2helper.update_token(user_name, token) self.oauth2helper.redirect_from_callback() except Exception as e: session.save() # If the callback is called with an error, we must show the message error_description = toolkit.request.GET.get('error_description') if not error_description: if e.message: error_description = e.message elif hasattr(e, 'description') and e.description: error_description = e.description elif hasattr(e, 'error') and e.error: error_description = e.error else: error_description = type(e).__name__ toolkit.response.status_int = 302 redirect_url = oauth2.get_came_from( toolkit.request.params.get('state')) redirect_url = '/' if redirect_url == constants.INITIAL_PAGE else redirect_url toolkit.response.location = redirect_url helpers.flash_error(error_description)
def login(self, error=None): lang = session.pop('lang', None) if lang: session.save() return h.redirect_to(locale=str(lang), controller='user', action='login') if 'error' in request.params: h.flash_error(request.params['error']) if request.environ['SCRIPT_NAME'] and g.openid_enabled: # #1662 restriction log.warn('Cannot mount CKAN at a URL and login with OpenID.') g.openid_enabled = False if not c.user: came_from = request.params.get('came_from', '') c.login_handler = h.url_for( self._get_repoze_handler('login_handler_path'), came_from=came_from) if error: vars = {'error_summary': {'': error}} else: vars = {} return render('user/login.html', extra_vars=vars) else: return render('user/logout_first.html')
def send_user_message(self): body = {} try: request_body = json.loads(request.body) except Exception: # Didn't get appropriate JSON format bot_response = "Inappropriate body format - body must be application/json" logger.info(bot_response) body["bot"] = bot_response body["error"] = True response.body = json.dumps(body) return if not session.get("sender_id"): session["sender_id"] = session.id session.save() sender_id = session["sender_id"] message = request_body["text"] version_connector = VersionConnector() if not version_connector.query_rasa(): body["bot"] = ["Rasa server is down"] body["error"] = True else: bot_response = self.rasa_handle_message(message, sender_id) # Returns a list of responses if not bot_response: body["error"] = True bot_response ={ "type": "string", "data" : "DataBot didn't get any response. DataBot server is probably down." } body["bot"] = bot_response response.body = json.dumps(body) return
def identify(self): # Handle auth. for the first session if 'saabreg_new_user' in session: tk.c.user = session['saabreg_new_user'] session['saabreg_user'] = session['saabreg_new_user'] del session['saabreg_new_user'] session.save() elif 'saabreg_user' in session: tk.c.user = session['saabreg_user']
def after_update(self, context, pkg_dict): is_suitable = twitter_helpers.twitter_pkg_suitable( context, pkg_dict['id']) print is_suitable if is_suitable: session.setdefault('twitter_is_suitable', pkg_dict['id']) session.save()
def sso(self, id): log.info('SSO for organization "%s"' % id) session['organization_id'] = id session.save() log.info('redirecting to login page') login_url = toolkit.url_for(host=request.host, controller='user', action='login', qualified=True) redirect_to(login_url)
def login_success(user_name, came_from): '''Handle login success Saves the user in the session and redirects to user/logged_in :param user_name: The user name ''' session[u'ckanext-ldap-user'] = user_name session.save() return toolkit.redirect_to(u'user.logged_in', came_from=came_from)
def login(self): if 'saabreg_user' in session: if 'saabreg_not_student' in session: # Revert del session['saabreg_not_student'] session.save() tk.h.redirect_to(controller='user', action='me') else: # Redirect to dataset creation tk.h.redirect_to('/student/new')
def after_update(self, context, pkg_dict): is_suitable = twitter_helpers.twitter_pkg_suitable(context, pkg_dict['id']) if is_suitable: try: session.pop('twitter_is_suitable', '') session.setdefault('twitter_is_suitable', pkg_dict['id']) session.save() except TypeError: print "session not iterable"
def logout(self): # save our language in the session so we don't lose it session['lang'] = request.environ.get('CKAN_LANG') session.save() # Do any plugin logout stuff for item in p.PluginImplementations(p.IAuthenticator): item.logout() h.redirect_to(self._get_repoze_handler('logout_handler_path'))
def logout(self): """ When user logs out, this is the first function that is hit when the URL is .../_logout came_from parameter is a comma separated list of logout redirects that are redirected in order. """ # save our language in the session so we don't lose it session['lang'] = request.environ.get('CKAN_LANG') # Mark: Save in session HACK because we redirect to logout and we loose the parameter came_from = request.params.get('came_from', '') session['logout_came_from'] = came_from session.save() h.redirect_to(self._get_repoze_handler('logout_handler_path'))
def login_to_org(id): ''' Used by the "Log in th Organization" button on the organization page, in order to add the membership of the user to this organization if it has been defined in the portal but the icon in the portal not yet clicked on. So does a login to the organization with the provided id, with the same process as /sso, with the differences that, if it fails : - it does not try to log in to any other organization whose id is listed in the ozwillo_global_login_organization_names configuration property - will display (in callback()) "not a member" rather than "Login failed". ''' log.info('Login to organization "%s"' % id) session['is_login_to_org'] = True session.save() return sso(id)
def callback(self): g = model.Group.get(session['organization_id']) client = Clients.get_client(g) org_url = str(toolkit.url_for(controller="organization", action='read', id=g.name)) try: userinfo, app_admin, app_user, access_token, id_token \ = client.callback(session['state'], request.GET) session['access_token'] = access_token session['id_token'] = id_token session.save() except OIDCError, e: flash_error('Login failed') redirect_to(org_url, qualified=True)
def callback(self): try: #token = self.oauth2helper.get_token() #user_name = self.oauth2helper.identify(token) #authorization_header = "x-goog-iap-jwt-assertion".lower() authorization_header = toolkit.config.get( "ckan.oauth2.authorization_header", 'Authorization').lower() log.debug("-----AUTH_HEADER_KEY---" + authorization_header) for h in toolkit.response.headers: log.debug("----HEADERS:---" + h) apikey = toolkit.request.headers.get(authorization_header, '') user_name = None # This API Key is not the one of CKAN, it's the one provided by the OAuth2 Service if apikey: # TODO let's see if firebase lib has a get_token() token = {'access_token': apikey} new_token = self.oauth2helper.validate_token(token) user_name = self.oauth2helper.identify(new_token) self.oauth2helper.save_token(user_name, new_token) self.oauth2helper.remember(user_name, new_token) self.oauth2helper.redirect_from_callback() except Exception as e: session.save() # If the callback is called with an error, we must show the message error_description = toolkit.request.GET.get('error_description') if not error_description: if e.message: error_description = e.message elif hasattr(e, 'description') and e.description: error_description = e.description elif hasattr(e, 'error') and e.error: error_description = e.error else: error_description = type(e).__name__ log.exception("-----CALLBACK---EXC") toolkit.response.status_int = 302 redirect_url = oauth2.get_came_from( toolkit.request.params.get('state')) redirect_url = '/' if redirect_url == constants.INITIAL_PAGE else redirect_url toolkit.response.location = redirect_url helpers.flash_error(error_description)
def _logout_user(self): # to revoke the Google token uncomment the code below # if 'ckanext-google-accesstoken' in session: # atoken = session.get('ckanext-google-accesstoken') # res = requests.get('https://accounts.google.com/o/oauth2/revoke?token=' + atoken) # if res.status_code == 200: # del session['ckanext-google-accesstoken'] # else: # raise GoogleAuthException('Token not revoked') if 'ckanext-google-user' in session: del session['ckanext-google-user'] if 'ckanext-google-email' in session: del session['ckanext-google-email'] session.save()
def login(self): for cookie in request.cookies: value = request.cookies.get(cookie) response.set_cookie(cookie, value, secure=True, httponly=True) if 'organization_id' in session: g = model.Group.get(session['organization_id']) client = Clients.get_client(g) url, ht_args, state = client.create_authn_request(conf.ACR_VALUES) session['state'] = state session.save() if ht_args: toolkit.request.headers.update(ht_args) redirect_to(url) else: redirect_to('/')
def callback(self): g = model.Group.get(session['organization_id']) client = Clients.get_client(g) org_url = str( toolkit.url_for(controller="organization", action='read', id=g.name)) try: userinfo, app_admin, app_user, access_token, id_token \ = client.callback(session['state'], request.GET) session['access_token'] = access_token session['id_token'] = id_token session.save() except OIDCError, e: flash_error('Login failed') redirect_to(org_url, qualified=True)
def logout(self): log.info('Logging out user: %s' % session['user']) session['user'] = None session.save() g = model.Group.get(session['organization_id']) for cookie in request.cookies: response.delete_cookie(cookie) if g: org_url = toolkit.url_for(host=request.host, controller='organization', action='read', id=g.name, qualified=True) redirect_to(str(org_url)) else: redirect_to('/')
def logout(self): log.info('Logging out user: %s' % session.get('user')) response = Response() session['user'] = None session.save() g = model.Group.get(session['organization_id']) for cookie in request.cookies: response.delete_cookie(cookie) if g: org_url = url_for(host=request.host, controller='organization', action='read', id=g.name, qualified=True) redirect_to(str(org_url)) else: redirect_to('/')
def ozwillo_login(): ''' Called by sso(). Sets response cookies, loads the organization logged into from session-provided id (and if it doesn't exist, instead of failing right away uses the first of ozwillo_global_login_organization_names as default, so ex. /dummy_org/sso can be used as a global login url in the theme), creates OID client from client_id/secret of session-provided organization, saves its state and redirects to its callback ''' for cookie in request.cookies: value = request.cookies.get(cookie) Response().set_cookie(cookie, value, secure=True, httponly=True) if 'organization_id' in session: g_ = model.Group.get(session['organization_id']) if not g_ and not ('is_login_to_org' in session and session['is_login_to_org']): # if unknown organization, uses the first conf'd one as default : g_ = model.Group.get(get_global_login_organization_names()[0]) log.info('ozwillo_login org', g_) client = Clients.get_client(g_) url, ht_args, state = client.create_authn_request(conf.ACR_VALUES) session['state'] = state session['from_login'] = True session.save() if ht_args: request.headers.update(ht_args) # Redirect URI should not include language info init. # Returns: `invalid_request: Invalid parameter value: redirect_uri` url = url.replace('en%2F', '').replace('en/', '') return redirect_to(url) else: return redirect_to('/') extra_vars = {} if g.user: return base.render(u'user/logout_first.html', extra_vars) came_from = request.params.get(u'came_from') if not came_from: came_from = h.url_for(u'user.logged_in') g.login_handler = h.url_for(_get_repoze_handler(u'login_handler_path'), came_from=came_from) return base.render(u'user/login.html', extra_vars)
def login(self): if tk.c.user: # Please log out to log in return tk.render('user/logout_first.html') variant = None if 'revert' in tk.request.GET: # Default behaviour if 'login' in tk.request.POST: user = model.Session.query(model.User).filter( model.User.name == tk.request.POST['login']).first() if user is None or not user.validate_password( tk.request.POST['password']): return tk.render('user/login.html', extra_vars={ 'revert': True, 'error_summary': { '': 'Invalid username or password.' } }) # Successful login session['emailauth_user'] = user.name session.save() tk.h.redirect_to(controller='user', action='me') variant = 'revert' elif 'emailauth_fail' in session: del session['emailauth_fail'] session.save() variant = 'invalid' elif 'email_addr' in tk.request.POST: email_addr = tk.request.POST['email_addr'] # Check if email registered user = model.Session.query( model.User).filter(model.User.email == email_addr).first() if user is not None: # Send email send_login_email(email_addr, user.id) variant = 'sent' else: variant = 'reg_required' vars = {} if variant is not None: vars[variant] = True return tk.render('user/login.html', extra_vars=vars)
def sso(id): ''' Logs in to the organization with the given id, and if it fails (KeyError because of missing client_id in organization extra fields, as a patch to the case when it has been erased by mistake such as using the default custom form fields) to the next one in the ozwillo_global_login_organization_names property if configured ''' log.info('SSO for organization "%s"' % id) session['organization_id'] = id session.save() log.info('redirecting to login page') login_url = url_for('ozwillo-pyoidc.ozwillo_login') try: return ozwillo_login() except KeyError as e: log.info('sso KeyError, probably missing client_id ? :', e.args[0], e) sso_ok = try_sso_next_login_org(id) if sso_ok: return sso_ok
def identify(self): log.debug('identify') oauth2helper = oauth2.OAuth2Helper() authorization_header = config.get( 'ckanext.oauth2.authorization_header', 'Authorization') # Create session if it does not exist. Workaround to show flash messages session.save() def _refresh_and_save_token(user_name): new_token = oauth2helper.refresh_token(user_name) if new_token: toolkit.c.usertoken = new_token environ = toolkit.request.environ apikey = toolkit.request.headers.get(authorization_header, '') user_name = None # This API Key is not the one of CKAN, it's the one provided by the OAuth2 Service if apikey: try: token = {'access_token': apikey} user_name = oauth2helper.identify(token) except Exception: pass # If the authentication via API fails, we can still log in the user using session. if user_name is None and 'repoze.who.identity' in environ: user_name = environ['repoze.who.identity']['repoze.who.userid'] log.info('User %s logged using session' % user_name) # If we have been able to log in the user (via API or Session) if user_name: toolkit.c.user = user_name toolkit.c.usertoken = oauth2helper.get_stored_token(user_name) toolkit.c.usertoken_refresh = partial(_refresh_and_save_token, user_name) else: log.warn('The user is not currently logged...')
def verify(self): result = authomatic.login(WebObAdapter(request, response), "oi") if result: if result.error: redirect("/user/logged_in") if not (result.user.name and result.user.id): result.user.update() user = get_user(result.user.id) if not user: user = toolkit.get_action('user_create')( context={ 'ignore_auth': True }, data_dict={ 'email': result.user.email, 'name': get_username(result.user.id), 'password': unique_string() }) session['openid-user'] = user['name'] session.save() redirect("/")
def identify(self): ''' This does work around saml2 authorization. c.user contains the saml2 id of the logged in user we need to convert this to represent the ckan user. ''' # If no drupal sesssion name create one if self.drupal_session_names in (None, []): self.create_drupal_session_names() # Can we find the user? cookies = p.toolkit.request.cookies user = None for drupal_session_name in self.drupal_session_names: drupal_sid = cookies.get(drupal_session_name) if drupal_sid: # Drupal session ids now need to be unquoted drupal_sid = urllib.parse.unquote(drupal_sid) sid_hash = hashlib.sha256(drupal_sid.encode('utf-8')).digest() encoded_sid_hash = base64.urlsafe_b64encode(sid_hash).replace(b"=", b'') encoded_sid_hash_str = encoded_sid_hash.decode('utf-8') engine = sa.create_engine(self.connection) rows = engine.execute('SELECT u.name, u.mail, t.entity_id as uid FROM users_field_data u ' 'JOIN sessions s on s.uid=u.uid LEFT OUTER JOIN ' '(SELECT r.roles_target_id as role_name, r.entity_id FROM user__roles r ' ' WHERE r.roles_target_id=%s ' ') AS t ON t.entity_id = u.uid ' 'WHERE s.sid=%s AND u.name != \'\'', [self.sysadmin_role, encoded_sid_hash_str]) for row in rows: user = self.user(row) break if user: session.save() break p.toolkit.c.user = user
def callback(id): # Blueprints act strangely after user is logged in once. It will skip # SSO and user/login when trying to log in from different account and # directly get here. This is a workaround to force login user if not # redirected from loging page (as it sets important values in session) if not session.get('from_login'): return sso(id) session['from_login'] = False g_ = model.Group.get(session.get('organization_id', id)) client = Clients.get_client(g_) org_url = str(url_for(controller="organization", action='read', id=g_.name)) try: # Grab state from query parameter if session does not have it session['state'] = session.get('state', request.params.get('state')) userinfo, app_admin, app_user, access_token, id_token \ = client.callback(session['state'], request.args ) session['access_token'] = access_token session['id_token'] = id_token session.save() except OIDCError, e: flash_error('Login failed') return redirect_to(org_url, qualified=True)
def test_returns_true_if_is_in_session(self): session.setdefault('twitter_is_suitable', self.df.public_no_records['id']) session.save() eq_(self.js_helpers.tweet_ready(self.df.public_no_records['id']), True)
def set_lang(self, lang): # this allows us to set the lang in session. Used for logging # in/out to prevent being lost when repoze.who redirects things session['lang'] = str(lang) session.save()
def logout(self): # save our language in the session so we don't lose it session['lang'] = request.environ.get('CKAN_LANG') session.save() h.redirect_to(self._get_repoze_handler('logout_handler_path'))