def test_auth_user_init(self):
     """
     Tests models.AuthUser.__init__ to ensure that it correctly checks input
     """
     for test in self.auth_user_init_test_cases:
         if issubclass(test[KEY_EXPECTED_TYPE], Exception):
             with self.assertRaises(test[KEY_EXPECTED_TYPE]):
                 result = models.AuthUser(**test[KEY_INPUT])
         else:
             result = models.AuthUser(**test[KEY_INPUT])
             self.assertTrue(isinstance(result, test[KEY_EXPECTED_TYPE]))
Example #2
0
def push_new_user_to_db(name, auth_type):
    """ add name of user if they are signing in. guest if otherwise """

    if name != "GUEST":
        db.session.add(models.AuthUser(name, auth_type))
        db.session.commit()
    else:
        db.session.add(models.AuthUser(name, auth_type))
        db.session.commit()

    emit_all_oauth_users(USERS_UPDATED_CHANNEL)
Example #3
0
def push_new_user_to_db(name, auth_type):
    # TODO remove this check after the logic works correctly
    if name != "John Doe":
        db.session.add(models.AuthUser(name, auth_type))
        db.session.commit()

    emit_all_oauth_users(USERS_UPDATED_CHANNEL)
def add_or_get_auth_user(ucid, name):
    """
    Obtains the AuthUser corresponding to the given UCID and name (or creates
    one if one does not exist)
    """
    existing_user = (
        DB.session.query(models.AuthUser)
        .filter(func.lower(models.AuthUser.ucid) == func.lower(ucid))
        .first()
    )
    if existing_user:
        user_info = models.UserInfo(
            id=existing_user.id,
            ucid=existing_user.ucid,
            role=models.UserRole(existing_user.role),
            name=existing_user.name,
        )
    else:
        new_user = models.AuthUser(
            ucid=ucid,
            auth_type=models.AuthUserType.GOOGLE,
            role=models.UserRole.STUDENT,
            name=name,
        )
        DB.session.add(new_user)
        DB.session.flush()
        user_info = models.UserInfo(
            id=new_user.id,
            ucid=new_user.ucid,
            role=models.UserRole(new_user.role),
            name=new_user.name,
        )

    DB.session.commit()
    return user_info
Example #5
0
 def setUp(self):
     self.emit_list = []
     self.test_on_disconnect_params = [{
         KEY_INPUT: {
             KEY_SID:
             '123456789ABCDEF',
             KEY_MOCK_DATABASE_CALLS:
             [([
                 mock.call.query(models.CurrentConnections),
                 mock.call.filter_by(sid='123456789ABCDEF'),
                 mock.call.first()
             ], models.CurrentConnections('123456789ABCDEF', 0)),
              ([
                  mock.call.query(models.EnteredRooms),
                  mock.call.filter_by(user=0),
                  mock.call.delete()
              ], self.append_emit_list({"opp": "deleteEntered"})),
              ([
                  mock.call.query(models.AuthUser),
                  mock.call.filter_by(id=0),
                  mock.call.first()
              ],
               models.AuthUser(models.AuthUserType.GOOGLE, 'user1',
                               '*****@*****.**', 'www.google.com')),
              ([mock.call.delete(models.AuthUser)],
               self.append_emit_list({"opp": "deleteAuth"}))]
         },
         KEY_EXPECTED: [{
             "opp": "deleteEntered"
         }, {
             "opp": "deleteAuth"
         }, {
             "opp": "print"
         }]
     }]
Example #6
0
def resetadmin(config):

    try:
        u = models.AuthUser.get(models.AuthUser.username == 'admin')
    except models.AuthUser.DoesNotExist:
        u = models.AuthUser()
        u.username = '******'
        u.name = 'Administrator'
        u.group_id = 0

    u.password = genhash('admin')
    u.save()
Example #7
0
    def test_app_on_disconnect(self, mocked_flask):
        for test in self.test_on_disconnect_params:
            session = UnifiedAlchemyMagicMock()
            mocked_flask.request.sid = test[KEY_INPUT][KEY_SID]
            with mock.patch('models.DB.session', session):
                session.add(
                    models.CurrentConnections(test[KEY_INPUT][KEY_SID], 1))
                session.add(
                    models.AuthUser(models.AuthUserType.GOOGLE, 'nrw41',
                                    'meail', 'pciina'))
                session.commit()
                #with mock.patch('app.print', self.mock_print):
                #    with mock.patch('app.emit_all_users', self.mock_emit_all_users):
                with mock.patch('app.get_room', self.mock_get_room):
                    app.on_disconnect()

            self.assertEqual(len(self.emit_list) + 1, len(test[KEY_EXPECTED]))
            for i in range(len(self.emit_list)):
                self.assertEqual(self.emit_list[i]['opp'],
                                 test[KEY_EXPECTED][i]['opp'])
