def getMainPageLoggedIn(request): # check if user has priviliges and if yes allow him to modify groups = groupfinder(unauthenticated_userid(request), request) with_modify = False if groups and 'g:moderator' in groups or 'g:admin' in groups: with_modify = True return {'welcomepage': 'off', 'with_modify': with_modify}
def get_user_from_request(request): from c2cgeoportal.models import DBSession, Role class O(object): pass username = unauthenticated_userid(request) if username is not None: user = O() user.id = 0 user.username = username user.email = None connector = get_ldap_connector(request) cm = connector.manager # 0 means 'Tous publics' roletheme = 0 with cm.connection() as conn: result = conn.search_s("ou=portail,dc=act,dc=lu", ldap.SCOPE_SUBTREE, "(login=%s)" % username) if len(result) == 1: if "roleTheme" in result[0][1]: roletheme = result[0][1]["roleTheme"][0] if "mail" in result[0][1]: user.mail = result[0][1]["mail"][0] if "sn" in result[0][1]: user.sn = result[0][1]["sn"][0] user.role = DBSession.query(Role).filter_by(id=roletheme).one() user.functionalities = [] return user
def login(request): """ This method lets a user login to pyquiz """ if unauthenticated_userid(request) != None and 'user' in request.session.keys(): return HTTPFound(location='/index') message = '' login = '' password = '' if 'form.submitted' in request.params: username = request.params['login'] password = request.params['password'] server = ServerProxy(serverLocation, transport = trans) if server.login(username, password): user_info = server.get_user_info(username) userinfo = schooltool_login(username, password, user_info) request.session['user'] = userinfo headers = remember(request, userinfo['roles'][0]) return HTTPFound(location='/index', headers = headers) message = 'Failed login' return dict( message = message, url = request.application_url + '/', login = login, password = password, main = get_renderer('templates/master.pt').implementation(), )
def current_user(request): """ This is added to the request as an attribute named "user" The function takes care of everything and caches various results so that for each time we call `user_groups` we don't rerun the database queries unnecessarily. It is highly unlikely that in the milliseconds it takes to render the page that the user is going to lose access to a particular resource. """ class UserData: pass def _user_nonexistent(): udata = UserData() udata.username = None udata.user = None udata.ticket = None udata.groups = None return udata def _user_exists(user, ticket, groups): udata = UserData() udata.username = user.disp_uname udata.user = user udata.ticket = ticket udata.groups = groups return udata userid = security.unauthenticated_userid(request) # Check to see if any tokens are set if 'REMOTE_USER_TOKENS' in request.environ: cur_ticket = [x for x in request.environ['REMOTE_USER_TOKENS'] if 'tkt_' in x] cur_ticket = cur_ticket[0][4:] if len(cur_ticket) == 1 else None # If we don't get a ticket, we return that the user is non-existent if cur_ticket is None: return _user_nonexistent() # Find the user by looking up the ticket/username ticket = UserTickets.find_ticket_username(cur_ticket, userid) # If the ticket has been removed, we unauth the user if ticket is None: return _user_nonexistent() user = ticket.user # Load up all the groups that the user is in user_groups = ['userid:' + unicode(user.id)] user_groups.extend(['group:' + grp.name for grp in user.groups]) # Return a valid user containing data return _user_exists(user, ticket, user_groups) return _user_nonexistent()
def get_is_authenticated(request): """Has this ``request`` been made by an authenticated user? Setup:: >>> from mock import Mock >>> from pyramid_simpleauth import hooks >>> _unauthenticated_userid = hooks.unauthenticated_userid >>> hooks.unauthenticated_userid = Mock() >>> mock_request = Mock() When the request is not authenticated, returns ``False``:: >>> hooks.unauthenticated_userid.return_value = None >>> get_is_authenticated(mock_request) False When the request is authenticated, returns ``True``:: >>> hooks.unauthenticated_userid.return_value = 1234 >>> get_is_authenticated(mock_request) True Teardown:: >>> hooks.unauthenticated_userid = _unauthenticated_userid """ return bool(unauthenticated_userid(request))
def caslogin(request, return_url=None): """ Cas login and user challenger view """ service = cas.getserviceurl(request) username = unauthenticated_userid(request) if username is None: ticket = request.GET.get('ticket') if ticket is None: return cas.sendtoservice(request) username = cas.verifycas20(request, ticket, service) if username is None: return 'no user' settings = request.registry.settings if 'pyramid_cas.callback.get_user' in settings: callable = settings['pyramid_cas.callback.get_user'] module = callable.split('.')[0] + '.' + callable.split('.')[1] caller = sys.modules[module] method = getattr(caller, callable.split('.')[2]) user = method(username, request) else: user = username headers = remember(request, user, max_age='86400') # fall back to setting from config file if return_url isn't provided redirect_to = return_url or request.route_url(settings['pyramid_cas.redirect_route']) return HTTPFound(location=redirect_to, headers=headers) else: raise HTTPForbidden
def login(request): """ This method lets a user login to pyquiz """ if unauthenticated_userid(request) != None and 'user' in request.session.keys(): return HTTPFound(location='/index') message = '' login = '' password = '' if 'form.submitted' in request.params: username = request.params['login'] password = request.params['password'] if USERS.get(username) == password: userinfo = schooltool_login(username, password) request.session['user'] = userinfo headers = remember(request, userinfo['role']) return HTTPFound(location='/index', headers = headers) message = 'Failed login' return dict( message = message, url = request.application_url + '/', login = login, password = password, )
def getMainPageLoggedIn(request): # check if user has priviliges and if yes allow him to modify groups = groupfinder(unauthenticated_userid(request), request) with_modify = False if groups and 'g:moderator' in groups or 'g:admin' in groups: with_modify = True return {'welcomepage':'off', 'with_modify':with_modify}
def foursquare_callback(request): error_msg = None author_id = unauthenticated_userid(request) code = request.params.get('code') if not code: error = request.params.get('error') raise Exception('Error authenticating user with Foursquare: {error}'.format(error=error)) # let's get the acces_token queryArgs = urllib.urlencode([('client_id', tim_config['oauth'][SERVICE]['key']), ('client_secret', tim_config['oauth'][SERVICE]['secret']), ('grant_type', 'authorization_code'), ('redirect_uri', request.route_url('foursquare_callback')), ('code', code)]) url = tim_config['oauth'][SERVICE]['access_token_url'].format(args=queryArgs) try: r = requests.get(url) r.raise_for_status() json_dict = r.json except requests.exceptions.RequestException, e: log.error(e) raise e
def get_user(request): userid = unauthenticated_userid(request) try: user = User.by_username(userid) except (MultipleResultsFound, NoResultFound): user = None return user
def __call__(self, request, check, normalized_retcode, results, **kwargs): if normalized_retcode == 0: title = 'RESOLVED' action = 'succeeded' elif normalized_retcode == 1: title = 'WARNING' action = 'failed' else: title = 'ERROR' action = 'failed' if len(results) == 1: target = results[0].minion else: target = "%d minions" % len(results) subject = "[%s] %s on %s" % (title, check.name, target) if kwargs.get('marked_resolved'): minions = [result.minion for result in results] body = ("%s marked resolved by %s on %s" % (check.name, unauthenticated_userid(request), ', '.join(minions))) else: body = "%s %s on\n" % (check.name, action) for result in results: body += (" %s %d time%s\n" % (result.minion, result.count, 's' if result.count > 1 else '')) if result.stdout: body += 'STDOUT:\n' + result.stdout if result.stderr: body += 'STDERR:\n' + result.stderr request.subreq('mail', subject=subject, body=body, mail_to=self.mail_to)
def forbidden(request): if unauthenticated_userid(request): request.response.status_int = 403 return {'message': 'You are not allowed to perform this action.'} else: request.response.status_int = 401 return {'message': 'You must login to perform this action.'}
def get_user(request): userid = unauthenticated_userid(request) if userid is not None: return DBSession.query(User).filter(User.id == userid).first() return None
def get_user(request): db = request.db api_key = unauthenticated_userid(request) if api_key is not None: # this should return None if the user doesn't exist # in the database return User.by_api_key(db, api_key)
def cas_login(request): "CAS login and user challenger view" username = unauthenticated_userid(request) # Already authenticated if username is not None: logger.info("Already authenticated: username=%s", username) raise HTTPForbidden next_url = _get_next_url(request, "route_on_login") cas = CASProvider(request, next_url) ticket = request.GET.get("ticket", None) if ticket is None: logger.info("No ticket, redirecting to CAS login page") return HTTPFound(location=cas.get_login_url()) else: # We have a ticket logger.info("Verifying ticket") username = cas.verify_cas_20(ticket) if username is None: msg = "Authentication failure: CAS returned no user" logger.error(msg) return msg # We have a username logger.info("Successful authentication for username: %s", username) headers = remember(request, username, max_age="86400") return HTTPFound(location=next_url, headers=headers)
def casLogin(request): """ Cas login and user challenger view """ service = cas.getServiceUrl(request) username = unauthenticated_userid(request) if username is None: ticket = request.GET.get('ticket') if ticket is None: return cas.sendToService(request) username = cas.verifyCas20(request,ticket,service) if username is None: return 'no user' settings = request.registry.settings if 'pyramid_cas.callback.get_user' in settings: callable = settings['pyramid_cas.callback.get_user'] module = callable.split('.')[0] + '.' + callable.split('.')[1] caller = sys.modules[module] method = getattr(caller,callable.split('.')[2]) user = method(username,request) else: user = username headers = remember(request,user,max_age = '86400') return HTTPFound(location=request.route_url('home'),headers=headers) else: return HTTPFound(location='/not-allowed')
def tm_tween(request): if 'repoze.tm.active' in request.environ: # don't handle txn mgmt if repoze.tm is in the WSGI pipeline return handler(request) if activate is not None: if not activate(request): return handler(request) manager = getattr(request, 'tm', None) if manager is None: # pragma: no cover (pyramid < 1.4) manager = create_tm(request) request.tm = manager number = attempts if annotate_user: if hasattr(request, 'unauthenticated_userid'): userid = request.unauthenticated_userid else: # pragma no cover (for pyramid < 1.5) from pyramid.security import unauthenticated_userid userid = unauthenticated_userid(request) else: userid = None while number: number -= 1 try: manager.begin() # make_body_seekable will copy wsgi.input if necessary, # otherwise it will rewind the copy to position zero if attempts != 1: request.make_body_seekable() t = manager.get() if userid: userid = native_(userid, 'utf-8') t.setUser(userid, '') try: t.note(native_(request.path_info, 'utf-8')) except UnicodeDecodeError: t.note("Unable to decode path as unicode") response = handler(request) if manager.isDoomed(): raise AbortResponse(response) if commit_veto is not None: veto = commit_veto(request, response) if veto: raise AbortResponse(response) manager.commit() return response except AbortResponse as e: manager.abort() return e.response except: exc_info = sys.exc_info() try: retryable = manager._retryable(*exc_info[:-1]) manager.abort() if (number <= 0) or (not retryable): reraise(*exc_info) finally: del exc_info # avoid leak
def get_user(request): from bodhi.models import User userid = unauthenticated_userid(request) if userid is not None: user = request.db.query(User).filter_by(name=unicode(userid)).first() # Why munch? https://github.com/fedora-infra/bodhi/issues/473 return munchify(user.__json__(request=request))
def user(self): from .models.user import User userid = unauthenticated_userid(self) if self.path.startswith('/admin'): return User.admin_by_id(userid) if userid is not None: return User.get_by_id(userid)
def googleplus_callback(request): error_msg = None author_id = unauthenticated_userid(request) code = request.params.get('code') if not code: error = request.params.get('error') log.error('Google+ oauth failed: %s' % error) raise Exception(error) # let's exchange the authorization code for an access token and a refresh token query_args = {'code': code, 'client_id': tim_config['oauth'][SERVICE]['key'], 'client_secret': tim_config['oauth'][SERVICE]['secret'], 'redirect_uri': request.route_url('googleplus_callback'), 'grant_type': 'authorization_code'} try: r = requests.post(tim_config['oauth'][SERVICE]['oauth_exchange_url'], data=query_args) r.raise_for_status() json_dict = r.json except requests.exceptions.RequestException, e: log.error(e) raise e
def get_user(request): '''fetches the user. Used to attach a user object to the request''' user = unauthenticated_userid(request) if user is not None: return DBSession.query(User).filter(User.user == user).first() else: return DBSession.query(User).filter(User.user == User.VISITOR).first()
def user(self): session = DBSession() user_email = unauthenticated_userid(self) if user_email is not None: # this should return None if the user doesn't exist # in the database return session.query(User).filter(User.email==user_email).first()
def user(self): if not self.path_info.startswith('/static'): username = unauthenticated_userid(self) if username: return User.by_username(username) else: return None
def user(self): query = self.dbsession.query(User) userid = unauthenticated_userid(self) if userid is not None: # this should return None if the user doesn't exist # in the database return query.filter_by(email=userid).first()
def player(self): session = self.db user_id = unauthenticated_userid(self) if user_id is not None: # this should return None if the user doesn't exist # in the database return session.query(Player).filter_by(id=user_id).first()
def login(request): ''' forbidden_view_config decorator indicates that this is the route to redirect to when an user has no access to a page ''' # Get session id from cookie session_id = unauthenticated_userid(request) # Get roles principals = effective_principals(request) # Requests will be forwarded here when users aren't authorized to those pages # If they are unauthorized to those pages, they should have session id and principals # and, if there is a session id and principals, return 403 # Here, we return 403 for users that has a role of None # This can be an user that has no role from IDP or has a role that we don't know of if Roles.get_invalid_role() in principals or (principals and session_id): write_security_event("Forbidden view being accessed", SECURITY_EVENT_TYPE.WARN, session_id) return HTTPForbidden() # clear out the session if we found one in the cookie if session_id is not None: expire_session(session_id) handlers = [_handle_OAUTH2_Implicit_login_flow, _handle_SAML2_login_flow] for handler in handlers: response = handler(request) if response is not None: return response return HTTPForbidden()
def logout(request): # Get the current session session_id = unauthenticated_userid(request) # Redirect to login if no session exist url = request.route_url('login') headers = None params = {} if session_id is not None: # remove cookie headers = forget(request) session = get_user_session(session_id) # Check that there is a session in db, else we can't log out from IDP # If for some reason, we get into this case where session is not found in db, it'll redirect back to login route # and if the user still has a valid session with IDP, it'll redirect to default landing page if session is not None: # Logout request to identity provider logout_request = SamlLogoutRequest( request.registry.settings['auth.saml.issuer_name'], session.get_idp_session_index(), request.registry.settings['auth.saml.name_qualifier'], session.get_name_id()) params = logout_request.generate_saml_request() params = urllib.parse.urlencode(params) url = request.registry.settings[ 'auth.saml.idp_server_logout_url'] + "?%s" % params write_security_event("Logout requested", SECURITY_EVENT_TYPE.INFO, session_id) # expire our session expire_session(session_id) return HTTPFound(location=url, headers=headers)
def linkedin_callback(request): error_msg = None author_id = unauthenticated_userid(request) # the oauth_token is request as a query arg; the auth_token_secret is in session store oauth_token = request.params['oauth_token'] oauth_token_secret = request.session['oauth_token_secret'] oauth_verifier = request.params['oauth_verifier'] # Step 3: Once the consumer has redirected the user back to the oauth_callback # URL you can request the access token the user has approved. You use the # request token to sign this request. After this is done you throw away the # request token and use the access token returned. You should store this # access token somewhere safe, like a database, for future use. consumer = oauth.Consumer(tim_config['oauth'][SERVICE]['key'], tim_config['oauth'][SERVICE]['secret']) token = oauth.Token(oauth_token, oauth_token_secret) token.set_verifier(oauth_verifier) client = oauth.Client(consumer, token) resp, content = client.request(tim_config['oauth'][SERVICE]['access_token_url'], "POST") if resp['status'] != '200': raise Exception("Invalid response %s (%s)." % (resp['status'], content)) access_dict = dict(urlparse.parse_qsl(content)) # these are the real deal and need to be stored securely in the DB access_token = access_dict['oauth_token'] access_token_secret = access_dict['oauth_token_secret'] # Create our OAuth consumer instance token = oauth.Token(key=access_token, secret=access_token_secret) client = oauth.Client(consumer, token) url = '{endpoint}{resource}'.format(endpoint=tim_config['oauth'][SERVICE]['endpoint'], resource='people/~:(id)') response = make_request(client, url, {'x-li-format': 'json'}) json_dict = json.loads(response) linkedin_id = json_dict['id'] url = '{endpoint}/v1/authors/{author}/services'.format(endpoint=tim_config['api']['endpoint'], author=author_id) payload = {'name': SERVICE, 'access_token': access_token, 'access_token_secret': access_token_secret, 'service_author_id': linkedin_id} headers = {'content-type': 'application/json; charset=utf-8'} cookies = request.cookies try: r = requests.post(url, data=json.dumps(payload), headers=headers, cookies=cookies) r.raise_for_status() except requests.exceptions.RequestException, e: log.error(e.message) if e.response.status_code == 409: error_msg = 'Service already exists for this author ({message})'.format(message=e.message)
def _get_user(request): userid = unauthenticated_userid(request) if userid is not None: return request.dbsession.query(Account).filter_by( id=userid, enabled=True).first() return None
def get_user(request): userid = unauthenticated_userid(request) user_class = request.registry.queryUtility(interfaces.IUserClass) if userid is not None: return user_class.get_by_id(request, userid) return None
def user(self): userid = unauthenticated_userid(self) if userid is not None: try: return User.get(userid) except pycassa.NotFoundException: return None return None
def forbidden(request): log.info("error.forbidden") if unauthenticated_userid(request): request.response.status_int = 403 return err_dict('You are not allowed to perform this action.') else: request.response.status_int = 401 return err_dict('You must login to perform this action.')
def user(self): id = unauthenticated_userid(self) if id: conn = DBSession() user = conn.query(User).get(id) return user else: return None
def get_user(request): """ See if the current user is logged in and fetch the corresponding user object. """ user_id = unauthenticated_userid(request) if user_id is not None: return User.objects.get(id=user_id, is_active=True)
def forbidden_redirect(self): if unauthenticated_userid(self.request): # The user is logged but doesn't have the right permission location = self.request.route_url('forbidden') else: login_url = self.request.route_url('login') location = '%s?%s' % (login_url, urlencode({'next': self.request.url})) return HTTPFound(location=location)
def checkIsUser(request): userid = unauthenticated_userid(request) log.info('Checked userid is %s' % userid) if Users.by_username(userid, request.db): # this should return None if the user doesn't exist return userid else: return False
def user(self): id = unauthenticated_userid(self) if id: conn=DBSession() user=conn.query(User).get(id) return user else: return None
def _join(request, provider_name, user): login_user = unauthenticated_userid(request) if not login_user: raise HTTPForbidden() user = _convert_user(user) request.session[provider_name] = user return HTTPFound( location=request.route_url("popup", provider=provider_name))
def get_auth_user(request): """ Get the authenticated user id from the request and return an `AuthUser` object. :param request: a ``pyramid.request`` object """ user_id = unauthenticated_userid(request) if user_id: return AuthUser.get_by_id(user_id)
def has_permission(self, package, perm): """ Check if this user has a permission for a package """ current_userid = unauthenticated_userid(self.request) if current_userid is not None and self.is_admin(current_userid): return True for principal in effective_principals(self.request): if perm in self.principal_permissions(package, principal): return True return False
def home(request): login_user = unauthenticated_userid(request) if not login_user: return render_to_response("login.html", {}, request=request) out = {} for name in ["twitter", "facebook", "google", "ninja", "yahoo"]: out[name] = request.session.get(name, None) return out
def get_user(request): userid = unauthenticated_userid(request) if test_session_callable == None: # set db_session to none to pass to the UserModel.by_id db_session = None else: # Else assign the request.session db_session = session_provider_callable(request) if userid is not None: return UserModel.by_id(userid, db_session=db_session)
def get_user(request): # the below line is just an example, use your own method of # accessing a database connection here (this could even be another # request property such as request.db, implemented using this same # pattern). userid = unauthenticated_userid(request) if userid is not None: # this should return None if the user doesn't exist # in the database return User.query.filter_by(id=userid).first()
def get_avatar(request): """ Returns the current User object """ log.info("Get avatar") login = unauthenticated_userid(request) if login is not None: log.info(" + Returning the user") user = request.dbsession.query(User).filter_by(login=login).first() return user
def user(self): # <your database connection, however you get it, the below line # is just an example> # dbconn = self.registry.settings['dbconn'] user_id = unauthenticated_userid(self) if user_id is not None: # this should return None if the user doesn't exist # in the database user = UserMgr.get(user_id=user_id) return user
def user(self): userid = unauthenticated_userid(self) #print "--- in RequestWithUserAttribute: userid = " + str(userid) if userid is not None: # this should return None if the user doesn't exist # in the database #return dbsession.query('users').filter(user.user_id == userid) return C3sStaff.check_user_or_None(userid) # else: userid == None return userid # pragma: no cover
def get_user(request): userid = unauthenticated_userid(request) if userid is None: return None else: user = DBSession.query(User).filter_by(username=userid).first() if user: return user else: return None
def get_authenticated_user(request): ''' This function is used to attach user object to current request ''' userid = unauthenticated_userid(request) if userid is not None: # this should return None if the user doesn't exist # in the database return User.get_by_id(userid)