コード例 #1
0
def register_user():
    first_name = request.json.get('firstName')
    last_name = request.json.get('lastName')
    username = request.json.get('username')
    password = request.json.get('password')
    email = request.json.get('email')

    user_validator = Validator()
    user_validator.validate(request.json, get_json("user_schema"))
    if user_validator.errors:
        abort(make_response(jsonify(errors=user_validator.errors), 403))

    if None in [first_name, last_name, username, password, email]:
        abort_with_message("Form not complete", 400)
    if User.query.filter_by(username=username).first() is not None:
        abort_with_message("User already registered", 400)

    user = User(
        first_name=first_name,
        last_name=last_name,
        username=username,
        email=email)
    user.hash_password(password)

    db.session.add(user)
    db.session.commit()
    ThreadedEmail(email).start()
    return jsonify({'id': user.id}), 201, {'Location': url_for('user_api.get_user_by_id', _id=user.id, _external=True)}
コード例 #2
0
 def create_user(just_phone: bool = False):
     user = User(password='******',
                 first_name='first name',
                 last_name='last name',
                 phone='9121234567',
                 email='*****@*****.**')
     if just_phone:
         user.email = None
     user_id = UserHandler.create_user(user)
     return user_id
コード例 #3
0
def change_password(db: alchemy, user: User, password: str,
                    settings: AuthSettings):
    db.add(UsedPassword(password=user.password, user_id=user.id))
    user.password = encrypt(password)
    user.must_change_password = False
    user.last_password_change_datetime, user.last_password_change_epoch = current_datetime_epoch(
    )
    user.password_expiration_epoch = user.last_password_change_epoch + settings.password_expiration_epoch
    user.password_expiration_datetime = datetime.fromtimestamp(
        float(user.password_expiration_epoch))
    db.commit()
コード例 #4
0
 def create_user(cls, user: User) -> int:
     if cls._user_validation(user):
         user.password = cls._hashing(user.password)
         user.state = cls._get_user_state(user).value
         session = cls._Session()
         session.add(user)
         session.commit()
         if user.email:
             cls._generate_token(user.uid, ExchangeMethods.EMAIL)
         if user.phone:
             cls._generate_token(user.uid, ExchangeMethods.PHONE)
     return user.uid
コード例 #5
0
    def test_log_in_by_email(self):
        pss = 'Pa$$w0rd'
        user = User(password=pss,
                    first_name='first name',
                    last_name='last name',
                    phone='9121234567',
                    email='*****@*****.**')
        UserHandler.create_user(user)

        # region check failed scenario
        with self.assertRaises(AuthenticationException) as _ex:
            UserHandler.log_in_by_email(user.email, user.password)
        with self.assertRaises(AuthenticationException) as _ex:
            UserHandler.log_in_by_email(user.email, 'wrong password')
        self.assertEqual('Entered password is wrong!', str(_ex.exception))
        with self.assertRaises(AuthenticationException) as _ex:
            UserHandler.log_in_by_email('*****@*****.**', pss)
        self.assertEqual('Wrong Email Address!', str(_ex.exception))
        # endregion

        # region check succeed scenario
        u = UserHandler.log_in_by_email(user.email, pss)
        # assert user properties with origin properties
        self.assertEqual(user.first_name, u.first_name)
        self.assertEqual(user.last_name, u.last_name)
        self.assertEqual(user.phone, u.phone)
        self.assertEqual(user.email, u.email)
        # check if password is null
        self.assertIsNone(u.password)
