Example #1
0
 def _convert_json_to_user(self, user_data: dict) -> User:
     args = [
         user_data[UserAttribute.USER_ID],
         user_data[UserAttribute.USER_NAME],
         User.Privilege(user_data[UserAttribute.USER_PRIVILEGE])
     ]
     return User(*args)
Example #2
0
    def test_user_set_password_method(self):
        """ test that the set password method actually fills the password_hash field
		and that the value in the password hash field is infact not the actual password"""

        newguy = User(username="******")
        password = "******"
        newguy.set_password(password)

        self.assertIsNotNone(newguy.password_hash)
        self.assertNotEqual(password, newguy.password_hash)
Example #3
0
    def setUpClass(cls):
        super().setUpClass()

        cls.brian = User(username="******")
        cls.brian.set_password("brian password ayyee")
        cls.brian.save()
        cls.suzy = User(username="******")
        cls.suzy.set_password("shwingggg")
        cls.suzy.save()

        cls.pair = Pair(person1=cls.brian, person2=cls.suzy)
        cls.pair.save()
Example #4
0
File: login.py Project: rafex/Nabix
def new_user():
    username = request.json.get('username')
    password = request.json.get('password')
    if username is None or password is None:
        abort(400)  # missing arguments
    if User.query.filter_by(username=username).first() is not None:
        abort(400)  # existing user
    user = User(username=username)
    user.hash_password(password)
    db.session.add(user)
    db.session.commit()
    return (jsonify({'username': user.username}), 201, {
        'Location': url_for('get_user', id=user.id, _external=True)
    })
Example #5
0
def register():
    if request.method == 'GET':
        return render_template('register.html')
    user = User(request.form['username'], request.form['password'])
    db.session.add(user)
    db.session.commit()
    flash('User successfully registered')
    return redirect(url_for('login'))
def create_admin_user(session):
    """
    Creates a single "admin" user and adds it to the session
    :return: user
    """
    user1 = User(username='******')
    session.add(user1)
    return user1
Example #7
0
 def test_nonce(self):
     """ It shall be possible to receive user only once """
     user = User("user-id", "username")
     new_accounts = UserAccountActivationInMemoryStorage()
     nonce = new_accounts.put_user(user)
     new_accounts.pop_user(nonce)
     received_user = new_accounts.pop_user(nonce)
     self.assertFalse(received_user.id)
Example #8
0
def get_users(config):
    users = []
    for u in config['users']:
        users.append(User(
            u['username'],
            u['password'],
            u['vars']
        ))
    return users
Example #9
0
File: login.py Project: rafex/Nabix
def verify_password(username_or_token, password):
    # first try to authenticate by token
    user = User.verify_auth_token(username_or_token)
    if not user:
        # try to authenticate with username/password
        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
Example #10
0
 def add_user(self,
              user_data: ApplicationUserData,
              identity: UserIdentity = None) -> User:
     user_id = uuid.uuid4()
     user = User(str(user_id), user_data[JsonAttribute.name],
                 user_data[JsonAttribute.privilege])
     user_record = self._new_user(user, identity)
     self._users.append(user_record)
     self._save()
     return user
Example #11
0
    def setUpClass(cls):
        super().setUpClass()

        cls.client = app.test_client()
        cls.USERNAME, cls.PASSWORD = "******", "newpasswordwhothis"
        cls.user = User(username=cls.USERNAME)
        cls.user.set_password(cls.PASSWORD)
        cls.user.save()

        cls.register_url = "/register"
        cls.login_url = "/"
Example #12
0
 def test_serialize_user(self):
     user_data = [
         123,
         "username",
         User.Privilege.ADMINISTRATOR  # = 1
     ]
     user = User(*user_data)
     expected = json.dumps(
         dict(id=user.id, name=user.name, privilege=user.privilege.value))
     conv = AuthenticatedUserSerializer()
     self.assertEqual(expected, conv.serialize(user))
Example #13
0
 def test_create_user_when_already_exists(self):
     storage = Mock(spec=UserAccountStorage)
     storage.get_user_by_name.return_value = User("1234-5678", "username")
     config = [{
         Attribute.TYPE: "user",
         Attribute.NAME: "username",
         Attribute.PRIVILEGE: "USER"
     }]
     init = UserAccountsBootstrap(storage, config, list())
     init.create_from_config()
     storage.add_user.assert_not_called()
Example #14
0
def find_or_create_user(name, email, password):
    """ Find existing user or create new user """
    from application import User
    user = User.query.filter(User.username == name).first()
    if not user:
        user = User(username=name,
                    password=app.user_manager.hash_password(password),
                    email=email,
                    active=True)
        the_db.session.add(user)
    return user
