Ejemplo n.º 1
0
 def post(self, election_id, candidate_id):
     if self.request.get("cancel_button") == "True":
         self.render_template("vote.html",
                              message="Your vote has been discarded")
         return
     election, candidate = self.ValidateElectionAndCandidate(
         election_id, candidate_id)
     current_user = users.get_current_user()
     if current_user is None:
         raise HTTPUnauthorized("You must be logged in to vote.")
     if election.HasAlreadyVoted(current_user):
         raise HTTPUnauthorized("You've already voted in this election.")
     election_active_state = election.CheckStartEndTime()
     if election_active_state == constants.NOT_STARTED:
         raise HTTPBadRequest("This election has not started yet.")
     elif election_active_state == constants.ENDED:
         raise HTTPBadRequest("This election has ended.")
     voter_id = election.GenerateVoterId(current_user)
     Vote(parent=candidate, voter=voter_id,
          election=str(election.key())).put()
     self.NotifyChannels(election)
     self.render_template(
         "vote.html",
         canvote=False,
         message="Thanks! Your vote for %s was registered." %
         candidate.name)
Ejemplo n.º 2
0
 def post(self, election_id):
     election = Election.get_by_id(long(election_id))
     if election is None:
         raise HTTPBadRequest("Invalid election id provided.")
     current_user = users.get_current_user()
     if current_user is None:
         raise HTTPUnauthorized("You must be logged in to vote.")
     if election.HasAlreadyVoted(current_user):
         raise HTTPUnauthorized("You've already voted in this election.")
     election_active_state = election.CheckStartEndTime()
     if election_active_state == constants.NOT_STARTED:
         raise HTTPBadRequest("This election has not started yet.")
     elif election_active_state == constants.ENDED:
         raise HTTPBadRequest("This election has ended.")
     candidate_id = self.request.get("candidate")
     if candidate_id is None:
         raise HTTPBadRequest("No candidate was provided.")
     candidate = Candidate.get_by_id(long(candidate_id), parent=election)
     if candidate is None:
         raise HTTPBadRequest("Invalid candidate id provided.")
     voter_id = election.GenerateVoterId(current_user)
     Vote(parent=candidate, voter=voter_id,
          election=str(election.key())).put()
     self.NotifyChannels(election)
     self.render_template("webvote.html",
                          canvote=False,
                          message="Thanks! Your vote has been recorded",
                          show_ads=election.ads_enabled)
Ejemplo n.º 3
0
def test_login_overlay():
    with h.login_overlay():
        raise HTTPUnauthorized()
    with h.login_overlay(exceptions=['foo']):
        raise HTTPUnauthorized()
    with td.raises(HTTPUnauthorized):
        with h.login_overlay(exceptions=['foobar']):
            raise HTTPUnauthorized()
Ejemplo n.º 4
0
 def __call__(self, env, start_response):
     if env['REQUEST_METHOD'] == 'GET':
         if self.status == 200:
             start_response(Response().status)
             start_response({'Content-Type': 'text/xml'})
             json_pattern = [
                 '"name":%s', '"last_modified":%s', '"hash":%s',
                 '"bytes":%s'
             ]
             json_pattern = '{' + ','.join(json_pattern) + '}'
             json_out = []
             for b in self.objects:
                 name = simplejson.dumps(b[0])
                 time = simplejson.dumps(b[1])
                 json_out.append(json_pattern % (name, time, b[2], b[3]))
             account_list = '[' + ','.join(json_out) + ']'
             return account_list
         elif self.status == 401:
             start_response(HTTPUnauthorized().status)
             start_response({})
         elif self.status == 404:
             start_response(HTTPNotFound().status)
             start_response({})
         else:
             start_response(HTTPBadRequest().status)
             start_response({})
     elif env['REQUEST_METHOD'] == 'PUT':
         if self.status == 201:
             start_response(HTTPCreated().status)
             start_response({})
         elif self.status == 401:
             start_response(HTTPUnauthorized().status)
             start_response({})
         elif self.status == 202:
             start_response(HTTPAccepted().status)
             start_response({})
         else:
             start_response(HTTPBadRequest().status)
             start_response({})
     elif env['REQUEST_METHOD'] == 'DELETE':
         if self.status == 204:
             start_response(HTTPNoContent().status)
             start_response({})
         elif self.status == 401:
             start_response(HTTPUnauthorized().status)
             start_response({})
         elif self.status == 404:
             start_response(HTTPNotFound().status)
             start_response({})
         elif self.status == 409:
             start_response(HTTPConflict().status)
             start_response({})
         else:
             start_response(HTTPBadRequest().status)
             start_response({})
