def _authorize(*args, **kwargs): login_required = HTTPUnauthorized() login_required.headers['WWW-Authenticate'] = \ 'Basic realm="Manage bridge"' if IRequest.providedBy(args[0]): request = args[0] else: request = args[0].request authorization = request.headers.get('Authorization', None) if not authorization: raise login_required _basic, authorization = authorization.split(' ', 1) username, password = authorization.decode('base64').split(':', 1) settings = getUtility(ISettings) admin_user = settings.get('bridge.admin.username', object()) admin_pass = settings.get('bridge.admin.password', object()) if username != admin_user or password != admin_pass: raise login_required return fun(*args, **kwargs)
def graphqlview(context, request): #pylint: disable=W0613 token = request.headers.get('X-Api-Key', '') is_private = getattr(request.root, 'only_for_members', False) if is_private and not auth_user(token, request): response = HTTPUnauthorized() response.content_type = 'application/json' return response if request.method == 'OPTIONS': response = Response(status=200, body=b'') response.headerlist = [] # we have to reset headerlist response.headerlist.extend( ( ('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Headers', 'Content-Type'), ) ) else: solver = graphql_wsgi(schema) response = solver(request) response.headerlist.append( ('Access-Control-Allow-Origin', '*') ) return response
def forbidden_view(request): """ Forbidden view gets called when user is not authorized, here we just send a challenge to the user to authenticate itself. """ resp = HTTPUnauthorized() resp.www_authenticate = 'Basic realm="Secure Area"' return resp
def create(self): user = self.request.user if user is None: return HTTPUnauthorized() map = Map() map.user_login = user.username return self.save(map)
def proxy(self) -> pyramid.response.Response: if self.user is None: raise HTTPUnauthorized("Authentication required", headers=[("WWW-Authenticate", 'Basic realm="TinyOWS"')]) operation = self.lower_params.get("request") typenames = ({normalize_typename(self.lower_params["typename"])} if "typename" in self.lower_params else set()) method = self.request.method if method == "POST": try: (operation, typenames_post) = self._parse_body(self.request.body) except Exception: LOG.exception("Error while parsing POST request body") raise HTTPBadRequest( # pylint: disable=raise-missing-from "Error parsing the request (see logs for more details)") typenames = typenames.union(typenames_post) if operation is None or operation == "": operation = "getcapabilities" if operation == "describefeaturetype": # for DescribeFeatureType we require that exactly one type-name # is given, otherwise we would have to filter the result if len(typenames) != 1: raise HTTPBadRequest( "Exactly one type-name must be given for DescribeFeatureType requests" ) if not self._is_allowed(typenames): raise HTTPForbidden( "No access rights for at least one of the given type-names") # we want clients to cache GetCapabilities and DescribeFeatureType req. use_cache = method == "GET" and operation in ("getcapabilities", "describefeaturetype") cache_control = Cache.PRIVATE if use_cache else Cache.PRIVATE_NO errors: Set[str] = set() url = super()._get_wfs_url(errors) if url is None: LOG.error("Error getting the URL:\n%s", "\n".join(errors)) raise HTTPInternalServerError() response = self._proxy_callback( operation, cache_control, url=url, params=dict(self.request.params), cache=use_cache, headers=self._get_headers(), body=self.request.body, ) return response
def duties(self): account = self.request.session.get(LOGGED_ACCOUNT_KEY, None) if account is None: return HTTPUnauthorized() sign_list = SignService.find_out_mouth_signs(account) dict_list = list() for sign in sign_list: dict_list.append(sign) return {'duties': dict_list}
def remove_all(self): user = self.request.user if user is None: return HTTPUnauthorized() product = self.product_repository.find_by_id(self.request.matchdict['id']) if product is None: return HTTPNotFound() self.shopping_cart_service.remove_all(user.id, product.id) return HTTPOk(body='')
def create_design_request_page(req: Request): is_logged_in = verify_user_token(req) user = DBSession.query( m.DoctorUser).filter_by(username=req.session.get('uname')).first() if not is_logged_in or not user: return HTTPUnauthorized("You must be logged in to view this page") return {'is_logged_in': is_logged_in, 'user_name': user.username}
def get_node(cls, id, context, info): try: result = cls.get_query(context).get(id) except NoResultFound: return None # The user can't retrieve a content from a different discussion discussion_id = context.matchdict['discussion_id'] if hasattr(result, 'discussion_id') and result.discussion_id != discussion_id: raise HTTPUnauthorized() user_id = context.authenticated_userid or Everyone permissions = get_permissions(user_id, discussion_id) if not result.user_can(user_id, CrudPermissions.READ, permissions): raise HTTPUnauthorized() return result
def fire_transition(self, transition_id, comment=None, side_effect=None, check_security=True, principal=None, request=None): # pylint: disable=too-many-arguments """Fire transition with given ID""" versions = IWorkflowVersions(self.parent) state = IWorkflowState(self.context) if request is None: request = check_request() # this raises InvalidTransitionError if id is invalid for current state transition = self.wf.get_transition(state.state, transition_id) # check whether we may execute this workflow transition if check_security and transition.permission: if not request.has_permission(transition.permission, context=self.context): raise HTTPUnauthorized() # now make sure transition can still work in this context if not transition.condition(self, self.context): raise ConditionFailedError() # perform action, return any result as new version if principal is None: principal = request.principal result = transition.action(self, self.context) if result is not None: # stamp it with version versions.add_version(result, transition.destination, principal) # execute any side effect: if side_effect is not None: side_effect(result) event = WorkflowVersionTransitionEvent(result, self.wf, principal, self.context, transition.source, transition.destination, transition, comment) else: versions.set_state(state.version_id, transition.destination, principal) # execute any side effect if side_effect is not None: side_effect(self.context) event = WorkflowTransitionEvent(self.context, self.wf, principal, transition.source, transition.destination, transition, comment) # change state of context or new object registry = request.registry registry.notify(event) # send modified event for original or new object if result is None: registry.notify(ObjectModifiedEvent(self.context)) else: registry.notify(ObjectModifiedEvent(result)) return result
def challenge(self, request, content="Unauthorized"): print("challenge_______________") """Challenge the user for credentials. This method returns a 401 response using the WWW-Authenticate field as constructed by forget(). You might like to use it as pyramid's "forbidden view" when using this auth policy. """ return HTTPUnauthorized(content, headers=self.forget(request))
def get_instance(self, key, parent_instance): if key == 'current': from ..auth.util import get_current_user_id try: key = get_current_user_id() except RuntimeError: raise HTTPUnauthorized() return super(AllUsersCollection, self).get_instance(key, parent_instance)
def valid_token(request, **kargs): header = 'X-Messaging-Token' htoken = request.headers.get(header) if htoken is None: raise HTTPUnauthorized() try: user, token = htoken.split('-', 1) except ValueError: raise HTTPUnauthorized() valid = user in _USERS and _USERS[user] == token if not valid: raise HTTPUnauthorized() request.validated['user'] = user
def widget_userstate_put(request): # No further permission check for user_state user_state = request.json_body if user_state: user_id = authenticated_userid(request) if not user_id: raise HTTPUnauthorized() request.context._instance.set_user_state(user_state, user_id) return HTTPOk() # HTTPNoContent() according to Mozilla
def global_vote_results_csv(request): ctx = request.context user_id = request.authenticated_userid if not user_id: raise HTTPUnauthorized widget = ctx._instance if widget.activity_state != "ended": permissions = ctx.get_permissions() if P_ADMIN_DISC not in permissions: raise HTTPUnauthorized() user_prefs = LanguagePreferenceCollection.getCurrent() # first fetch the ideas voted on ideas = widget.db.query(Idea ).join(AbstractIdeaVote, AbstractIdeaVote.idea_id == Idea.id ).join(AbstractVoteSpecification ).filter(AbstractVoteSpecification.widget_id == widget.id ).distinct().all() idea_ids = [i.id for i in ideas] titles = [(idea.safe_title(user_prefs, request.localizer), idea.id) for idea in ideas] titles.sort() q = widget.db.query(Idea.id).filter(Idea.id.in_(idea_ids)) # then get the vote specs specs = [(spec.title.best_lang(user_prefs).value if spec.title else str(spec.id), spec) for spec in widget.vote_specifications] specs.sort() # construct a query with each votespec creating two columns: # sum of vote values, and count of votes. # Ideas are rows (and Idea.id is column 0) for (t, spec) in specs: a = aliased(spec.get_vote_class(), name="votes_%d" % spec.id) q = q.outerjoin(a, (a.idea_id == Idea.id) & (a.vote_spec_id == spec.id)) q = q.add_columns(func.sum(a.vote_value).label('vsum_%d' % spec.id), func.count(a.id).label('vcount_%d' % spec.id)) q = q.group_by(Idea.id) r = q.all() r = {x[0]: x for x in r} output = BytesIO() output_utf8 = TextIOWrapper(output, encoding='utf-8') csvw = csv.writer(output_utf8) csvw.writerow([""] + [t.encode('utf-8') for (t, spec) in specs]) for title, idea_id in titles: row = [title.encode('utf-8')] sourcerow = r[idea_id][1:] for i, (t, spec) in enumerate(specs): num = sourcerow[1 + i * 2] if num: if isinstance(spec, TokenVoteSpecification): # we want total number of tokens num = 1 # otherwise we want average vote value row.append(sourcerow[i * 2] / num) else: row.append("") csvw.writerow(row) output_utf8.detach() output.seek(0) return Response(body_file=output, content_type='text/csv', charset="utf-8")
def forbidden_view(self, request): if request.authenticated_userid is None: response = HTTPUnauthorized() response.headers.update(forget(request)) # user is logged in but doesn't have permissions, reject wholesale else: response = HTTPForbidden() return response
def graphql_api(request): slug = request.matchdict['discussion_slug'] # Check permission discussion = models.Discussion.query.filter( models.Discussion.slug == slug).one() if discussion is None: raise HTTPUnauthorized() discussion_id = discussion.id # set discussion_id in request.matchdict which is use as context_value request.matchdict['discussion_id'] = discussion_id user_id = authenticated_userid(request) or Everyone permissions = get_permissions(user_id, discussion_id) if not discussion.user_can(user_id, CrudPermissions.READ, permissions): raise HTTPUnauthorized() solver = graphql_wsgi(Schema) return solver(request)
def __call__(self): if self.request.has_permission(security.VIEW): return HTTPFound(location = self.request.resource_url(self.context)) if not self.request.authenticated_userid: raise HTTPUnauthorized() if self.access_policy.view is not None: #Redirect to access policy custom view return HTTPFound(location = self.request.resource_url(self.context, self.access_policy.view)) return super(RequestAccessForm, self).__call__()
def mutate(root, args, context, info): ATTACHMENT_PURPOSE_IMAGE = models.AttachmentPurpose.IMAGE.value ATTACHMENT_PURPOSE_DOCUMENT = models.AttachmentPurpose.DOCUMENT.value cls = models.Resource discussion_id = context.matchdict['discussion_id'] discussion = models.Discussion.get(discussion_id) user_id = context.authenticated_userid or Everyone resource_id = args.get('id') resource_id = int(Node.from_global_id(resource_id)[1]) resource = cls.get(resource_id) permissions = get_permissions(user_id, discussion_id) allowed = resource.user_can(user_id, CrudPermissions.UPDATE, permissions) if not allowed: raise HTTPUnauthorized() with cls.default_db.no_autoflush: title_entries = args.get('title_entries') if title_entries is not None and len(title_entries) == 0: raise Exception( 'Resource titleEntries needs at least one entry') # Better to have this message than # 'NoneType' object has no attribute 'owner_object' # when creating the saobj below if title=None update_langstring_from_input_entries(resource, 'title', title_entries) update_langstring_from_input_entries(resource, 'text', args.get('text_entries')) kwargs = {} kwargs['embed_code'] = args.get('embed_code', None) kwargs['order'] = args.get('order', resource.order) for attr, value in kwargs.items(): setattr(resource, attr, value) db = resource.db # add uploaded image as an attachment to the resource image = args.get('image') if image is not None: update_attachment(discussion, models.ResourceAttachment, image, resource.attachments, ATTACHMENT_PURPOSE_IMAGE, db, context) # add uploaded doc as an attachment to the resource doc = args.get('doc') if doc is not None: update_attachment(discussion, models.ResourceAttachment, doc, resource.attachments, ATTACHMENT_PURPOSE_DOCUMENT, db, context) db.flush() return UpdateResource(resource=resource)
def loginchange(self): new_password = self.request.params.get('newPassword', None) new_password_confirm = self.request.params.get('confirmNewPassword', None) if new_password is None or new_password_confirm is None: raise HTTPBadRequest( '"newPassword" and "confirmNewPassword" should be \ available in request params') # check if loggedin if not self.request.user: raise HTTPUnauthorized('bad credentials') if new_password != new_password_confirm: raise HTTPBadRequest("the new password and the new password \ confirmation don't match") u = self.request.user u._set_password(new_password) u.is_password_changed = True DBSession.flush() log.info("password changed for user: %s" % self.request.user.username) # handle replication if 'auth_replication_enabled' in self.request.registry.settings and \ self.request.registry.settings['auth_replication_enabled'] == \ 'true': # pragma: no cover try: log.debug( "trying to find if engine set for replication exists") engine = sqlahelper.get_engine('replication') except RuntimeError: log.debug("engine for replication doesn't exist yet, trying \ to create") engine = engine_from_config(self.request.registry.settings, 'sqlalchemy_replication.') sqlahelper.add_engine(engine, 'replication') DBSession2 = scoped_session(sessionmaker(bind=engine)) dbuser_r = DBSession2.query(User).filter( User.id == self.request.user.id) result = dbuser_r.all() if len(result) == 0: msg = 'user not found in replication target database: %s' \ % self.request.user.username log.exception(msg) return HTTPBadRequest(msg) # pragma nocover else: u_r = dbuser_r.all()[0] u_r._set_password(new_password) u_r.is_password_changed = True DBSession2.commit() log.info("password changed in replication target database \ for user: %s" % self.request.user.username) return Response('true', cache_control="no-cache")
def sync_signin(request): req = request.json_body login = req['login'] password = req['password'] user = DBSession.query(User).filter_by(login=login).first() if user and user.check_password(password): request.response.status = HTTPOk.code return HTTPOk(json_body={}) return HTTPUnauthorized(location=request.route_url('login'))
def oauth2_step2(request, token_uri, client_id, client_secret, redirect_url, scope): try: code = request.params['code'] except KeyError: return HTTPBadRequest('Missing required code') try: state = request.params['state'] except KeyError: return HTTPBadRequest('Missing required state') try: my_state = request.session['state'] if state != my_state: return HTTPUnauthorized('State parameter does not match internal ' 'state. You may be a victim of CSRF') else: del request.session['state'] except KeyError: return HTTPUnauthorized('Missing internal state. ' 'You may be a victim of CSRF') params = { 'grant_type': 'authorization_code', 'client_id': client_id, 'client_secret': client_secret, 'code': code, 'redirect_uri': redirect_url, 'scope': scope, } response = requests.post(token_uri, data=params) if response.status_code != 200: return HTTPUnauthorized(response.text) try: response_dict = response.json() except ValueError: response_dict = dict(urlparse.parse_qsl(response.text)) return response_dict['access_token']
def interesting_ideas(request): from .discussion import get_analytics_alerts ctx = request.context target = request.context._instance user_id = request.authenticated_userid or Everyone discussion_id = ctx.get_discussion_id() permissions = get_permissions(user_id, discussion_id) if P_READ not in permissions: raise HTTPUnauthorized() if user_id != target.id and P_ADMIN_DISC not in permissions: raise HTTPUnauthorized() discussion = Discussion.get(discussion_id) if not discussion: raise HTTPNotFound() result = get_analytics_alerts(discussion, target.id, ["interesting_to_me"], False) result = loads(result)['responses'][0]['data'][0]['suggestions'] result = {x['targetID']: x['arguments']['score'] for x in result} return result
def authenticate(request, **kwargs): _api_key = request.headers['X-Api-Key'] # api key not set serverside if 'api.c3smembership.api_key' not in request.registry.settings: raise HTTPServiceUnavailable() if not request.registry.settings['api.c3smembership.api_key']: raise HTTPServiceUnavailable() # api key not valid if _api_key != request.registry.settings['api.c3smembership.api_key']: raise HTTPUnauthorized()
def vote_results(request): ctx = request.context user_id = authenticated_userid(request) or Everyone widget = ctx.get_instance_of_class(VotingWidget) if not widget: raise HTTPNotFound() if widget.activity_state != "ended": if P_ADMIN_DISC not in ctx.get_permissions(): raise HTTPUnauthorized() return ctx._instance.all_voting_results()
def user_delete(request): id = request.matchdict['id'] user = load_user(id) if not user: return HTTPUnauthorized() delete_user(id) return HTTPFound(location=route_path("user_list", request))
def get(self): """Return the current user, or fail with 401 if not logged in """ user = self.request.user if user is None: raise HTTPUnauthorized() return self.user_json(user)
def _patch(request: Request): db_issue: Issue = request.validated['issue'] db_user: User = request.validated['user'] if db_user.is_admin() or db_user is db_issue.author: shallow_patch(db_issue, request.json_body, allowed_fields=ApiIssue.modifiable) return db_issue else: return HTTPUnauthorized()
def post_disable_two_factor(request: Request, code: str) -> Response: """Disable two-factor authentication for the user.""" if not request.user.is_correct_two_factor_code(code): raise HTTPUnauthorized(body="Invalid code") request.user.two_factor_enabled = False request.user.two_factor_secret = None request.user.two_factor_backup_codes = None return {}
def user_messages(request): user_id = authenticated_userid(request) if not user_id: raise HTTPUnauthorized() DBSession.query(User).get(user_id) comments = [] return dict(page_id="messages", comments=comments)
def stat(request): userid = request.authenticated_userid if not userid: raise HTTPUnauthorized() # verify to OAS spec request.oas.validate_params() swift = request.registry.getUtility(ISwift) return swift.stat(userid)
def instance_view(request): ctx = request.context user_id = authenticated_userid(request) or Everyone permissions = get_permissions(user_id, ctx.get_discussion_id()) instance = ctx._instance if not instance.user_can(user_id, CrudPermissions.READ, permissions): return HTTPUnauthorized() view = ctx.get_default_view() or 'default' view = request.GET.get('view', view) return instance.generic_json(view, user_id, permissions)
def validAdminParms3(request, **kwargs): adminKey = 'admin:' + getAdminAccessToken(request) userKey = 'user:'******'email') # only root user can peek at other administrator accounts if not request.adminInRoot(adminKey,True) and \ request.hasAdminRole(userKey): raise HTTPUnauthorized("Unauthorized")
def forbidden_view(request): res = HTTPUnauthorized() res.www_authenticate = 'Basic realm="Secure Area"' return res
def make_401_error(message, realm_suffix='Update'): error = HTTPUnauthorized(headers=make_headers({'WWW-Authenticate': 'Basic realm="CLBC %s"' % realm_suffix})) error.content_type = "text/plain" error.text = message return error
def make_401_error(message, realm='CIOC RPC'): error = HTTPUnauthorized(headers=make_headers({'WWW-Authenticate': 'Basic realm="%s"' % realm})) error.content_type = "text/plain" error.text = message return error