Example #15
0
    def test_user_getotherperson_method(self):
        """ test that the method works as prescribed"""

        billy = User(username="******")
        billy.set_password("billy")
        billy.save()
        p = Pair(person1=billy, person2=self.uche)
        p.save()
        self.assertEqual(billy.username, self.uche.getotherperson(p.pairname))
        self.assertEqual(self.uche.username, billy.getotherperson(p.pairname))
Example #16
0
 def test_gunserialize_user(self):
     raw_json = {
         UserAttribute.USER_ID: 123,
         UserAttribute.USER_NAME: "username",
         UserAttribute.USER_PRIVILEGE: 1  # = User.Privilege.ADMINISTRATOR
     }
     conv = AuthenticatedUserSerializer()
     user = conv.unserialize(json.dumps(raw_json))
     self.assertEqual(raw_json[UserAttribute.USER_ID], user.id)
     self.assertEqual(raw_json[UserAttribute.USER_NAME], user.name)
     self.assertEqual(
         User.Privilege(raw_json[UserAttribute.USER_PRIVILEGE]),
         user.privilege)
Example #17
0
    def test_user_check_password_method(self):
        """ ensure that the checkpassword method actually works as expected"""
        password = "******"
        newgirl = User(username="******")
        newgirl.set_password(password)

        self.assertTrue(newgirl.check_password(password))
        self.assertFalse(newgirl.check_password("wronmg password"))
Example #18
0
 def test_create_unix_account_with_non_existing_associated_user(self):
     user_id, username = "******", "user-name"
     added_users = [User(user_id, username)]
     storage = Mock(spec=UnixAccountStorage)
     storage.unix_account_exists.return_value = False
     config = [{
         Attribute.TYPE: "unix_account",
         Attribute.NAME: "unix_account_name",
         Attribute.ID: 1001,
         Attribute.ASSOCIATED_USER: "******",
     }]
     init = UnixAccountsBootstrap(storage, config, added_users)
     init.create_from_config()
     expected_calls = [call(ANY, None)]
     storage.add_unix_account.assert_has_calls(expected_calls)
Example #19
0
    def test_register_route_user_created_successfully(self):
        """ test to ensure that a user was created successfuly"""
        newuser, newuserpassword = "******", "password_hehe"
        data = {
            "username": newuser,
            "password": newuserpassword,
            "confirm_password": newuserpassword
        }
        response = self.client.post(self.register_url,
                                    data=data,
                                    follow_redirects=True)

        # check if there are 2 users in the db, the user and setup and the new user created
        self.assertEqual(2, len(User.objects()))
        self.assertEqual(200, response.status_code)
Example #20
0
    def test_pair_getAPair_method_works_as_prescribed(self):
        """ test that irrespective of order of users in the method it will
			return the same pair object regardless if the users exists
			or none if the user doesnt exist
		"""

        self.assertEqual(self.pair, Pair.getAPair(self.brian, self.suzy))
        self.assertEqual(self.pair, Pair.getAPair(self.suzy, self.brian))
        popo = User(username="******")
        popo.set_password("popo")
        popo.save()
        self.assertIsNone(Pair.getAPair(popo, self.suzy))
Example #21
0
    def test_pair_ondelete_refrenceusers_associatingPairnamesAreDeleted(self):
        """ test that when we delete a pair the pairname stored in the 
			pair's referenced users are also deleted as well
		"""

        eze = User(username="******")
        eze.set_password('ezeiscool')
        eze.save()

        p = Pair(person1=eze, person2=self.suzy)
        p.save()
        self.assertEqual(2, len(self.suzy.pairnames))
        p.delete()
        self.assertEqual(1, len(self.suzy.pairnames))
Example #22
0
    def test_pair_adds_pairnamesToIndividualUsers(self):
        """ test that when a pair is created its pairname is added to
			pairnames list of the users it references
		"""

        # test with a brand new pair
        eze = User(username="******")
        eze.set_password('ezeiscool')
        eze.save()

        Pair(person1=eze, person2=self.suzy).save()
        self.assertEqual(1, len(eze.pairnames))
        self.assertIn(self.suzy.username, eze.pairnames[0])
        self.assertEqual(2, len(self.suzy.pairnames))