Ejemplo n.º 5
0
 def wrap(ctx, request):
     header = request.headers.get(
         'Authorization')  # Authorization: Basic Y29teW46cGFzcw==
     print(header)
     if header is None:
         raise HTTPUnauthorized()
     user, password = b64decode(
         header.split()[-1].encode()).decode().split(':')
     if user == 'jkzhao' and password == 'pass':
         request.user = user
         return fn(ctx, request)
     raise HTTPUnauthorized()
Ejemplo n.º 6
0
 def wrap(ctx, request):
     token = request.headers.get('X-Authorization-Token')
     if token is None:
         raise HTTPUnauthorized()
     try:
         decoded = jwt.decode(token.encode(), __KEY, ['HS512'])
         user = decoded.get('user')
         if user is None:
             raise HTTPUnauthorized()
         request.user = user
         return fn(ctx, request)
     except Exception:
         raise HTTPUnauthorized()
Ejemplo n.º 7
0
 def __init__(self, request):
     super().__init__(request)
     token = request.headers.get('X-Authorization-Token')
     if token is None:
         raise HTTPUnauthorized()
     try:
         decoded = jwt.decode(token.encode(), KEY, ['HS512'])
         user = decoded.get('user')
         if user is None:
             raise HTTPUnauthorized()
         self.__principal = Principal('comyn', ['admin'])
     except Exception as e:
         logging.error(e)
         raise HTTPUnauthorized()
Ejemplo n.º 8
0
 def principal(self):
     if self.token is None:
         raise HTTPUnauthorized()
     try:
         decoded = jwt.decode(self.token.encode(), self.key, ['HS512'])
         user_id = decoded.get('user')
         if user_id is None:
             raise HTTPUnauthorized()
         user = User.query.filter(User.id == user_id).first()
         if user is None:
             raise HTTPUnauthorized()
         return user
     except Exception as e:
         logging.error(e)
         raise HTTPUnauthorized()
Ejemplo n.º 9
0
    def challenge(self, environ, status, app_headers, forget_headers):
        """Return a 401 page unconditionally."""
        headers = app_headers + forget_headers
        #remove content-length header
        headers = filter(lambda h:h[0].lower() != 'content-length', headers)

        # The HTTP status code and reason may not be the default ones:
        status_parts = self._HTTP_STATUS_PATTERN.search(status)
        reason = status_parts.group('reason')
        code = int(status_parts.group('code'))

        response = HTTPUnauthorized(headers=headers)
        response.title = reason
        response.code = code
        return response
Ejemplo n.º 10
0
    def challenge(self, environ, status, app_headers, forget_headers):
        """Return a 401 page unconditionally."""
        headers = app_headers + forget_headers
        #remove content-length header
        headers = filter(lambda h: h[0].lower() != 'content-length', headers)

        # The HTTP status code and reason may not be the default ones:
        status_parts = self._HTTP_STATUS_PATTERN.search(status)
        reason = status_parts.group('reason')
        code = int(status_parts.group('code'))

        response = HTTPUnauthorized(headers=headers)
        response.title = reason
        response.code = code
        return response
Ejemplo n.º 11
0
    def add_member(self, req, image_id, member, body=None):
        """
        Adds a membership to the image, or updates an existing one.
        If a body is present, it is a dict with the following format::

            {"member": {
                "can_share": [True|False]
            }}

        If "can_share" is provided, the member's ability to share is
        set accordingly.  If it is not provided, existing memberships
        remain unchanged and new memberships default to False.
        """
        if req.context.read_only:
            raise HTTPForbidden()
        elif req.context.owner is None:
            raise HTTPUnauthorized(_("No authenticated user"))

        # Figure out can_share
        can_share = None
        if body and 'member' in body and 'can_share' in body['member']:
            can_share = bool(body['member']['can_share'])
        try:
            registry.add_member(self.options, req.context, image_id, member,
                                can_share)
        except exception.NotFound, e:
            msg = "%s" % e
            logger.debug(msg)
            raise HTTPNotFound(msg, request=req, content_type='text/plain')