Example #8
0
def accept_google_login(data):
    socketio.emit(
        "login accepted",
        room=flask.request.sid
    )
    user = models.DB.session.query(models.AuthUser).filter_by(auth_type=models.AuthUserType.GOOGLE.value, email=data['email']).first()
    if not user:
        print('adding new user')
        models.DB.session.add(models.AuthUser(models.AuthUserType.GOOGLE, data['user'], data['email'], data['pic']))
        models.DB.session.commit()
        user = models.DB.session.query(models.AuthUser).filter_by(auth_type=models.AuthUserType.GOOGLE.value, email=data['email']).first()
    else:
        print('updating existing user')
        user.username = data['user']
        user.picUrl = data['pic']
    connection = models.DB.session.query(models.CurrentConnections).filter_by(sid=flask.request.sid).first()
    connection.user = user.id
    models.DB.session.commit()
    print("{} logged in".format(user.username))
    emit_joined_rooms(flask.request.sid)
async def seed_users(args):

    config.load_from_yaml(
        f'{_root}/config/config.{os.getenv("ENVIRONMENT", "local")}.yaml')
    await Tortoise.init(config=config.tortoise_config())

    _exists = await models.users.AuthUser.all().count()
    if _exists:
        # do not add seed
        return

    _file = f'{_current_path}/{args.file}'
    with open(_file) as f:
        csv_reader = csv.reader(f)
        for csv_user in csv_reader:
            print(csv_user)

            auth_user = models.AuthUser()
            auth_user.username = csv_user[0]
            auth_user.password = csv_user[1]
            auth_user.role_flags = int(csv_user[2])
            # on new users platform user's roles are changed ADMIN -> SUPERUSER
            if auth_user.role_flags == user_roles.ADMIN and auth_user.username != 'admin':
                auth_user.role_flags = user_roles.SUPERUSER
            if auth_user.username == '*****@*****.**':
                auth_user.role_flags = user_roles.ADMIN

            auth_user.scopes = {'OPENWASTE': 3, 'OPENLIGHT': 3}
            await auth_user.save()

            user = models.User()
            user.auth_user = auth_user
            user.first_name = csv_user[3]
            user.last_name = csv_user[4]
            user.email = csv_user[5]
            user.alarm_type = int(csv_user[6])
            user.notification_type = int(csv_user[7])
            user.phone = PHONES[
                auth_user.
                username]['number'] if auth_user.username in PHONES else None
            await user.save()
Example #10
0
async def main():

    f = Faker()
    config.load_from_yaml(
        f'{_root}/config/config.{os.getenv("ENVIRONMENT", "local")}.yaml')
    await Tortoise.init(config=config.tortoise_config())

    _exists = await models.users.AuthUser.all().count()
    if _exists:
        # do not add seed
        return

    _roles = [
        (user_roles.USER, 10),
        (user_roles.ADMIN, 5),
        (user_roles.DEVELOPER, 2),
        (user_roles.SUPERUSER, 2),
    ]
    for role in _roles:
        for _ in range(role[1]):
            auth_user = models.AuthUser()
            auth_user.username = f.user_name()
            auth_user.password = format_password(auth_user.username, '123')
            auth_user.role_flags = role[0]
            auth_user.scopes = {'OPENWASTE': 3, 'OPENLIGHT': 3}
            await auth_user.save()

            user = models.User()
            user.auth_user = auth_user
            user.first_name = f.first_name()
            user.last_name = f.last_name()
            user.email = f.email()
            user.alarm_type = 1
            user.notification_type = 1
            user.phone = f.phone_number()
            await user.save()
KEY_TIME = "available time"

KEY_ROOM_NUM = "room number"
KEY_SIZE = "room size"
KEY_CAPACITY = "room capacity"

KEY_DATA = "data sent"
AUTH_TYPE = "auth_type"
NAME = "name"
EMAIL = "email"

MOCK_AUTH_USER_DB_ENTRIES = {
    1:
    models.AuthUser(
        ucid="jd123",
        auth_type=models.AuthUserType.GOOGLE,
        role=models.UserRole.STUDENT,
        name="John Doe",
    ),
    2:
    models.AuthUser(
        ucid="johnny.appleseed",
        auth_type=models.AuthUserType.GOOGLE,
        role=models.UserRole.PROFESSOR,
        name="Johnny Appleseed",
    ),
    3:
    models.AuthUser(
        ucid="lr123",
        auth_type=models.AuthUserType.GOOGLE,
        role=models.UserRole.LIBRARIAN,
        name="Libra Rian",
Example #12
0
def push_new_user_to_db(ident, name):
    """
    Pushes new user to database.
    """
    db.session.add(models.AuthUser(ident, name))
    db.session.commit()
Example #13
0
def push_new_user_to_db(name, auth_type):
    # TODO remove this check after the logic works correctly
    if name != "John Doe":
        db.session.add(models.AuthUser(name, auth_type))
        db.session.commit()