Example #23
0
    def test_pair_uniqueness_works_for_both_persons(self):
        """ ensure a pair is only considered unique as a pair, that is 
			if there is a pair(a, b) then creating another pair(a, c) or
			pair(d, b) is valid 
		"""
        yemi = User(username="******")
        yemi.set_password("yemi")
        yemi.save()

        p1 = Pair(person1=self.brian, person2=yemi)
        p1.save()
        p2 = Pair(person1=yemi, person2=self.suzy)
        p2.save()

        self.assertIsNotNone(p1)
        self.assertIsNotNone(p2)
Example #24
0
    def test_pair_doesnt_duplicate_pairnames_onRepeatedSaveCalls(self):
        """ test that if we call save on the same pair object again we doen
			add the same pairname a=on its user references again
		"""

        eze = User(username="******")
        eze.set_password('ezeiscool')
        eze.save()

        p = Pair(person1=eze, person2=self.suzy)
        p.save()
        p.save()
        p.save()

        self.assertNotEqual(3, len(eze.pairnames))
        self.assertEqual(1, len(eze.pairnames))
Example #25
0
def login():
    session.permanent = True
    #pdb.set_trace()
    if DISABLE_LOGIN:
        flash('error:Login is disable because of many failed login attempts!')
        return render_template('login/login.html', disable=True)

    if request.method == 'POST':
        user = request.form['user']
        pawd = request.form['chaabi']

        if not authenticate(user, pawd):
            guard('POST')
            flash("error:Invalid Username or Password!")
            #return render_template('login/login.html')
        else:
            flash("info:Login Successful!")
            user = User("test_user")
            login_user(user)
            return redirect("/blog")
    guard('GET')
    return render_template('login/login.html')
Example #26
0
from application import app, db, User, Threshold

if __name__ == "__main__":
    db.drop_all()
    db.create_all()

    # Create inital DB
    # TODO: add the real users
    db.session.add(User(1, [[0]*128], 10.5, 0))
    db.session.add(User(2, [[0.1]*128], 20.5, 1))
    db.session.add(User(3, [[0.2]*128], 30.5, 2))
    db.session.add(User(4, [[0.3]*128], 40.5, 3))
    db.session.add(User(5, [[0.4]*128], 50.5, 4))
    db.session.add(User(6, [[0.5]*128], 60.5, 5))

    db.session.add(Threshold(5)) # TODO: set the real threshold
    
    db.session.commit()

    app.run(debug=True, host='0.0.0.0', port=1337, ssl_context='adhoc')
Example #27
0
 def add_user(self,
              user: ApplicationUserData,
              identity: UserIdentity = None) -> User:
     """  Return a user based on the data provided """
     return User("123-456-789", user["name"],
                 User.Privilege(user["privilege"]))
Example #28
0
from application import User
from application.storage import (
    UserAccountStorage,
    UserIdentity,
)
from storage import (ApplicationUserData)
from ..response_mixin import StubResponseMixin

stored_user = User(id_="123-456-789", name="User from database")


class UserAccountStorageStub(UserAccountStorage, StubResponseMixin):
    def default_response_data(self) -> dict:
        response_data = {
            "add_user": stored_user,
            "user_exist": False,
            "remove_user_by_id": True,
            "get_user_by_id": stored_user,
            "get_user_by_name": stored_user,
            "get_all_users": [stored_user],
            "add_identity_to_user": True,
            "get_user_by_identity": stored_user
        }
        return response_data

    def add_user(self,
                 user: ApplicationUserData,
                 identity: UserIdentity = None) -> User:
        """  Return a user based on the data provided """
        return User("123-456-789", user["name"],
                    User.Privilege(user["privilege"]))
Example #29
0
 def test_database_incorrect_entry_register(self):
     user = User(112, 'KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKlllllllllll', True,
                 False, 121342)
     db.session.add(user)
     #self.assertRaises(IntegrityError, db.session.commit)
     db.session.commit()
import tornado.websocket
import tornado.httpclient

from application import User
from application.messaging import (MessageBus, Message)
from stubs import (UserSerializerStub, UnprivilegedUser)
from unix_account_authorization import (MessageProtocol, topic_user_requests,
                                        topic_user_updates,
                                        topic_user_responses, DecodeFailed)

from .unix_account_authorization_ws import (
    UnixAccountAuthorizationWebsocket,
    UnixAccountAuthorizationWebsocketArguments)

default_user = User(id_="1234-5678",
                    name="not-admin",
                    privilege=User.Privilege.USER)


class MessageStub(Message):
    pass


class TestUnixAccountAuthorizationWebsocket(AsyncHTTPTestCase):
    API_ENDPOINT = "/api/unix_account/ws"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._user_serializer = UserSerializerStub()
        self._message_protocol = Mock(spec=MessageProtocol)
        self._message_bus = Mock(spec=MessageBus)