def test_get_user_by_id(self): """Test user controllier method that returns user role by id.""" with patch('app.controllers.admin_controller.User') as mock_model: mock_model.query.filter_by.return_value.\ first.return_value.\ role.return_value = u'admin' c = AdminController() result = c.get_user_role_by_id(1) message = loads(result[0]) self.assertEqual(message['message'], u'admin')
def test_change_user_group(self): with patch('app.controllers.admin_controller.User') as mock_model: mock_model.query.filter_by.return_value.\ first.return_value.\ role_id = 0 c = AdminController() c.is_last_admin = Mock(return_value=False) result = c.change_user_group(1, {"user_role": 1}) message = loads(result[0]) self.assertEqual(message['message'], u'OK')
def test_delete_user_by_id(self): """Test user controllier method that deactivates or activates a user.""" with patch('app.controllers.admin_controller.User') as mock_model: mock_model.query.filter_by.return_value.\ first.return_value.\ is_active = 1 # print mock_model.query.filter_by().first().is_active is_success = AdminController().delete_by_id(user_id=1) assert is_success # print mock_model.query.filter_by().first().is_active assert not mock_model.query.filter_by().first().is_active is_success = AdminController().delete_by_id(user_id=1, delete=1) assert is_success # print mock_model.query.filter_by().first().is_active assert mock_model.query.filter_by().first().is_active
def post(self): """ Add a new admin """ from app.controllers.admin_controller import AdminController post_data = request.get_json() return AdminController.create_admin(post_data)
def post(self): """ Login admin through telegram """ post_data = request.get_json() admin_data = { "id": post_data.get("id", None), "first_name": post_data.get("first_name", None), "last_name": post_data.get("last_name", None), "username": post_data.get("username", None), "photo_url": post_data.get("photo_url", None), "auth_date": post_data.get("auth_date", None), "hash": post_data.get("hash", None) } data_check_string = self._concat_params_to_string(admin_data) data_check_string_bytes = data_check_string.encode("utf-8") secret_key = os.environ.get("ACCESS_TOKEN", None) secret_key_bytes = hashlib.sha256(secret_key.encode("utf-8")).digest() hmac_string = hmac.new(secret_key_bytes, data_check_string_bytes, hashlib.sha256).hexdigest() # TODO: check # if hmac_string == user_data["hash"]: # return {"status": "loged in successfully"}, 201 # else: # return {"fail": hmac_string, # "hash": user_data["hash"]}, 400 # if everything is ok with telegram then from app.controllers.admin_controller import AdminController return AdminController.login_admin(admin_data)
def delete_user(user_id): """ This function takes a request and bans/unbans a user """ delete_flag = 0 if request.method == 'DELETE' else 1 is_success = AdminController().delete_by_id(user_id, delete_flag) return json.dumps({'success': is_success}),\ 200 if is_success else 404,\ {'ContentType': 'application/json'}
from flask_login import (LoginManager, login_user, login_required, logout_user, current_user) from app import app from app.controllers.admin_controller import AdminController from app.controllers.login_form import LoginForm from app.models.user import User login_manager = LoginManager() # provide default view method for attempts of non logged in # users to visit protected by login pages: login_manager.login_view = 'login' login_manager.init_app(app) _admin_controller = AdminController() @app.route('/user/<int:user_id>', methods=['DELETE', 'PUT']) @login_required def delete_user(user_id): """ This function takes a request and bans/unbans a user """ delete_flag = 0 if request.method == 'DELETE' else 1 is_success = AdminController().delete_by_id(user_id, delete_flag) return json.dumps({'success': is_success}),\ 200 if is_success else 404,\ {'ContentType': 'application/json'} @app.route('/users/<int:user_id>/reset_password', methods=['POST'])
from app.database import sqlite_script from app.controllers.client_controller import ClientController from app.controllers.admin_controller import AdminController from app.controllers.catalog_controller import CatalogController from app.common_definitions import helper_functions # Create and fill database with values - closes connection to # Database was filled, objects are in memory if function call returns True objects_in_memory = sqlite_script.initializeAndFillDatabase() # Connect to the database through an abstracted object - this object must be imported into route files for use databaseObject = DatabaseContainer.get_instance() # Send the database object to all Controllers catalog_controller = CatalogController.get_instance() client_controller = ClientController.get_instance() admin_controller = AdminController.get_instance() if not objects_in_memory: catalog_controller.load_database_into_memory() client_controller.load_database_into_memory() admin_controller.load_database_into_memory() client_controller.load_loans_db_to_memory() # Helper function to be used in front end app.jinja_env.globals.update( convert_epoch_to_datetime=helper_functions.convert_epoch_to_datetime) from app import routes
def get(self, id): """ Returns admin by admin_id """ from app.controllers.admin_controller import AdminController return AdminController.get_admin_by_id(id)
def test_edit_user(self): controller = AdminController() self.assertTrue(controller.edit_user(self.user, self.params)) self.assertEqual(self.user.full_name, self.params['full_name']) self.assertEqual(self.user.email, self.params['email']) self.assertEqual(self.user.role_id, self.params['role_id'])
def get(self): """ Get list of all admins """ from app.controllers.admin_controller import AdminController return AdminController.get_all_admins()
def todo_list(): return AdminController().index()
def broadcast_notification(*args, **kwargs): user = kwargs['user'].as_dict() if (user['role_id'] != ROLE['admin']): return 'unauthorized' else: return AdminController.broadcast_notification(request, user)
def send_email(*args, **kwargs): user = kwargs['user'].as_dict() if (user['role_id'] != ROLE['admin']): return 'unauthorized' else: return AdminController.send_email(request, user)
def initializeAndFillDatabase(): """ Main where we implement most methods above (create connection, create table, insert data, close connection.) """ # Database already exists; do nothing if len(glob.glob(PATH_TO_DATABASE)) == 1: return False database = app.classes.database_container.DatabaseContainer.get_instance() app.classes.database_container.DatabaseContainer.commit_lock = True print("- Filling database -") # initialized variable with query that creates book table with columns/attributes table_creation_dict = { "book_table": """CREATE TABLE IF NOT EXISTS book ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, author TEXT NOT NULL, title TEXT NOT NULL, format TEXT NOT NULL, pages INTEGER NOT NULL, publisher TEXT NOT NULL, year_of_publication INTEGER NOT NULL, language TEXT NOT NULL, isbn_10 TEXT NOT NULL, isbn_13 TEXT NOT NULL, total_quantity INTEGER NOT NULL, quantity_available INTEGER NOT NULL );""", # initialized variable with query that creates magazine table with columns/attributes "magazine_table": """CREATE TABLE IF NOT EXISTS magazine ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, publisher TEXT NOT NULL, year_of_publication INTEGER NOT NULL, language TEXT NOT NULL, isbn_10 TEXT NOT NULL, isbn_13 TEXT NOT NULL, total_quantity INTEGER NOT NULL, quantity_available INTEGER NOT NULL );""", # initialized variable with query that creates movie table with columns/attributes "movie_table": """CREATE TABLE IF NOT EXISTS movie ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, director TEXT NOT NULL, producers TEXT NOT NULL, actors TEXT NOT NULL, language TEXT NOT NULL, subtitles TEXT NOT NULL, dubbed TEXT NOT NULL, release_date INTEGER NOT NULL, run_time INTEGER NOT NULL, total_quantity INTEGER NOT NULL, quantity_available INTEGER NOT NULL );""", # initialized variable with query that creates album table with columns/attributes "album_table": """CREATE TABLE IF NOT EXISTS album ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, type TEXT NOT NULL, title TEXT NOT NULL, artist TEXT NOT NULL, label TEXT NOT NULL, release_date INTEGER NOT NULL, asin TEXT NOT NULL, total_quantity INTEGER NOT NULL, quantity_available INTEGER NOT NULL );""", # initialized variable with query that creates client table with columns/attributes "user_table": """CREATE TABLE IF NOT EXISTS client ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, firstName TEXT NOT NULL, lastName TEXT NOT NULL, physicalAddress TEXT NOT NULL, email TEXT NOT NULL, phoneNumber TEXT NOT NULL, username TEXT NOT NULL, password TEXT NOT NULL, isAdmin INTEGER NOT NULL, isLogged INTEGER NOT NULL, lastLogged INTEGER NOT NULL );""", # initialized variable with query that creates book_copy table with columns/attributes #FOREIGN KEY(book_id) REFERENCES book(id), "book_copy_table": """CREATE TABLE IF NOT EXISTS book_copy ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, book_id INTEGER NOT NULL, isLoaned INTEGER NOT NULL, FOREIGN KEY(book_id) REFERENCES book(id) );""", # initialized variable with query that creates magazine_copy table with columns/attributes "magazine_copy_table": """CREATE TABLE IF NOT EXISTS magazine_copy ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, magazine_id INTEGER NOT NULL, FOREIGN KEY(magazine_id) REFERENCES magazine(id) );""", # initialized variable with query that creates movie_copy table with columns/attributes "movie_copy_table": """CREATE TABLE IF NOT EXISTS movie_copy ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, movie_id INTEGER NOT NULL, isLoaned INTEGER NOT NULL, FOREIGN KEY(movie_id) REFERENCES movie(id) );""", # initialized variable with query that creates album_copy table with columns/attributes "album_copy_table": """CREATE TABLE IF NOT EXISTS album_copy ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, album_id INTEGER NOT NULL, isLoaned INTEGER NOT NULL, FOREIGN KEY(album_id) REFERENCES album(id) );""", "loan_table": """CREATE TABLE IF NOT EXISTS loan ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, record_id INTEGER NOT NULL, table_name TEXT NOT NULL, loan_time INTEGER NOT NULL, due_time INTEGER NOT NULL, return_time INTEGER NOT NULL, is_returned INTEGER NOT NULL, FOREIGN KEY(user_id) REFERENCES client(id) );""" } # Create all tables for table_name, table_sql in table_creation_dict.items(): database.execute_query(table_sql) app.classes.database_container.DatabaseContainer.commit_lock = False database.commit_db() COPIES = 3 NUM_BOOKS = 50 MAX_BOOK_PAGES = 1500 NUM_MAGAZINES = 50 NUM_MOVIES = 50 NUM_ALBUMS = 50 NUM_USERS = 50 book_types = [ 'Paperback', 'Hardcover', 'Graphic', 'Coffee Table Book', 'Textbook' ] languages = [ 'English', 'French', 'Italian', 'Spanish', 'Greek', 'Russian', 'German' ] album_types = ["Vinyl", "CD", "Cassette"] MAX_QUANTITY = 10 MAX_TOTAL = 4 # Get all catalogs in order to use them to fill the database book_catalog = BookCatalog.get_instance() magazine_catalog = MagazineCatalog.get_instance() album_catalog = AlbumCatalog.get_instance() movie_catalog = MovieCatalog.get_instance() loan_catalog = LoanCatalog.get_instance() # Create controllers in order to create users admin_controller = AdminController.get_instance() client_controller = ClientController.get_instance() movie_name = lambda: "The " + f.job() if f.random_int( ) % 2 == 0 else " ".join(f.words()).capitalize() album_name = movie_name names = lambda: ", ".join( [f.name() for x in range(1 + f.random_int() % 9)]) date = lambda: int(time.time() - f.random_int() * f.random_int()) asin = lambda: "".join([ f.random_letter().upper() if f.random_int() % 2 == 0 else str(f.random_digit()) for x in range(10) ]) phone_number = lambda: "".join([str(f.random_digit()) for x in range( 3)]) + "-" + "".join([str(f.random_digit()) for x in range( 3)]) + "-" + "".join([str(f.random_digit()) for x in range(4)]) # Don't commit until the end app.classes.database_container.DatabaseContainer.commit_lock = True # Fake data generator f = Faker() for b in range(NUM_BOOKS): book_attributes = { 'author': f.name(), 'title': f.catch_phrase(), 'format': book_types[f.random_int() % len(book_types)], 'pages': f.random_int() % MAX_BOOK_PAGES, 'publisher': f.last_name(), 'year_of_publication': (f.random_int() % 100) + 1910, 'language': languages[f.random_int() % len(languages)], 'isbn_10': f.isbn10(), 'isbn_13': f.isbn13() } new_book = Book(book_attributes) # Create copies of the same book - also done for every record type below for c in range(COPIES): book_catalog.add(new_book, True) for m in range(NUM_MAGAZINES): magazine_attributes = { 'title': f.word().upper(), 'publisher': f.last_name(), 'year_of_publication': f.random_int() % 100 + 1910, 'language': languages[f.random_int() % len(languages)], 'isbn_10': f.isbn10(), 'isbn_13': f.isbn13() } new_magazine = Magazine(magazine_attributes) for c in range(COPIES): magazine_catalog.add(new_magazine, True) for m in range(NUM_MOVIES): movie_attributes = { 'title': movie_name(), 'director': f.name(), 'producers': names(), 'actors': names(), 'language': languages[f.random_int() % len(languages)], 'subtitles': languages[f.random_int() % len(languages)], 'dubbed': languages[f.random_int() % len(languages)], 'release_date': date(), 'run_time': 60 + f.random_int() % (2 * 60) } new_movie = Movie(movie_attributes) for c in range(COPIES): movie_catalog.add(new_movie, True) for a in range(NUM_ALBUMS): album_attributes = { 'type': album_types[f.random_int() % len(album_types)], 'title': album_name(), 'artist': f.name(), 'label': f.word().upper(), 'release_date': date(), 'asin': asin() } new_album = Album(album_attributes) for cop in range(COPIES): album_catalog.add(new_album, True) for u in range(NUM_USERS): user_attributes = { 'firstName': f.first_name(), 'lastName': f.last_name(), 'physicalAddress': f.address().replace("\n", ", "), 'email': f.email(), 'phoneNumber': phone_number(), 'username': f.user_name(), 'password': f.password(), 'isAdmin': f.random_int() % 2, 'isLogged': f.random_int() % 2, 'lastLogged': int(time.time() - f.random_int() * f.random_int()) } # Add user based on admin status if user_attributes["isAdmin"] == 1: admin_controller._admin_catalog.add(Admin(user_attributes), True) elif user_attributes["isAdmin"] == 0: client_controller._client_catalog.add(Client(user_attributes), True) client1 = dict( (('firstName', "Aaron"), ('lastName', 'Doe'), ('physicalAddress', '1451 De Maisonneuve Blvd. W. Montreal, QC H3G 1M8 Canada'), ('email', '*****@*****.**'), ('phoneNumber', '514-555-0001'), ('username', 'antman'), ('password', 'password1'), ('isAdmin', 0), ('isLogged', 1), ('lastLogged', 1537207100))) admin1 = dict( (('firstName', "Chloe"), ('lastName', 'Doe'), ('physicalAddress', '1452 De Maisonneuve Blvd. W. Montreal, QC H3G 1M8 Canada'), ('email', '*****@*****.**'), ('phoneNumber', '514-555-0002'), ('username', 'catwoman'), ('password', 'password3'), ('isAdmin', 1), ('isLogged', 1), ('lastLogged', 1537207100))) # create a new clients inside client table client_controller._client_catalog.add(Client(client1), True) admin_controller._admin_catalog.add(Admin(admin1), True) print("- Finished filling database -") # Turn off commit lock app.classes.database_container.DatabaseContainer.commit_lock = False database.commit_db() return True
def send_email(*args, **kwargs): user = kwargs['user'].as_dict() if (user['role_id'] != ROLE['admin']): return Response(json.dumps({'message': 'unauthorized'}), status=401, mimetype='application/json') else: return AdminController.send_email(request, user)
def admin_authorize(): return AdminController.password_require(request)