コード例 #6
0
    def test_change_password(self):
        pss = 'Pa$$w0rd'
        user = User(password=pss,
                    first_name='first name',
                    last_name='last name',
                    phone='9121234567',
                    email='*****@*****.**')
        UserHandler.create_user(user)

        # region check failed scenario
        with self.assertRaises(SecurityException) as _ex:
            UserHandler.change_password(0, pss, 'Pa$$w)rd1')
            self.assertEqual("user doesn't exist!", str(_ex.exception))
        with self.assertRaises(AuthenticationException) as _ex:
            UserHandler.change_password(user.uid, 'another Pa$$w0rd',
                                        'Pa$$w)rd1')
        self.assertEqual('Entered password is wrong!', str(_ex.exception))
        with self.assertRaises(ValueException) as _ex:
            UserHandler.change_password(user.uid, pss, 'pass')
        self.assertEqual('Entered password is not valid!', str(_ex.exception))
        # endregion

        # region check succeed scenario
        new_pss = 'NEW pa$$w0rd'
        UserHandler.change_password(user.uid, pss, new_pss)
        u = UserHandler.log_in_by_email(user.email, new_pss)
        self.assertEqual(user.uid, u.uid)
コード例 #7
0
def verify_password(username_or_token, password):
    user = User.verify_auth_token(username_or_token)
    if not user:
        user = User.query.filter_by(username=username_or_token).first()
        if not user or not user.verify_password(password):
            return False
    g.user = user
    return True
コード例 #8
0
 def create_user():
     user = User(password='******',
                 first_name='first name',
                 last_name='last name',
                 phone='9121234567',
                 email='*****@*****.**')
     UserHandler.create_user(user)
     return user
コード例 #9
0
 def test_user_change_info(self):
     user = User(password='******',
                 first_name='first name',
                 last_name='last name',
                 phone='9121234567',
                 email='*****@*****.**')
     UserHandler.create_user(user)
     u = UserHandler.update_user_info(user.uid, 'new name', 'new last name')
     self.assertEqual('new name', u.first_name)
     self.assertEqual('new last name', u.last_name)
コード例 #10
0
 def generate_toke(self, no_exchange=False, user_id=None):
     if user_id is None:
         if no_exchange:
             user_id = UserHandler.create_user(
                 User(password='******',
                      first_name='first name',
                      last_name='last name'))
         else:
             user_id = self.create_user()
     result = TokenHandler.generate_token(user_id, ExchangeMethods.PHONE)
     return user_id, result
コード例 #11
0
 def create_or_update(self, request_json):
     private_id = request_json["private_id"]
     authentication_type = request_json["authentication_type"]
     user = None
     try:
         # update
         user = self.find_by_private_id(private_id)
         user.renew_auth()
     except:
         # create
         user = User(private_id, authentication_type=authentication_type)
         profile = Profile()
         if user.authentication_type == AuthenticationTypeEnum.ID_PORTEN:
             profile.national_id_number = private_id
         if user.authentication_type == AuthenticationTypeEnum.ACTIVE_DIRECTORY:
             profile.active_directory_id = private_id
         user.profile = profile
     current_app.db_session.add(user)
     current_app.db_session.commit()
     current_app.db_session.refresh(user)
     return user
コード例 #12
0
 def test_create_user_and_get_by_email(self):
     user = User(password='******',
                 first_name='first name',
                 last_name='last name',
                 phone='9121234567',
                 email='*****@*****.**')
     UserHandler.create_user(user)
     u = UserHandler.get_user_by_email('*****@*****.**')
     # assert user properties with origin properties
     self.assertEqual(user.first_name, u.first_name)
     self.assertEqual(user.last_name, u.last_name)
     self.assertEqual(user.phone, u.phone)
     self.assertEqual(user.email, u.email)
     # check if password is null
     self.assertIsNone(u.password)
