def add_default_users(db): try: UserRole.add_default_roles() User.add_default_users() except sqlalchemy.exc.IntegrityError as e: db.session.rollback() print(e)
def setUpClass(cls): cls.app = create_app('testing') cls.app_context = cls.app.app_context() cls.app_context.push() db.drop_all() db.create_all() # insert role role1 = Role(id=1,role_name='admin') role2 = Role(id=2,role_name='normal') db.session.add_all([role1,role2]) db.session.commit() # insert an admin u = User(username='******', email='*****@*****.**') u.set_password('123456') db.session.add(u) db.session.commit() userroles = UserRole(user_id=u.id, role_id = 1) db.session.add(userroles) db.session.commit() # insert an user user = User(username='******', email='*****@*****.**') user.set_password('123456') db.session.add(user) db.session.commit() userroles = UserRole(user_id=user.id, role_id = 2) db.session.add(userroles) db.session.commit() cls.client = cls.app.test_client(use_cookies=True)
def addAdminUsers(): # check if roles are present and if not then add them roles = [] roles = Role.query.all() if len(roles) == 0: roles = addTestRoles() # pragma: no cover user1 = User(public_id=str(uuid.uuid4()), username='******', password=generate_password_hash('password'), created=make_datetime_string(), last_login=make_datetime_string(), email='*****@*****.**') user2 = User(public_id=str(uuid.uuid4()), username='******', password=generate_password_hash('password'), created=make_datetime_string(), last_login=make_datetime_string(), email='*****@*****.**') db.session.add(user1) db.session.add(user2) db.session.commit() users = [user1, user2] # add all users to two admin roles userole1 = UserRole(user_id=user1.id, role_id=1) userole2 = UserRole(user_id=user2.id, role_id=2) db.session.add(userole1) db.session.add(userole2) db.session.commit()
def create_fake_users(db, nb_users=50, fake=None): from app.models import User from app.models import UserRole from app.models import Whitelist if fake is None: fake = Faker() #logging.getLogger('faker.factory').setLevel(logging.ERROR) wl1 = Whitelist(label=fake.word()) admin = UserRole(label=fake.word()) contributor = UserRole(label=fake.word()) db.session.add(wl1) db.session.add(admin) db.session.add(contributor) db.session.commit() roles = [admin, contributor] whitelists = [wl1] for i in range(0, nb_users): u1 = User(username=fake.user_name(), password=fake.user_name(), email=fake.free_email(), active=1, first_name=fake.first_name(), last_name=fake.last_name()) u1.role = roles[1] u1.whitelists = whitelists db.session.add(u1) db.session.commit()
def create_fake_users(db, nb_users=50, fake=None): from app.models import User from app.models import UserRole from app.models import Whitelist if fake is None: fake = Faker() wl1 = Whitelist(label=fake.word()) admin = UserRole(label=fake.word()) contributor = UserRole(label=fake.word()) db.session.add(wl1) db.session.add(admin) db.session.add(contributor) db.session.commit() roles = [admin, contributor] whitelists = [wl1] try: for i in range(0, nb_users): u1 = User(username=fake.user_name(), password=fake.user_name(), email=fake.free_email(), active=random.choice([0, 1]), first_name=fake.first_name(), last_name=fake.last_name()) u1.role = random.choice(roles) u1.whitelists = [random.choice(whitelists)] db.session.add(u1) db.session.commit() except IntegrityError as e: db.session.rollback()
def test_role_cascade_reaction(self): usr = User(username='******', email='*****@*****.**') usr.set_password('test2') db.session.add(usr) db.session.commit() userrole = UserRole(user_id=usr.id) userrole.role_id = 2 db.session.add(userrole) db.session.commit() user = User.query.filter_by(username='******').first() db.session.delete(user) db.session.commit() role = UserRole.query.filter_by(user_id=user.id).first() self.assertIsNone(role)
def get_role(self, username): user = self.read(username) role = UserRole.select().where(UserRole.id == user.role_id).get() return role.role
def create(self, role, **kwargs): role = UserRole.select().where(UserRole.role == role).get() kwargs["password"] = hash_password(kwargs["password"]) user = User.create(role_id=role.id, **kwargs) return user
def read_by_role(self, role): role = UserRole.select().where(UserRole.role == role).get() users = User.select().where(User.role_id == role.id) result = list() for user in users: result.append(user) return result
def decorated(*args, **kwargs): app = server.get_app() dbo = app.user_dbo token = request.headers['X-API-KEY'] user = dbo.read_by_key(token) user_role = UserRole.select().where(UserRole.id==user.role_id).get() if not user_role.role in roles: return {'message' : 'You are not authorized.'}, 401 return f(*args, **kwargs)
def decorated(*args, **kwargs): app = server.get_app() dbo = app.user_dbo user = dbo.read_by_id(current_user.id) user_role = UserRole.select().where( UserRole.id == user.role_id).get() if not user_role.role in roles: message = "Unauthorized" description = "You do not have authorization to enter this page" return render_message(message, description) return f(*args, **kwargs)
def update(self, username, role="", **kwargs): user = self.read(username) if "new_username" in kwargs: kwargs["username"] = kwargs["new_username"] del kwargs["new_username"] for key, value in kwargs.items(): setattr(user, key, value) if role: role = UserRole.select().where(UserRole.role == role).get() user.role_id = role.id user.save() return True
def set_up(): db.create_all() UserRole.insert_roles() CompanyFeature.insert_features()
def create_app(): from app.config import Config, ConfigDB app.config.from_object(Config) app.config.from_object(ConfigDB) CORS(app) db.init_app(app) ma.init_app(app) configure_uploads(app, files) patch_request_class(app) # set maximum file size, default is 16MB excel.init_excel(app) with app.app_context(): from app.models import IndustryArea, EmailStatus, UserRole, User, EmployeeCompany, Employee, \ Company, CompanyEmailStat, AlumnusEmailStat db.create_all() # create tables in database if not UserRole.UserRole.get_all(): # initialise default super admin role, dev advices to assign the role id to a user first before login into the system new = UserRole.UserRole( user_role_description="SuperAdmin", user_role_json=json.loads( '{"roles":"full","areas":"full","users":"full","companies":"full","employees":"full","reports":"full","conversations":"full"}' )) new.save() if not IndustryArea.IndustryArea.get_all(): # initialise default super admin role, dev advices to assign the role id to a user first before login into the system new = IndustryArea.IndustryArea( industry_name="All", industry_desc= "This default area is for user that can manage all company, which separated from admin role.", is_read_only=True) new.save() if not EmailStatus.EmailStatus.get_all(): # initialise default super admin role, dev advices to assign the role id to a user first before login into the system new = EmailStatus.EmailStatus('Lead-Opened', 'New lead') new.save() new = EmailStatus.EmailStatus('Lead-Processing', 'Discussion undergoing on') new.save() new = EmailStatus.EmailStatus('Lead-Closed', 'Closed case on the lead') new.save() new = EmailStatus.EmailStatus('Opportunity-Opened', 'New opportunity') new.save() new = EmailStatus.EmailStatus('Opportunity-Processing', 'Discussion undergoing on') new.save() new = EmailStatus.EmailStatus('Opportunity-Closed', 'Closed case on the opportunity') new.save() migrate = Migrate( app, db, compare_type=True ) # provide Flask Migrate command ability, set column type to detect in migrate files_path = Config.UPLOADS_DEFAULT_DEST + 'files/' template_path = files_path + "company_template.csv" if not os.path.exists(files_path): os.makedirs(files_path) if not os.path.exists(template_path): with open(Config.UPLOADS_DEFAULT_DEST + 'files/company_template.csv', mode='w') as csv_file: fieldnames = [ 'company_reg_num', 'company_name', 'company_size', 'company_industry_id', 'company_desc', 'company_address', 'company_postcode', 'company_city', 'company_state', 'company_country', 'company_office_contact_num' ] writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() from app.modules.LoginModule import routes as login_route app.register_blueprint(login_route.login_bp) from app.modules.UserModule import routes as user_route app.register_blueprint(user_route.user_bp) from app.modules.UserRoleModule import routes as role_route app.register_blueprint(role_route.user_role_bp) from app.modules.IndustryAreaModule import routes as area_route app.register_blueprint(area_route.industry_area_bp) from app.modules.CompanyModule import routes as comp_route app.register_blueprint(comp_route.company_bp) from app.modules.EmployeeModule import routes as emp_route app.register_blueprint(emp_route.employee_bp) from app.modules.EmailStatModule import routes as email_route app.register_blueprint(email_route.email_bp) from app.modules.DashboardModule import routes as home_route app.register_blueprint(home_route.home_bp) from app.services.AuthMiddleware import AuthMiddleware app.wsgi_app = AuthMiddleware(app.wsgi_app)
def assign_student_roles(db, role_id): for student in Student.query.all(): user = User.query.filter_by(username=student.username).first() db.session.add(UserRole(user_id=user.id, role_id=role_id))
from app import db from app.models import User, Post, Project, ProjectImage, Address, Link, Tag, UserRole db.session.add(Tag(category_id=1, name='Retail')) db.session.add(Tag(category_id=1, name='Commercial')) db.session.add(Tag(category_id=1, name='Office')) db.session.add(Tag(category_id=1, name='Residential')) db.session.add(Tag(category_id=2, name='Single Family Residence')) db.session.add(Tag(category_id=2, name='Duplex')) db.session.add(Tag(category_id=2, name='Multifamily')) db.session.add(Tag(category_id=2, name='Townhouse')) db.session.add(Tag(category_id=2, name='Condominium')) db.session.add(Tag(category_id=2, name='Apartment')) db.session.add(Tag(category_id=2, name='Studio')) db.session.add(Tag(category_id=3, name='Low Rise (Garden)')) db.session.add(Tag(category_id=3, name='Mid Rise')) db.session.add(Tag(category_id=3, name='High Rise')) db.session.add(Tag(category_id=3, name='Dormitory')) db.session.add(Tag(category_id=3, name='Manufactured')) db.session.add(Tag(category_id=4, name='Landscape')) db.session.add(Tag(category_id=4, name='Interior')) db.session.add(Tag(category_id=4, name='Exterior')) db.session.add(UserRole(name='Member')) db.session.add(UserRole(name='Reviewer')) db.session.add(UserRole(name='Moderator')) db.session.add(UserRole(name='Admin')) db.session.commit() db.session.close()
def addNormalUsers(): # check if countries are present and if not then add them roles = [] roles = Role.query.all() if len(roles) == 0: roles = addTestRoles() user1 = User(public_id=str(uuid.uuid4()), username='******', password=generate_password_hash('password'), created=make_datetime_string(), last_login=make_datetime_string(), email='*****@*****.**') user2 = User(public_id=str(uuid.uuid4()), username='******', password=generate_password_hash('password'), created=make_datetime_string(), last_login=make_datetime_string(), email='*****@*****.**') user3 = User(public_id=str(uuid.uuid4()), username='******', password=generate_password_hash('password'), created=make_datetime_string(), last_login=make_datetime_string(), deleted=True, delete_date=make_datetime_string(), email='*****@*****.**') user4 = User(public_id=str(uuid.uuid4()), username='******', password=generate_password_hash('password'), created=make_datetime_string(), last_login=make_datetime_string(), email='*****@*****.**') user5 = User(public_id=str(uuid.uuid4()), username='******', password=generate_password_hash('password'), created=make_datetime_string(), last_login=make_datetime_string(), email='*****@*****.**') user6 = User(public_id=str(uuid.uuid4()), username='******', password=generate_password_hash('password'), created='Sun, 09 Jun 2019 18:33:32 GMT', last_login='******', email='*****@*****.**') user7 = User(public_id=str(uuid.uuid4()), username='******', password=generate_password_hash('password'), created='Sun, 09 Jun 2019 18:33:32 GMT', last_login=make_datetime_string(), email='brĂ¼[email protected]') user8 = User(public_id=str(uuid.uuid4()), username='******', password=generate_password_hash('password'), created=make_datetime_string(), last_login=make_datetime_string(), email='*****@*****.**') db.session.add(user1) db.session.add(user2) db.session.add(user3) db.session.add(user4) db.session.add(user5) db.session.add(user6) db.session.add(user7) db.session.add(user8) db.session.commit() users = [user1, user2, user3, user4, user5, user6, user7, user8] # add all users to users role for user in users: userole = UserRole(user_id=user.id, role_id=3) db.session.add(userole) db.session.commit() return users
def assign_mentor_roles(db, role_id): for mentor in Mentor.query.all(): user = User.query.filter_by(username=mentor.username).first() db.session.add(UserRole(user_id=user.id, role_id=role_id))
def make_admin(db, username): user = User.query.filter_by(username=username).first() db.session.add(UserRole(user_id=user.id, role_id=1))
def add_default_users(db): UserRole.add_default_roles() db.session.flush() User.add_default_users()