async def setUp(self):
     super(TestAuth, self).setUp()
     UserStorage.clear_storage()
     await self.initialize([
         partial_cls(AttestationCommunity, working_directory=':memory:'),
         partial_cls(IdentityCommunity, working_directory=':memory:')
     ], 2)
def read_credentials_file():
    """
    Put credentials in User Storage.
    """
    # Check if the file exists.
    if path.exists(working_directory) and stat(working_directory).st_size != 0:
        # Write your credentials to User.UserStorage.
        UserStorage.set_storage(json.load(open(working_directory)))
Ejemplo n.º 3
0
 async def setUp(self):
     super(TestCertificateEndpoint, self).setUp()
     if os.path.exists('resource/credentials.txt'):
         os.remove('resource/credentials.txt')
     await self.initialize([
         partial_cls(AttestationCommunity, working_directory=':memory:'),
         partial_cls(IdentityCommunity, working_directory=':memory:')
     ], 2)
     hashed_pw = bcrypt.hashpw('password'.encode('utf-8'),
                               bcrypt.gensalt()).decode("utf-8")
     UserStorage.create_user(id='user', password=hashed_pw)  # nosec
     await self.log_in(self.nodes[0])
    async def test_with_wrong_password(self):
        """
        Test a (POST: login) request while giving wrong credentials.
        """
        UserStorage.create_user(id='user', password=self.hashed_pw)

        response = await self.make_request(
            self.nodes[0],  # nosec
            'attestation/login',
            'POST',
            {},
            auth=True,
            user="******",
            password="******")
        self.assertEqual(response, {'message': 'Wrong credentials'},
                         "The given credentials should be invalid.")
async def register(request):
    """
    Register handler. Checks if you already registered, if not persist the
    user. Registration is done by checking the x-registration header. It is in
    the form password:is_attester in base64 form.
    """
    read_credentials_file()
    if UserStorage.registered():
        return Response({'message': 'Already registered'}, status=400)
    cred = request.headers.get('x-registration')
    cred = b64decode(cred.encode('utf-8')).decode('utf-8').split(':')
    pwd = cred[0].encode('utf8')
    hashed_pw = bcrypt.hashpw(pwd, bcrypt.gensalt()).decode("utf-8")
    UserStorage.create_user("user", hashed_pw, cred[1])
    write_credentials_file()
    return Response({'success': True}, status=200)
    async def test_login(self):
        """
        Test a (POST: login) request.
        """
        UserStorage.create_user(id='user', password=self.hashed_pw)
        auth.write_credentials_file()

        response = await self.make_request(
            self.nodes[0],  # nosec
            'attestation/login',
            'POST',
            {},
            auth=True,
            user="******",
            password="******")
        self.assertTrue("token" in response,
                        "The given credentials should be valid.")
def write_credentials_file():
    """
    Write credentials to file.
    """
    f = open(working_directory, 'w')
    # To serialize a simple class  to JSON in python, we can call __dict__.
    f.write(json.dumps(UserStorage.get_storage().__dict__))
    f.close()
    async def test_already_registered(self):
        """
        Test a (POST : register) request while already registered.
        :return:
        """
        UserStorage.create_user(id='user', password="******")  # nosec

        response = await self.make_request(
            self.nodes[0],  # nosec
            'attestation/register',
            'POST',
            {},
            register=True,
            user="******",
            password="******",
            doc=0)
        self.assertEqual(response, {'message': 'Already registered'},
                         "The user should already be registered.")
async def auth_middleware(request, handler):
    """
    Middleware that gets the JWT token in the "authorization" header. Checks
    if this JWT token is valid and not
    expired. Passes the result to the login_required_middleware.
    """
    request.user = None
    auth_type = request.headers.get('WWW-Authorization', None)
    jwt_token = request.headers.get('Authorization', None)
    if jwt_token and not auth_type == 'Basic':
        try:
            jwt.decode(jwt_token, JWT_SECRET, algorithms=[JWT_ALGORITHM])
        except (jwt.DecodeError, jwt.ExpiredSignatureError):
            return Response({'message': 'Token is invalid'}, status=400)

        request.user = UserStorage.get_storage()
    return await handler(request)
async def login(request):
    """
    Login handler which fetches the password from the body and compares it
    to the saved password. If they match up,
    returns a JWT token.
    """
    read_credentials_file()
    auth = request.headers.get('Authorization')
    auth = b64decode(auth.encode('utf-8')).decode('utf-8').split(':')
    user = UserStorage.get_storage()
    if user is None:
        return Response({'message': 'Not registered'}, status=417)

    if user.match_password(auth[1]) is False:
        return Response({'message': 'Wrong credentials'}, status=403)

    payload = {'user_id': user.id, 'is_attester': user.is_attester}
    jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM)
    return Response({'token': jwt_token.decode('utf-8')}, status=200)
Ejemplo n.º 11
0
        _isk_value = {}
        total = 0
        for idx, value in extracted.items():
            _isk_value[idx] = value * self.ore[idx]['IskValueRaw']
            total += _isk_value[idx]
        _isk_value['Total'] = total
        return _isk_value


if __name__ == '__main__':
    import time
    from ledgerParser import parseLedgerV2
    f = open("rawtest.txt", 'r')
    ledger = f.read()
    start = time.time()
    us = UserStorage()
    belt = ORE()  # Init belt values
    extracted = parseLedgerV2(
        ledger)  # Normally it will get user extraction info
    calc = Calc(
        belt._ore,
        belt.AvgBeltQuantity())  # Init calc object with average distribution
    for user in ['Kkuette', 'Alastyel']:
        usr = User(user)  # Init user
        usr.setExtracted(extracted)
        usr.setReward(calc.calcReward(
            extracted))  # Calc reward from user extraction info
        us.addUser(usr)

    for user in us.users:
        print(user.name, user.getExtracted(), user.getReward())