コード例 #13
0
    def test_add_address_to_user_addresses(self):
        user = User(password='******',
                    first_name='first name',
                    last_name='last name',
                    phone='9121234567',
                    email='*****@*****.**')
        UserHandler.create_user(user)

        # region Succeed Scenario
        address = Address(province='tehran',
                          city='tehran',
                          zip_code='1' * 10,
                          postal_address='somewhere in tehran')
        result = AddressHandler.add_address(user.uid, address)
        self.assertTrue(result)
        add = AddressHandler.get_address_by_id(address.uid)
        self.assertEqual(address.province, add.province)
        self.assertEqual(address.city, add.city)
        self.assertEqual(address.zip_code, add.zip_code)
        self.assertEqual(address.postal_address, add.postal_address)
        # endregion

        # region Failed Scenario
        new_address = Address(city='tehran',
                              zip_code='1' * 10,
                              postal_address='somewhere in tehran')
        with self.assertRaises(ValueException):
            AddressHandler.add_address(user.uid, new_address)

        new_address = Address(province='tehran',
                              zip_code='1' * 10,
                              postal_address='somewhere in tehran')
        with self.assertRaises(ValueException):
            AddressHandler.add_address(user.uid, new_address)

        new_address = Address(province='tehran',
                              city='tehran',
                              zip_code='0123456789')
        with self.assertRaises(ValueException):
            AddressHandler.add_address(user.uid, new_address)

        new_address = Address(province='tehran',
                              city='tehran',
                              postal_address='somewhere in tehran')
        with self.assertRaises(ValueException) as _ex:
            AddressHandler.add_address(12345, new_address)
        self.assertEqual("there is no user with this id: 12345",
                         str(_ex.exception))
コード例 #14
0
 def test_db_check_if_different_session_affect_entities(self):
     session = DBInitializer.get_session()
     user = User(password='******',
                 first_name='first name',
                 last_name='last name',
                 phone='9121234567',
                 email='*****@*****.**',
                 birth=datetime(1988, 1, 1).date())
     uid = UserHandler.create_user(user)
     u = UserHandler.get_user_by_id(uid)
     u.first_name = 'New_Name'
     session.commit()
     n_u = UserHandler.get_user_by_id(uid)
     self.assertNotEqual(n_u.first_name, 'New_Name')
     uu = session.query(User).get(u.uid)
     self.assertIsNotNone(uu.password)
コード例 #15
0
 def test_create_and_get_user(self):
     user = User(password='******',
                 first_name='first name',
                 last_name='last name',
                 phone='9121234567',
                 email='*****@*****.**',
                 birth=datetime(1988, 1, 1).date())
     uid = UserHandler.create_user(user)
     u = UserHandler.get_user_by_id(uid)
     # assert user properties with origin properties
     self.assertEqual(user.first_name, u.first_name)
     self.assertEqual(user.last_name, u.last_name)
     self.assertEqual(user.phone, u.phone)
     self.assertEqual(user.email, u.email)
     self.assertEqual(user.birth, u.birth)
     # check if password is null
     self.assertIsNone(u.password)
コード例 #16
0
    def test_retrieve_password_by_email_and_phone(self):
        user = User(password='******',
                    first_name='first name',
                    last_name='last name',
                    phone='9121234567',
                    email='*****@*****.**')
        UserHandler.create_user(user)
        # ask for retrieve and
        # save retrieve auth code to db

        # get tokens from db
        session = DBInitializer.get_session()
        token = session.query(Token).filter_by(
            exchange_method=ExchangeMethods.PHONE.value).one()
        session.close()
        # fail scenario: if user does not exist
        with self.assertRaises(SecurityException) as ex:
            UserHandler.change_password_by_hex_token(0, token.hex_token,
                                                     "New Pa$$w0rd1")
        #       if url token is wrong
        with self.assertRaises(AuthenticationException) as ex:
            UserHandler.change_password_by_url_token("wrong url token",
                                                     "New Pa$$w0rd1")
        # change password
        new_password = "******"
        result = UserHandler.change_password_by_hex_token(
            user.uid, token.hex_token, new_password)
        self.assertTrue(result)
        # check if password is really change
        UserHandler.log_in_by_email(user.email, new_password)

        # change password through url token
        result = UserHandler.change_password_by_url_token(
            token.url_token, "New Pa$$w0rd1")
        self.assertTrue(result)
        # check if password is really change
        UserHandler.log_in_by_email(user.email, "New Pa$$w0rd1")
