示例#1
0
def lambda_handler(event, context):

    logger.info(event)

    resp = ssm_client.get_parameter(Name=os.environ['SSM_PUBLIC_KEY_NAME'], )
    if resp["Parameter"]["Value"]:
        public_key = resp["Parameter"]["Value"]
    else:
        raise NameError("Public Key was not found within ssm response.")

    public_key = base64.b64decode(public_key).decode("utf-8")

    client_token = event['authorizationToken']

    method_arn = event['methodArn']

    tmp = method_arn.split(':')

    api_gateway_arn_tmp = tmp[5].split('/')

    method = api_gateway_arn_tmp[2]

    resource = re.search('(?<=\d{12}\/).*$', method_arn).group(0)

    aws_account_id = tmp[4]

    principal_id = str(uuid.uuid4())

    policy = AuthPolicy(principal_id, aws_account_id)
    policy.rest_api_id = api_gateway_arn_tmp[0]
    policy.region = tmp[3]
    policy.stage = api_gateway_arn_tmp[1]

    guid = RESOURCES_GUID[resource][method]

    try:
        auth.validate_token(client_token, public_key, guid)
    except Exception as e:
        logger.error(e)
        raise Exception("Unauthorized")

    policy.allow_method(method, '*')

    auth_response = policy.build()

    logger.info(auth_response)

    return auth_response
 def wrapper(*args, **kwargs):
     auth = request.headers.get('Authorization', None)
     if (not auth):
         return "Required Auth Token in Header", 400
     token = auth.split(" ")[1]
     if not validate_token(token):
         resp = make_response({"message": "Invalid Token"})
         return resp, 400
     return func(*args, **kwargs)
示例#3
0
def home():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        try:
            assert (len(username) >= 2 and len(username) <= 40)
            assert (len(password) >= 2 and len(password) <= 40)
            token = auth.generate_token(username, password)
            response = make_response(
                render_template('index.html', data=auth.validate_token(token)))
            response.set_cookie('token', token)
            return response
        except:
            return 'invalid username and/or password'
    else:
        token = request.cookies.get('token')
        if token:
            return render_template('index.html',
                                   data=auth.validate_token(token))
        else:
            return render_template('index.html')
示例#4
0
def intercept_login():
    """Intercepts every request and checks if the user is logged in."""
    if 'username' not in session and request.endpoint is not None and request.endpoint != 'login' and request.endpoint != 'api_login' and request.endpoint != 'static':
        if request.headers.get('token') is None:
            return redirect(url_for('login'))
        else:
            api_user = auth.validate_token(request.headers.get('token'))
            if api_user is None:
                raise InvalidRequestData('Invalid authentication token.')
            return
    
    # Sessions last for 30 minutes before having to login again
    session.permanent = True
    app.permanent_session_lifetime = timedelta(minutes=30)
    return
示例#5
0
    def users_who():
        #This endpoint will tell if the user should pass or not
        #and if his token expired, it will refresh it
        the_401_error = jsonify({
            "error": 401,
            "message": "unauthorized",
            "success": False
        })
        the_401_error.headers.add("Authorization", "")

        if "Authorization" not in request.headers:
            return the_401_error, 401
        #Now the cookie exists
        token = request.headers["Authorization"]
        #print(SECRET,flush=True)
        #print(request.cookies,flush=True)
        token_validation = validate_token(token=token, secret=SECRET)
        #print(token_validation,flush=True)
        #print("WHO: "+str(token_validation),flush=True)
        if token_validation["case"] == 3:
            return the_401_error, 401

        if token_validation["case"] == 2:
            res = jsonify({"success": True})
            user_id = token_validation["payload"]["uid"]
            response = auth_cookie_response(response={
                "success": True,
                "result": "refreshed expired token",
                "user_id": user_id
            },
                                            user_id=user_id)
            return response
        else:
            res = jsonify({
                "success": True,
                "result": "user is logged in",
                "user_id": token_validation["payload"]["uid"]
            })
            res.headers.add("Authorization", token)
            return res
示例#6
0
文件: tests.py 项目: ramuta/bit2me
 def test_token(self):
     token = generate_token(userid='12345', secret=secret_string)
     self.assertTrue(validate_token(token=token, secret=secret_string))
def post_tokens(content, parameters):
    received_auth = get_entity(content, 'auth')
    try:
        if 'passwordCredentials' in received_auth:
            password_credentials = received_auth['passwordCredentials']
            user_at_domain = password_credentials['username']
            user_password = password_credentials['password']
            token = auth.create_token(user_at_domain=user_at_domain,
                                      user_password=user_password)
        else:
            token = received_auth['token']['id']
    except KeyError as e:
        raise BadRequestError(e)

    if not auth.validate_token(token):
        raise auth.Forbidden()

    neutronurl = neutron_url()
    keystoneurl = keystone_url()
    novaurl = nova_url_with_version()
    region = openstack_region()
    neutron_id = openstack_neutron_id()
    keystone_id = openstack_keystone_id()

    # OpenStack Identity API v2.0 specifies HTTP 200 as return code for
    # successful token creation
    http_code = httplib.OK

    return Response(
        {
            'access': {
                'token': {
                    'id': token,
                    'expires': _get_token_expires()
                },
                'user': {
                    'username': '******',
                    'roles_links': [],
                    'id': '',
                    'roles': [{
                        'name': 'admin'
                    }],
                    'name': 'admin'
                },
                'serviceCatalog': [{
                    'endpoints': [{
                        'adminURL': neutronurl,
                        'internalURL': neutronurl,
                        'publicURL': neutronurl,
                        'region': region,
                        'id': neutron_id,
                    }],
                    'endpoints_links': [],
                    'type':
                    'network',
                    'name':
                    'neutron',
                }, {
                    'endpoints': [{
                        'adminURL': keystoneurl,
                        'region': region,
                        'internalURL': keystoneurl,
                        'id': keystone_id,
                        'publicURL': keystoneurl
                    }],
                    'endpoints_links': [],
                    'type':
                    'identity',
                    'name':
                    'keystone'
                }, {
                    'endpoints': [{
                        'adminURL': novaurl,
                        'region': region,
                        'internalURL': novaurl,
                        'id': keystone_id,
                        'publicURL': novaurl
                    }],
                    'endpoints_links': [],
                    'type':
                    'compute',
                    'name':
                    'nova'
                }]
            },
        },
        code=http_code)
示例#8
0
 def call_response_handler(self, response_handler, content, parameters):
     if not validate_token(
             self.headers.get(TOKEN_HTTP_HEADER_FIELD_NAME, '')):
         raise Forbidden()
     with OvnNorth() as ovn_north:
         return response_handler(ovn_north, content, parameters)