Esempio n. 1
0
    def test_register(self):
        response = self.app.get("/registration")

        # get should return 405
        assert response.status_code == 405

        response = self.app.post("/registration")

        # should return bad request with missing username and pasword
        assert response.status_code == 400

        payload = json.dumps({"username": "******", "password": "******"})

        response = self.app.post("/registration",
                                 headers={"Content-Type": "application/json"},
                                 data=payload)

        # new user created, OK
        assert response.status_code == 200

        # check db for new user
        new_user = UserModel.query.filter_by(username="******").first()

        assert new_user.username == "new_user"
        assert not new_user.username == "new_wrong_user"
        assert UserModel.verify_hash("pass", new_user.password)
        assert not UserModel.verify_hash("pass123", new_user.password)
    def setUp(self):
        db.create_all()
        self.app = app.test_client()

        db.session.add(
            UserModel(username="******", password=UserModel.generate_hash("pass"))
        )
        db.session.commit()
    def post(self):
        data = UserRegister.parser.parse_args()

        if UserModel.find_by_username(data['username']):
            return {"message": "A user with that username already exists"}, 400

        user = UserModel(data['username'], data['password'])
        user.save_to_db()

        return {"message": "User created successfully"}, 201
Esempio n. 4
0
    def setUp(self):
        db.create_all()
        self.app = app.test_client()

        db.session.add(
            UserModel(username="******", password=UserModel.generate_hash("pass"))
        )
        db.session.commit()

        atoken = self.login()

        xs, fs = self.get_xs_and_fs()

        payload = json.dumps(
            {
                "problem_type": "Discrete",
                "name": "discrete_test_problem",
                "objectives": fs,
                "objective_names": ["f1", "f2", "f3"],
                "variables": xs,
                "variable_names": [
                    "x1",
                    "x2",
                    "x3",
                    "x4",
                    "x5",
                    "x6",
                    "x7",
                    "x8",
                    "x9",
                    "x10",
                    "x11",
                ],
            }
        )

        response = self.app.post(
            "/problem/create",
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {atoken}",
            },
            data=payload,
        )

        if response.status_code != 201:
            # ABORT, failed to add problem to DB!
            self.tearDown()
            pytest.exit(
                f"FATAL ERROR: Could not add problem during setup in {__file__}."
            )
            exit()
Esempio n. 5
0
def authenticate(username, password):
    #user = username_mapping.get(username,None)
    user = UserModel.find_by_username(username)
    #if user and user.password = password:
    if user and safe_str_cmp(user.password, password):
        #return {"Good Job": user}
        return user
Esempio n. 6
0
    def post(self):

       data = UserRegister.parser.parse_args()
       if  UserModel.find_by_username(data['username']):
            return {"message":"User name already exist"}, 400
       user = UserModel(data['username'], data['password']) # OR Just user = UserModel(**data)
       user.save_to_db()

        #connection = sqlite3.connect('samdata.db')
       # cursor = connection.cursor()
       #
       # query = " INSERT INTO users VALUES (NULL, ?, ?)"
       # cursor.execute(query,( data['username'], data['password']) )
       # connection.commit()
       # connection.close()

       return {"message": "User created sucessfully"}, 201
    def setUp(self):
        db.create_all()
        self.app = app.test_client()

        db.session.add(
            UserModel(username="******",
                      password=UserModel.generate_hash("pass")))
        db.session.commit()

        user_id = UserModel.query.filter_by(username="******").first().id

        # add DTLZ2 for test_user
        problem = problem_builder("DTLZ2", n_of_variables=5, n_of_objectives=4)
        db.session.add(
            Problem(
                name="DTLZ2",
                problem_type="Analytical",
                problem_pickle=problem,
                user_id=user_id,
                minimize="[1, 1, 1, 1]",
            ))
        db.session.commit()
Esempio n. 8
0
    def post(self):
        data = parser.parse_args()
        current_user = UserModel.find_by_username(data["username"])

        if not current_user:
            return {"message": f"User {data['username']} does not exist!"}, 401

        try:
            if UserModel.verify_hash(data["password"], current_user.password):
                access_token = create_access_token(identity=data["username"])
                refresh_token = create_refresh_token(identity=data["username"])
                return {
                    "message": f"Logged as {current_user.username}",
                    "access_token": access_token,
                    "refresh_token": refresh_token,
                }, 200
        except Exception as e:
            print(f"DEBUG: {e}")
            return {"message": "Something went wrong."}, 500

        else:
            return {"message": "Wrong credentials"}, 401