コード例 #17
0
def add_users(fixtures, created_models):
    user_models = {}

    for fixture in fixtures:
        user = User(fixture.get('private_id'))
        user.db_id = fixture.get('db_id', None)
        user.id = fixture.get('id', None)
        user.authentication_type = fixture.get('authentication_type', None)
        user.person_id = fixture.get('person_id', None)
        user.created_on = fixture.get('created_on', None)
        user.auth_token = fixture.get('auth_token', None)
        user.auth_timestamp = fixture.get('auth_timestamp', None)
        user.credentials = [created_models["credential_models"][credential_id] for credential_id in fixture.get('credential_ids')]
        user.roles = [created_models["role_models"][role_name] for role_name in fixture.get('role_names')]

        profile = Profile()
        profile.national_id_number = fixture.get('profile').get('national_id_number', None)
        profile.active_directory_id = fixture.get('profile').get('active_directory_id', None)
        profile.first_name = fixture.get('profile').get('first_name', None)
        profile.last_name = fixture.get('profile').get('last_name', None)
        profile.email = fixture.get('profile').get('email', None)
        profile.phone = fixture.get('profile').get('phone', None)

        user.profile = profile

        user_models[user.db_id] = user
        app.db_session.add(user)

    created_models["user_models"] = user_models
    return created_models
コード例 #18
0
def login(db: alchemy, user: User) -> str:
    token = create_token()
    db.add(Session(token=token, user_id=user.id))
    user.failed_login_number = 0
    db.commit()
    return token
コード例 #19
0
def fail_login(db: alchemy, user: User) -> int:
    settings = get_settings(db)
    user.failed_login_number += 1
    user.is_enabled = user.failed_login_number + 1 < settings.failed_login_maximum_number
    db.commit()
    return settings.failed_login_maximum_number - user.failed_login_number
コード例 #20
0
from domain.models import AuthSettings, User

settings = ConfigParser()
settings.read('settings.ini')
m = import_module(settings['alembic']['models_location'] + '.models')
base = getattr(m, 'Base')
engine = create_engine(settings['alembic']['sqlalchemy.url'])
base.metadata.create_all(engine, checkfirst=True)
db = sessionmaker(bind=engine, autoflush=False)()
db.add(
    AuthSettings(failed_login_maximum_number=3,
                 password_expiration_epoch=100000,
                 session_expiration_epoch=100000,
                 simultaneous_sessions_nro_allowed=1,
                 min_special_letters_number=1,
                 min_uppercase_letters_number=1,
                 min_password_len=8))
db.add(
    User(
        id_number='666666',
        name='Pedro',
        last_name='Yupanqui',
        email_address='*****@*****.**',
        birthday=datetime(1985, 6, 17),
        username='******',
        password=encrypt('Admin6543!'),
        password_expire=True,
        is_admin=True,
    ))
db.commit()
コード例 #21
0
 def create(self, user: UserDtoIn, db: Session):
     db_user = User(**user.dict())
     db.add(db_user)
     db.commit()
     db.refresh(db_user)
     return db_user