Ejemplo n.º 12
0
    def unauthorized(self, req):
        """Return unauthorized given a webob Request object.

        This can be stuffed into the evironment for chase.authorize or
        called from the authoriztion callback when authorization fails.
        """
        return HTTPUnauthorized(request=req)
Ejemplo n.º 13
0
    def __call__(self, env, start_response):
        if time() > self._rtime:
            self._reload()
        req = Request(env)
        account = env.get('HTTP_X_AUTH_USER')
        token = env.get('HTTP_X_AUTH_TOKEN', env.get('HTTP_X_STORAGE_TOKEN'))

        # check only 1st request
        # 2nd request will use token
        if token is None:
            # if can't get account, then try swift3
            if account is None:
                s = env.get('HTTP_AUTHORIZATION')
                #self.logger.info('s is %' % s)
                x = [x.strip() for x in s.split(':')]
                y = str(x[0]).split(' ')
                #self.logger.info('y[0] is %' % str(y[0]))
                if y[0] == "AWS":
                    account = y[1]
                    #self.logger.info('account for S3 v2 is %' % account)
                elif y[0] == "AWS4-HMAC-SHA256":
                    z = str(y[1].split("Credential=")[1])
                    account = z.split("/")[0]
                    #self.logger.info('account for S3 v4 is %' % str(account))
            if (account not in self.account_list):
                self.logger.info('%s is not allow to get token' % account)
                resp = HTTPUnauthorized(request=req,
                                        body="Account not in list")
                return resp(env, start_response)
            else:
                self.logger.info(
                    '%s is in account list and allow to get token' % account)
                return self.app(env, start_response)
        else:
            return self.app(env, start_response)
Ejemplo n.º 14
0
 def test_call_200_identity_reset(self):
     from webob.exc import HTTPUnauthorized
     environ = self._makeEnviron()
     headers = [('a', '1')]
     new_identity = {'user_id': 'foo', 'password': '******'}
     app = DummyIdentityResetApp('200 OK', headers, new_identity)
     challenge_app = HTTPUnauthorized()
     challenge = DummyChallenger(challenge_app)
     challengers = [('challenge', challenge)]
     credentials = {'login': '******', 'password': '******'}
     identifier = DummyIdentifier(credentials)
     identifiers = [('identifier', identifier)]
     authenticator = DummyAuthenticator()
     authenticators = [('authenticator', authenticator)]
     mw = self._makeOne(app=app,
                        challengers=challengers,
                        identifiers=identifiers,
                        authenticators=authenticators)
     start_response = DummyStartResponse()
     result = mw(environ, start_response)
     self.assertEqual(environ.get('challenged'), None)
     self.assertEqual(identifier.forgotten, False)
     new_credentials = identifier.credentials.copy()
     new_credentials['login'] = '******'
     new_credentials['password'] = '******'
     # @@ unfuck
     ##         self.assertEqual(identifier.remembered, new_credentials)
     self.assertEqual(environ['REMOTE_USER'], 'chris')
Ejemplo n.º 15
0
    def create_response_for_invalid_auth_token(self, req):

        error = LoadBalancerFaultException("Invalid authentication token. Please renew")
                                                     
        content_type, detail = self.get_error_body(req, error) 
 
	return HTTPUnauthorized(body=detail, content_type=content_type, request=req)
Ejemplo n.º 16
0
 def test_call_200_challenger_and_identifier_and_authenticator(self):
     from webob.exc import HTTPUnauthorized
     environ = self._makeEnviron()
     headers = [('a', '1')]
     app = DummyWorkingApp('200 OK', headers)
     challenge_app = HTTPUnauthorized()
     challenge = DummyChallenger(challenge_app)
     challengers = [('challenge', challenge)]
     credentials = {'login': '******', 'password': '******'}
     identifier = DummyIdentifier(credentials)
     identifiers = [('identifier', identifier)]
     authenticator = DummyAuthenticator()
     authenticators = [('authenticator', authenticator)]
     mw = self._makeOne(app=app,
                        challengers=challengers,
                        identifiers=identifiers,
                        authenticators=authenticators)
     start_response = DummyStartResponse()
     result = mw(environ, start_response)
     self.assertEqual(environ.get('challenged'), None)
     self.assertEqual(identifier.forgotten, False)
     # @@ figure out later
     ##         self.assertEqual(dict(identifier.remembered)['login'], dict(identifier.credentials)['login'])
     ##         self.assertEqual(dict(identifier.remembered)['password'], dict(identifier.credentials)['password'])
     self.assertEqual(environ['REMOTE_USER'], 'chris')