Esempio n. 9
0
class LoginService:
    """
    TODO doc
    """
    def __init__(self, otp_digits=4):
        self.otp_digits = otp_digits
        self.user_model = UserModel()

    def create_user(self, name, surname, email, password):
        if name and surname and email and password:
            api_key = self.encrypt_string(email, password)
            return self.user_model.create(name, surname, email, api_key)

    def user_exist(self, email, api_key):
        return self.user_model.get_user(email, api_key)

    def set_otp_code(self, email, api_key):
        otp_code = self.generate_otp()
        self.user_model.create_otp(api_key, otp_code)
        if send_otp(email, otp_code):
            return True
        return False

    def clear_otp(self, api_key, otp):
        return self.user_model.delete_otp(api_key, otp)

    def user_login(self, email, api_key, otp):
        return self.user_model.get_user_with_otp(email, api_key, otp)

    def send_reset_pw(self, email, password):
        if self.user_model.get_user(email,
                                    self.encrypt_string(email, password)):
            return send_reset_password(email)
        return True

    # SHA256 - ENCRYPT
    def encrypt_string(self, email, password):
        hash_string = email + password + email.split('@')[0]
        sha_signature = \
            hashlib.sha256(hash_string.encode()).hexdigest()
        return sha_signature

    def generate_otp(self):
        return randint(1000, 9999)

    def check_api_key(self, key):
        return self.user_model.check_api_key(key)
Esempio n. 10
0
    def post(self):
        data = parser.parse_args()

        if UserModel.find_by_username(data["username"]):
            return {"message": f"User {data['username']} already exists!"}, 400

        new_user = UserModel(username=data["username"],
                             password=UserModel.generate_hash(
                                 data["password"]))
        try:
            new_user.save_to_db()
            access_token = create_access_token(identity=data["username"])
            refresh_token = create_refresh_token(identity=data["username"])
            return {
                "message": f"User {data['username']} was created!",
                "access_token": access_token,
                "refresh_token": refresh_token,
            }, 200
        except Exception as e:
            print(f"DEBUG: {e}")
            return {"message": "Something went wrong"}, 500
Esempio n. 11
0
 def __init__(self, otp_digits=4):
     self.otp_digits = otp_digits
     self.user_model = UserModel()
Esempio n. 12
0
def identity(payload):
    user_id = payload['identity']
    #return userid_mapping.get(user_id, None)
    return UserModel.find_by_id(user_id)
Esempio n. 13
0
def authenticate(username, password):
    user = UserModel.find_by_username(username)
    # safe_str_cmp function provides safe string comparison
    if user and safe_str_cmp(user.password, password):
        return user
Esempio n. 14
0
def identity(payload):
    user_id = payload['identity']
    return UserModel.find_by_id(user_id)
Esempio n. 15
0
 def get(self):
     return UserModel.return_all()
Esempio n. 16
0
 def __init__(self):
     super().__init__()
     self.user_data = UserModel()
Esempio n. 17
0
def add_user(username, password):
    db.session.add(
        UserModel(username=username,
                  password=UserModel.generate_hash(password)))
    db.session.commit()
Esempio n. 18
0
 def delete(self):
     return UserModel.delete_all()
Esempio n. 19
0
    def setUp(self):
        db.create_all()
        self.app = app.test_client()

        db.session.add(
            UserModel(username="******", password=UserModel.generate_hash("pass"))
        )
        db.session.add(
            UserModel(username="******", password=UserModel.generate_hash("pass"))
        )
        db.session.commit()

        payload = json.dumps({"username": "******", "password": "******"})
        response = self.app.post(
            "/login", headers={"Content-Type": "application/json"}, data=payload
        )
        data = json.loads(response.data)

        access_token = data["access_token"]

        problem_def = {
            "problem_type": "Analytical",
            "name": "setup_test_problem_1",
            # "objective_functions": ["x / y - z", "y / x - z", "z+y+x"],
            "objective_functions": ["x + 3*y - z", "y - 3*x + z", "3*z - y + x"],
            "objective_names": ["f1", "f2", "f3"],
            "variables": ["x", "y", "z"],
            "variable_initial_values": [0, 0, 0],
            "variable_bounds": [[-10, 10], [-10, 10], [-10, 10]],
            "variable_names": ["x", "y", "z"],
            "nadir": [10, 20, 30],
            "ideal": [-10, -20, -30],
            "minimize": [1, 1, 1],
        }

        payload = json.dumps(problem_def)
        response = self.app.post(
            "/problem/create",
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {access_token}",
            },
            data=payload,
        )

        problem_def["name"] = "setup_test_problem_2"
        payload = json.dumps(problem_def)
        response = self.app.post(
            "/problem/create",
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {access_token}",
            },
            data=payload,
        )

        problem_def["name"] = "setup_test_problem_3"
        payload = json.dumps(problem_def)
        response = self.app.post(
            "/problem/create",
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {access_token}",
            },
            data=payload,
        )

        assert response.status_code == 201