예제 #1
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()
예제 #2
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)
예제 #3
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"))
예제 #4
0
파일: run.py 프로젝트: 0z4ck/flask-login
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'))
예제 #5
0
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
예제 #6
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)
예제 #7
0
파일: config.py 프로젝트: stphivos/fnval
def get_users(config):
    users = []
    for u in config['users']:
        users.append(User(
            u['username'],
            u['password'],
            u['vars']
        ))
    return users
예제 #8
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
예제 #9
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)
예제 #10
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))
예제 #11
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()
예제 #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))
예제 #13
0
파일: run.py 프로젝트: fernl/BookCloud
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
예제 #14
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 = "/"
예제 #15
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))
예제 #16
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))
예제 #17
0
파일: login.py 프로젝트: 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)
    })
예제 #18
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))
예제 #19
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)
예제 #20
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)
예제 #21
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))
예제 #22
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')
예제 #23
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()
예제 #24
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')
예제 #25
0
from application import db, User, Category, Item

session = db.session

#Dumb user
user1 = User(name="ilaria", email="*****@*****.**", picture="")

session.add(user1)
session.commit()

user2 = User(name="kevin", email="*****@*****.**", picture="")

session.add(user2)
session.commit()

#Python section
category1 = Category(name="Python", user=user2)

session.add(category1)
session.commit()

item1 = Item(
    title="Learning Python",
    author="Mark Lutz",
    description=
    "Get a comprehensive, in-depth introduction to the core Python language with this hands-on book. Based on author Mark Lutz’s popular training course, this updated fifth edition will help you quickly write efficient, high-quality code with Python. It’s an ideal way to begin, whether you’re new to programming or a professional developer versed in other languages.",
    category=category1)

session.add(item1)
session.commit()
예제 #26
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"]))
예제 #27
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"]))
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)
                         UserAccountRegistration)
from openid_connect import (OpenIDClientConfiguration, TokenFromCodeExchanger,
                            TokenRequestFailed, JwtDecodeFailed)
from storage import UniqueConstraintFailed
from stubs import UserSerializerStub

from .base import (AUTH_TOKEN_NAME, SESSION_TOKEN_NAME)
from .user_account_openid import (OAuth2Authorization,
                                  OAuth2AuthorizationArguments,
                                  UserAccountLoginCallback,
                                  UserAccountRegistrationCallback,
                                  UserAccountLogoutOpenID)

# Used as reference representing a valid and authorized user during the tests (but not used in any assertion at the moment).
valid_user = User(id_="123-456-789",
                  name="user",
                  privilege=User.Privilege.USER)


async def get_token_from_code(code: str) -> str:
    return "<raw-jwt>"


class TokenFromCodeExchangerStub(TokenFromCodeExchanger):
    async def get_token_from_code(self, code: str) -> str:
        return "<raw-jwt>"


class TestOAuth2Authorization(AsyncHTTPTestCase):
    API_BASE_URL = "/"
    API_ENDPOINT_LOGIN = "******"
예제 #30
0
def regist_account(username, password, email):

    newUser = User(username=username, password=password, email=email)
    add_data2DB(newUser)