Ejemplo n.º 17
0
    def create_response_for_missing_auth_token(self, req):

        error = LoadBalancerFaultException("Missing authentication token. Please provide the authentication token in the X-Auth-Token header of the request")
                                                     
        content_type, detail = self.get_error_body(req, error) 
 
	return HTTPUnauthorized(body=detail, content_type=content_type, request=req)
Ejemplo n.º 18
0
 def has_permissions(self, permissions=None):
     if self.principal is None:
         raise HTTPUnauthorized()
     if not permissions:
         return True
     if set(getattr(self.principal, 'roles', [])).intersection(permissions):
         return True
     raise HTTPForbidden()
Ejemplo n.º 19
0
 def denied_response(self, req):
     """
     Returns a standard WSGI response callable with the status of 403 or 401
     depending on whether the REMOTE_USER is set or not.
     """
     if req.remote_user:
         return HTTPForbidden(request=req)
     else:
         return HTTPUnauthorized(request=req)
Ejemplo n.º 20
0
def edit_account_view(context, request):
    confirmed = request.registry.queryAdapter(context,
                                              IRegistrations,
                                              name='confirmed')
    if confirmed is None:  #pragma NO COVERAGE
        confirmed = ConfirmedRegistrations(context)

    identity = request.environ.get('repoze.who.identity')
    if identity is None:
        return HTTPUnauthorized()

    userid = identity['repoze.who.userid']
    account_info = confirmed.get(userid)
    if account_info is None:
        return HTTPForbidden()

    appstruct = {
        'login_name': account_info.login,
        'email': account_info.email,
        'security': {
            'question': account_info.security_question or '',
            'answer': account_info.security_answer or '',
        },
    }
    schema = EditAccount().bind(current_login_name=account_info.login,
                                confirmed=confirmed,
                                old_password=account_info.password)
    form = Form(schema, buttons=('update', ))
    rendered_form = form.render(appstruct)

    if 'update' in request.POST:
        try:
            appstruct = form.validate(request.POST.items())
        except ValidationFailure, e:
            rendered_form = e.render()
        else:
            login = appstruct['login_name']
            email = appstruct['email']
            pwd_mgr = SSHAPasswordManager()
            password = pwd_mgr.encodePassword(appstruct['password'])
            security_question = appstruct['security']['question']
            security_answer = appstruct['security']['answer']
            confirmed.set(
                userid,
                email=email,
                login=login,
                password=password,
                security_question=security_question,
                security_answer=security_answer,
            )
            return HTTPFound(location=view_url(
                context,
                request,
                'after_edit_url',
                request.view_name,
            ))
Ejemplo n.º 21
0
 def __call__(self, environ, start_response):
     try:
         LOG.debug('path_info: %s' % environ['PATH_INFO'])
         account = environ['PATH_INFO'].lstrip('/').split('/', 1)[0]
         LOG.debug('account: %s' % account)
     except IndexError:
         LOG.debug('Unable to pull account from request path')
         return HTTPNotFound()(environ, start_response)
     try:
         token = environ['HTTP_X_AUTH_TOKEN']
     except KeyError:
         LOG.debug('Unable to pull token from request headers')
         return HTTPUnauthorized()(environ, start_response)
     try:
         LOG.debug('Validate token')
         token_info = self.get_token_info(token, account)
     except InvalidUserToken, e:
         LOG.info('Invalid token (%s)' % e)
         return HTTPUnauthorized()(environ, start_response)
 def _raise_challenge(self, request):
     """Raise a HTTPUnauthorized to challenge for credentials."""
     api = self._api_factory(request.environ)
     # Get a WSGI app that will send the challenge.
     challenge_app = api.challenge()
     # If no challengers are configured, they just get 401 Unauthorized.
     if challenge_app is None:
         raise HTTPUnauthorized()
     # Otherwise, we use the response generated by the challenger.
     status, headers, app_iter = request.call_application(challenge_app)
     assert status.startswith("401 ")
     # Ensure that all IIdentifiers will forget the remembered login.
     logout_headers = api.logout()
     for header in logout_headers:
         if header not in headers:
             headers.append(header)
     raise HTTPUnauthorized(headerlist=list(headers),
                            app_iter=app_iter,
                            request=request)