コード例 #22
0
def add_user_to_services():
    user_data = request.get_json()
    if user_data == None:
        raise RuntimeError("Invalid user data")
    user_auth_domain = user_data.pop("user_auth_domain")
    user_data[
        "dn"] = f"uid={user_data['username']}-{user_data['userid']},{application.config['LDAP_AUTH_BASEDN']}"
    user_data["base_dn"] = application.config["LDAP_AUTH_BASEDN"]
    user_data["name"] = f"{user_data['username']} {user_data['surname']}"
    user_data["home"] = "/dev/null"
    if "gid" not in user_data:
        user_data["gid"] = 1004
    if "billing_id" not in user_data:
        user_data["billing_id"] = user_data["userid"]
    if "group_name" not in user_data:
        user_data["group_name"] = "Cloudxtiny"

    group_name = user_data.pop("group_name")

    # getOrCreate
    if User.query.filter_by(email=user_data['email']).scalar() is None:
        newClient = User(username=user_data['username'],
                         email=user_data['email'],
                         first_name=user_data["firstname"],
                         last_name=user_data["surname"],
                         billing_id=user_data["userid"],
                         billing_product_id=user_data["billing_product_id"],
                         ldap_group_name=group_name,
                         ovirt_auth_domain=user_auth_domain)
        db.session.add(newClient)
    else:
        newClient = User.query.filter_by(email=user_data['email']).first()
        newClient.username = user_data['username']
        newClient.first_name = user_data["firstname"]
        newClient.last_name = user_data["surname"]
        newClient.billing_id = user_data["userid"]
        newClient.billing_product_id = user_data["billing_product_id"]
        newClient.ldap_group_name = group_name
        newClient.ovirt_auth_domain = user_auth_domain
        newClient.updated = datetime.utcnow

    user_data.pop("billing_product_id")
    user = LdapUser(**user_data)
    if (user.save() == True):

        # add user to relevant group
        user_group = LdapGroup.set_basedn(
            application.config['LDAP_AUTH_GROUP_BASEDN']).query.filter(
                f"(cn={group_name})").first()
        user_group.members = user_data['username']
        try:
            add_group_msg = user_group.save()
        except Exception as ex:
            if ' memberUid:' in str(ex) and 'already exists' in str(ex):
                add_group_msg = True
            else:
                add_group_msg = str(add_group_msg)
                # adding to group failed so delete user from ldap
                LdapUser.set_basedn(
                    application.config['LDAP_AUTH_BASEDN']).query.filter(
                        f"(uid={user.username})").first().delete()

        if (add_group_msg == True):

            try:
                # added user to database and send ecrypted password
                encrypted_data = User.encrypt_username_password(
                    user_data['username'], user_data['password'])
                newClient.encrypted_ovirt_auth_hash = encrypted_data[
                    "ct_bytes"]
                newClient.encrypted_ovirt_auth_iv = encrypted_data["iv"]

                # get ovirt userid by logging in
                OvirtEngineService.loginCreatedUser(
                    newClient.username, user_data['password'],
                    newClient.ovirt_auth_domain)
                found_user = None
                user_search = OvirtEngineService().getUserDetailsByName(
                    user_data['firstname'])
                for auser in user_search:
                    if auser.user_name == f"{newClient.username}@{newClient.ovirt_auth_domain}":
                        found_user = auser

                if found_user:
                    newClient.ovirt_user_id = found_user.id
                else:
                    raise RuntimeError(
                        f"Could not find user {user_data['firstname']}@{newClient.ovirt_auth_domain} in Ovirt Service"
                    )

                application.logger.debug(newClient.dump_object())
                db.session.commit()

                result = json.dumps({
                    'java_ciphertext':
                    urlsafe_b64encode(encrypted_data["iv"] +
                                      encrypted_data["ct_bytes"]).decode(
                                          'utf-8'),
                    "auth_domain":
                    user_auth_domain
                })
            except Exception as ex:
                # rollback adding the user to LDAP
                LdapUser.set_basedn(
                    application.config['LDAP_AUTH_BASEDN']).query.filter(
                        f"(uid={user_data['username']})").first().delete()

                LdapGroup.remove_user(
                    user_data['username'], group_name,
                    application.config['LDAP_AUTH_GROUP_BASEDN'])

                OvirtEngineService().deleteUserAccount(found_user.id)

                # re-throw the exception.
                raise ex

            return result, 201
        else:
            res = jsonify({
                'status':
                "error",
                'message':
                f"Error. Failed to adding user to group: {add_group_msg}"
            })
            res.headers["content-type"] = "application/json"
            return res, 503
    else:
        res = jsonify({
            'status': "error",
            'message': "Error. Failed to adding user "
        })
        res.headers["content-type"] = "application/json"
        return res, 503