Ejemplo n.º 23
0
    def __call__(self, env, start_response):
        # Validate the request is trusted
        # Authenticate the Auth component itself.
        headers = [('www-authenticate', 'Basic realm="API Auth"')]
        if 'HTTP_AUTHORIZATION' not in env:
            # Redirect to proxy (auth component) and show that basic auth is
            # required
            return HTTPUseProxy(location=self.proxy_location,
                                headers=headers)(env, start_response)
        else:
            auth_type, encoded_creds = env['HTTP_AUTHORIZATION'].split(None, 1)
            if encoded_creds != self.remote_auth_pass:
                return HTTPUnauthorized(headers=headers)(env, start_response)

        # Make sure that the user has been authenticated by the Auth Service
        if 'HTTP_X_AUTHORIZATION' not in env:
            return HTTPUnauthorized()(env, start_response)

        return self.app(env, start_response)
Ejemplo n.º 24
0
 def get(self):
     if users.get_current_user() is None:
         raise HTTPUnauthorized("You must be logged in to view this page.")
     elections = Election.GetElections(users.get_current_user())
     for election in elections:
         election.id = election.key().id()
         election.candidates = election.GetCandidates()
         for candidate in election.candidates:
             candidate.vote_count = candidate.GetVoteCount()
     self.render_template("myelections.html", elections=elections)
Ejemplo n.º 25
0
 def __call__(self, env, start_response):
     if env['REQUEST_METHOD'] == 'GET' or env['REQUEST_METHOD'] == 'HEAD':
         if self.status == 200:
             start_response(Response().status)
             start_response(self.response_headers)
             if env['REQUEST_METHOD'] == 'GET':
                 return self.object_body
         elif self.status == 401:
             start_response(HTTPUnauthorized().status)
             start_response({})
         elif self.status == 404:
             start_response(HTTPNotFound().status)
             start_response({})
         else:
             start_response(HTTPBadRequest().status)
             start_response({})
     elif env['REQUEST_METHOD'] == 'PUT':
         if self.status == 201:
             start_response(HTTPCreated().status)
             start_response({'etag': self.response_headers['etag']})
         elif self.status == 401:
             start_response(HTTPUnauthorized().status)
             start_response({})
         elif self.status == 404:
             start_response(HTTPNotFound().status)
             start_response({})
         else:
             start_response(HTTPBadRequest().status)
             start_response({})
     elif env['REQUEST_METHOD'] == 'DELETE':
         if self.status == 204:
             start_response(HTTPNoContent().status)
             start_response({})
         elif self.status == 401:
             start_response(HTTPUnauthorized().status)
             start_response({})
         elif self.status == 404:
             start_response(HTTPNotFound().status)
             start_response({})
         else:
             start_response(HTTPBadRequest().status)
             start_response({})
def check_auth(request):
    """Controls the Authorization header and returns the username and the
    collection.

    Raises a 401 in these cases:

    - If the header is not present or unrecognized
    - If the request path is not *owned* by that user
    - the database token

    The header is of the form:

        AppSync b64(assertion):b64(username):b64(token)

    """
    user = request.matchdict['user']
    collection = request.matchdict['collection']
    auth = request.environ.get('HTTP_AUTHORIZATION')
    mock_browserid = request.registry.get('mock_browserid')
    if mock_browserid:
        return user, collection, None

    if auth is None:
        raise HTTPUnauthorized('No authorization provided')

    if not auth.startswith('AppSync '):
        logger.error('Attempted auth with bad type (not AppSync): %r' % auth)
        raise HTTPUnauthorized('Invalid token; expected Authorization type '
                               'AppSync')

    auth = auth[len('AppSync '):].strip()
    auth_part = auth.split(':')
    if len(auth_part) != 3:
        logger.error('Attempted auth with bad value (not x:y:z): %r' % auth)
        raise HTTPUnauthorized('Invalid token; invalid format')

    try:
        auth_part = [b64dec(part) for part in auth_part]
    except (binascii.Error, ValueError), e:
        logger.error('Attempted auth with invalid base64 content'
                     ': %r (%s)' % (auth, e))
        raise HTTPUnauthorized('Invalid token: invalid base64 encoding')
    def change_password(self, request):
        """Changes the user's password

        Takes a classical authentication or a reset code
        """
        # the body is in plain text utf8 string
        new_password = request.body.decode('utf8')

        if not valid_password(request.user.get('username'), new_password):
            raise HTTPBadRequest('Password should be at least 8 '
                                 'characters and not the same as your '
                                 'username')

        key = request.headers.get('X-Weave-Password-Reset')

        if key is not None:
            user_id = self.auth.get_user_id(request.user)

            if user_id is None:
                raise HTTPNotFound()

            if not self.reset.verify_reset_code(request.user, key):
                log_cef('Invalid Reset Code submitted',
                        5,
                        request.environ,
                        self.app.config,
                        request.user['username'],
                        'InvalidResetCode',
                        submitedtoken=key)

                raise HTTPJsonBadRequest(ERROR_INVALID_RESET_CODE)

            if not self.auth.admin_update_password(request.user, new_password,
                                                   key):
                raise HTTPInternalServerError('Password change failed '
                                              'unexpectedly.')
        else:
            # classical auth
            self.app.auth.authenticate_user(request, self.app.config,
                                            request.user['username'])

            if request.user['userid'] is None:
                log_cef('User Authentication Failed', 5, request.environ,
                        self.app.config, request.user['username'],
                        AUTH_FAILURE)
                raise HTTPUnauthorized()

            if not self.auth.update_password(
                    request.user, request.user_password, new_password):
                raise HTTPInternalServerError('Password change failed '
                                              'unexpectedly.')

        return text_response('success')
Ejemplo n.º 28
0
def valid_token(request):
    header = 'X-Messaging-Token'

    token = request.headers.get(header)
    if token is None:
        raise HTTPUnauthorized()

    token = token.split('-')
    if len(token) != 2:
        raise HTTPUnauthorized()

    user, token = token

    valid = user in _USERS and _USERS[user] == token
    #print("===== debugging _USERS =====")
    #print(_USERS)
    #print("===========================")
    if not valid:
        raise HTTPUnauthorized()

    request.validated['user'] = user
Ejemplo n.º 29
0
 def _validate_auth_url(self, auth_url):
     """Validate auth_url to ensure it can be used."""
     if not auth_url:
         raise HTTPBadRequest(
             _('Request missing required header '
               'X-Auth-Url'))
     allowed = cfg.CONF.auth_password.allowed_auth_uris
     if auth_url not in allowed:
         raise HTTPUnauthorized(
             _('Header X-Auth-Url "%s" not an allowed '
               'endpoint') % auth_url)
     return True
Ejemplo n.º 30
0
 def _validate_auth_url(self, env, start_response, auth_url):
     """Validate auth_url to ensure it can be used."""
     if not auth_url:
         resp = HTTPBadRequest(
             _('Request missing required header '
               'X-Auth-Url'))
         return resp(env, start_response)
     allowed = cfg.CONF.auth_password.allowed_auth_uris
     if allowed and not auth_url in allowed:
         resp = HTTPUnauthorized(
             _('Header X-Auth-Url "%s" not allowed') % auth_url)
         return resp(env, start_response)
     return None
Ejemplo n.º 31
0
 def test_call_401_no_identifiers(self):
     from webob.exc import HTTPUnauthorized
     environ = self._makeEnviron()
     headers = [('a', '1')]
     app = DummyWorkingApp('401 Unauthorized', headers)
     challenge_app = HTTPUnauthorized()
     challenge = DummyChallenger(challenge_app)
     challengers = [('challenge', challenge)]
     mw = self._makeOne(app=app, challengers=challengers)
     start_response = DummyStartResponse()
     result = b''.join(mw(environ, start_response)).decode('ascii')
     self.assertEqual(environ['challenged'], challenge_app)
     self.assertTrue(result.startswith('401 Unauthorized'))
 def _login(self, environ, start_response):
     response = HTTPUnauthorized()
     response.www_authenticate = ('Basic', {'realm': self._realm})
     return response(environ, start_response)