def deploy(): """run deployment tasks""" from flask.ext.migrate import upgrade from app.models.user import Role print(config_name) upgrade() Role.insert_roles()
def deploy(): """run deployment tasks""" from flask_migrate import upgrade from app.models.user import Role print(config_name) upgrade() Role.insert_roles()
def load_db_data(): from app.models.user import User, Role import json import os root = os.path.realpath(os.path.dirname(__file__)) # roles_seed_data = json.load(open(os.path.join(root, "roles.json"))) # for role in roles_seed_data: # r = Role(id=role["id"], display_name=role["display_name"]) # db.session.add(r) # users_seed_data = json.load(open(os.path.join(root, "roles.json"))) # for user in users_seed_data: # u = User(id=user["id"], login=user["login"], display_name=user["display_name"], # password=user["password"]) # db.session.add(u) # ba_user_1 = get_item_by_value(users_seed_data, "login", "ba-user-1") # ba_user_2 = get_item_by_value(users_seed_data, "login", "ba-user-2") # role_admin = get_item_by_value(roles_seed_data, "display_name", "admin") # role_user = get_item_by_value(roles_seed_data, "display_name", "user") # roles data roles_seed_data = json.load(open(os.path.join(root, "roles.json"))) role_admin_raw = get_item_by_value(roles_seed_data, "display_name", "admin") role_admin = Role(id=role_admin_raw["id"], display_name=role_admin_raw["display_name"]) role_user_raw = get_item_by_value(roles_seed_data, "display_name", "user") role_user = Role(id=role_user_raw["id"], display_name=role_user_raw["display_name"]) # users data users_seed_data = json.load(open(os.path.join(root, "users.json"))) ba_user_1_raw = get_item_by_value(users_seed_data, "login", "ba-user-1") ba_user_1 = User(id=ba_user_1_raw["id"], login=ba_user_1_raw["login"], display_name=ba_user_1_raw["display_name"], password=ba_user_1_raw["password"]) ba_user_1.roles.append(role_admin) db.session.add(ba_user_1) ba_user_2_raw = get_item_by_value(users_seed_data, "login", "ba-user-2") ba_user_2 = User(id=ba_user_2_raw["id"], login=ba_user_2_raw["login"], display_name=ba_user_2_raw["display_name"], password=ba_user_2_raw["password"]) ba_user_2.roles.append(role_user) db.session.add(ba_user_2) db.session.commit()
class UpdateUserSchema(Schema): first_name = fields.Str(required=False, validate=name_validate) last_name = fields.Str(required=False, validate=name_validate) email = fields.Email(required=False, validate=email_validate) role = fields.Str(required=False, validate=validate.OneOf(Role.get_roles())) verified_email = fields.Boolean(required=False)
def test_role_str_method_should_return_role_name(self): role_name = "exRoleName" mock_role = mock.Mock(spec=Role) mock_role.name = role_name self.assertEqual(Role.__str__(mock_role), role_name)
def setUpClass(cls): try: cls.client = webdriver.Firefox() except Exception as e: print e if cls.client: cls.app = create_app(TestingConfig) cls.app_ctx = cls.app.app_context() cls.app_ctx.push() db.drop_all() db.create_all() Role.insert_role() threading.Thread(target=cls.app.run).start() time.sleep(1)
def find_or_create_role(name, label): """ Find existing role or create new role """ role = Role.query.filter(Role.name == name).first() if not role: role = Role(name=name, label=label) db.session.add(role) return role
def test_project_create(self): """ Test project creation """ data = dict( title="An Experiment", difficulty=1, time_required="5 minutes", abstract="Create an experiment in 5 mins.", objective="The objective is to create something.", safety="No safety hazards", content="Start with the project, finish in 5 mins.", category_id=1, ) from app.models.user import User, Role # Create a mock user Role.insert_roles() creator = Role.query.filter_by(name="Creator").first() user = User(username="******", role=creator) db.session.add(user) db.session.commit() access_token = create_access_token(identity=user.id) create_resp = create_project(self, access_token, data) create_resp_data = json.loads(create_resp.data.decode()) project = create_resp_data["project"] self.assertTrue(create_resp.status) self.assertEqual(create_resp.status_code, 201) # Remove category id data.pop("category_id") # Check if each field matches. for field in data: self.assertEqual(project[field], data[field]) # Test for bad request data.pop("title") bad_create_resp = create_project(self, access_token, data) self.assertEqual(bad_create_resp.status_code, 400)
def add_role(name): """ Add New User Role """ try: r = Role() r.set_name(name) r.description = 'Default Description' r.save() except Exception as exp: print(exp) else: print(r.__repr__()) del r
def create(): data = get_filter({'name'}, request.json, False) role = Role(**data) try: db.session.add(role) db.session.commit() except DatabaseError as e: current_app.logger.exception(e) request_error('database error') current_app.logger.info('角色创建 %r', role) return success_result()
def default_user(): username = app.config.get('DEFAULT_USERNAME') password = app.config.get('DEFAULT_PASSWORD') name = app.config.get('DEFAULT_NAME') email = app.config.get('DEFAULT_EMAIL') user = User.find_user_by_username(username) if not user: user = User(username, hashlib.sha256(password.encode("utf-8")).hexdigest(), name, email) user.roles.append(Role(name='Admin')) user.save_to_db() app.logger.info('User %s created successfully', username)
def add_role(): form = RoleAddForm() form.auths.choices = [(v.id, v.id) for v in AuthModule.query.all()] form.validate_for_api() with db.auto_commit(): # 添加角色 role = Role(name=form.name.data) db.session.add(role) # 关联权限 with db.auto_commit(): role = Role.query.filter(Role.name == form.name.data).first() for i in form.auths.data: db.session.add(RoleAuth(role_id=role.id, auth_id=i)) write_oplog() return ReturnObj.get_response(ReturnEnum.SUCCESS.value, "success")
def update_user(user_id): """Update information on a user's account.""" class UpdateUserSchema(Schema): first_name = fields.Str(required=False, validate=name_validate) last_name = fields.Str(required=False, validate=name_validate) email = fields.Email(required=False, validate=email_validate) role = fields.Str(required=False, validate=validate.OneOf(Role.get_roles())) verified_email = fields.Boolean(required=False) try: user = User.query.filter_by(id=user_id).first() if user is None: abort(404) data = validate_request(request, UpdateUserSchema) user_updated = False email_updated = False if len(data) > 0: for field, new_value in data.items(): old_value = getattr(user, field) if field == 'role': new_value = Role(new_value) if old_value != new_value: if field == 'email': email_updated = True setattr(user, field, new_value) user_updated |= True if user_updated: if email_updated: user.verified_email = not user.is_admin( ) # Don't lock out admins db_session.add(user) db_session.commit() return jsonify(get_user_payload(user)), 200 raise ValueError("Request didn't include any changes.") except ValueError as e: return Response(str(e), 400)
def invite_user(): """Invites a new user to create an account and set their own password.""" class InviteUserSchema(Schema): first_name = name_field last_name = name_field email = email_field role = fields.Str(validate=validate.OneOf(Role.get_roles())) try: data = validate_request(request, InviteUserSchema) if User.query.filter_by(email=data['email']).first() is not None: raise ValueError("Email already in use.") user = User( role=Role(data['role']), first_name=data['first_name'], last_name=data['last_name'], email=data['email'], ) db_session.add(user) db_session.commit() send_join_from_invite_email(user) return jsonify({user.id: get_user_payload(user)}), 200 except ValueError as e: return Response(str(e), 400)
def setUp(self): db.drop_all() db.create_all() AppPermission.initialize_app_permissions() Role.initialize_roles() self.client = self.app.test_client(use_cookies=True)
def setUp(self): # Extend setUp super(TestUserModel, self).setUp() Role.insert_roles()
def initdb(): click.echo('初始化数据库') from datetime import datetime depts = [ Dept(id=1001, name='总部', superior=None, is_active=1, cr_date=datetime.now()), Dept(id=1011, name='财务部', superior=1001, is_active=1, cr_date=datetime.now()), Dept(id=1021, name='人力资源部', superior=1001, is_active=1, cr_date=datetime.now()), Dept(id=1031, name='行政部', superior=1001, is_active=1, cr_date=datetime.now()), Dept(id=1101, name='销售部', superior=1001, is_active=1, cr_date=datetime.now()), Dept(id=1111, name='销售一部', superior=1101, is_active=1, cr_date=datetime.now()), Dept(id=1121, name='销售二部', superior=1101, is_active=1, cr_date=datetime.now()), Dept(id=1201, name='技术部', superior=1001, is_active=1, cr_date=datetime.now()), Dept(id=1301, name='市场部', superior=1001, is_active=1, cr_date=datetime.now()), Dept(id=1401, name='生产部', superior=1001, is_active=1, cr_date=datetime.now()) ] db.session.add_all(depts) roles = [ Role(id=1, name='用户列表'), Role(id=2, name='用户信息修改'), Role(id=3, name='用户密码修改'), Role(id=4, name='企业查询'), Role(id=5, name='企业修改') ] db.session.add_all(roles) users = [ User(id=1001, name='管理员', dept_id=1001, superior=None, username='******', password='******', is_manager=1, position='管理员', can_login=1, cr_date=datetime.now()), User(id=1010, name='张三', dept_id=1001, superior=1001, username='******', password='******', is_manager=1, position='经理', can_login=1, cr_date=datetime.now()), User(id=1011, name='张思', dept_id=1001, superior=1010, username='******', password='******', is_manager=0, position='经理', can_login=1, cr_date=datetime.now()), User(id=1012, name='张武', dept_id=1001, superior=1010, username='******', password='******', is_manager=0, position='职员', can_login=1, cr_date=datetime.now()) ] db.session.add_all(users) permissions = [ Permission(user_id=1001, role_id=1, privilege=Privilege.全部), Permission(user_id=1001, role_id=2, privilege=Privilege.全部), Permission(user_id=1001, role_id=3, privilege=Privilege.全部), Permission(user_id=1010, role_id=1, privilege=Privilege.本部门), Permission(user_id=1010, role_id=3, privilege=Privilege.本人), Permission(user_id=1010, role_id=4, privilege=Privilege.本部门), Permission(user_id=1010, role_id=5, privilege=Privilege.本部门), Permission(user_id=1011, role_id=3, privilege=Privilege.本人), Permission(user_id=1011, role_id=4, privilege=Privilege.本人), Permission(user_id=1011, role_id=5, privilege=Privilege.本人), Permission(user_id=1012, role_id=3, privilege=Privilege.本人), Permission(user_id=1012, role_id=4, privilege=Privilege.本人), Permission(user_id=1012, role_id=5, privilege=Privilege.本人) ] db.session.add_all(permissions)
class InviteUserSchema(Schema): first_name = name_field last_name = name_field email = email_field role = fields.Str(validate=validate.OneOf(Role.get_roles()))
def prepare_data(): admin_role = Role.query.filter(Role.name == 'Admin').first() if not admin_role: admin_role = Role(name='Admin') db.session.add(admin_role) user_role = Role.query.filter(Role.name == 'User').first() if not user_role: user_role = Role(name='User') db.session.add(user_role) db.session.flush() user = User.query.filter(User.username == 'sdvico').first() if not user: user = User(username='******', first_name='SDVICO', last_name='SDVICO', password=f'{sha256_crypt.encrypt("sdvico@12345")}', role_id=user_role.id) db.session.add(user) zalo_oa_user = user.zalo_oas.first() if not zalo_oa_user: zalo_oa_user = ZaloOa(app_id='123456789', user_id=user.id) db.session.add(zalo_oa_user) db.session.flush() zalo_template = zalo_oa_user.templates.first() if not zalo_template: templates = [ TemplateZalo( name='Quan tâm SDVICO', zalo_oa_id=zalo_oa_user.id, elements=[ ElementZalo( title='Cảm ơn bạn đã quan tâm kênh Zalo OA của SDVICO', subtitle= 'Đây là kênh truyền thông của SDVICO dùng để tra cứu thông tin nhanh chóng và hiệu quả', image_url= 'https://cover.talk.zdn.vn/6/6/5/f/2/db78e63ab8ea409c458d7060661a2d91.jpg', priority=0, active=True), ElementZalo( title='Đăng kí thông tin', image_url= 'https://s160-ava-talk.zadn.vn/e/d/5/e/1/160/db78e63ab8ea409c458d7060661a2d91.jpg', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}/{app_id}/{recipient_id}/register" }), priority=1, active=True), ElementZalo(title='Mục con', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}" }), priority=2, active=False), ElementZalo(title='Mục Con', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}" }), priority=3, active=False), ElementZalo(title='Mục Con', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}" }), priority=4, active=False) ], scripts=[ ScriptZalo(name='quan_tam_script', event_name='follow', message="", zalo_oa_id=zalo_oa_user.id) ]), TemplateZalo( name='Tra cứu SDVICO', zalo_oa_id=zalo_oa_user.id, elements=[ ElementZalo( title='Tra cứu SDVICO', subtitle= 'Công cụ tra cứu thông tin tàu cá nhanh chóng và hiệu quả', image_url= 'https://cover.talk.zdn.vn/6/6/5/f/2/db78e63ab8ea409c458d7060661a2d91.jpg', priority=0, active=True), ElementZalo( title='Danh sách tàu cá', image_url= 'https://s160-ava-talk.zadn.vn/e/d/5/e/1/160/db78e63ab8ea409c458d7060661a2d91.jpg', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}/{app_id}/{recipient_id}/TraCuuSDVICO/ship-code" }), priority=1, active=True), ElementZalo(title='Mục con', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}" }), priority=2, active=False), ElementZalo(title='Mục Con', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}" }), priority=3, active=False), ElementZalo(title='Mục Con', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}" }), priority=4, active=False) ], scripts=[ ScriptZalo(name='tra_cuu_sdvico_script', message='#TraCuuSDVICO', zalo_oa_id=zalo_oa_user.id) ]), TemplateZalo( name='Tra cứu cước phí', zalo_oa_id=zalo_oa_user.id, elements=[ ElementZalo( title='Tra cứu cước phí', subtitle= 'Công cụ tra cứu cước phí nhanh chóng và hiệu quả', image_url= 'https://cover.talk.zdn.vn/6/6/5/f/2/db78e63ab8ea409c458d7060661a2d91.jpg', priority=0, active=True), ElementZalo( title='Danh sách tàu cá', image_url= 'https://s160-ava-talk.zadn.vn/e/d/5/e/1/160/db78e63ab8ea409c458d7060661a2d91.jpg', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}/{app_id}/{recipient_id}/TraCuuCuocPhi/ship-code" }), priority=1, active=True), ElementZalo(title='Mục con', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}" }), priority=2, active=False), ElementZalo(title='Mục Con', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}" }), priority=3, active=False), ElementZalo(title='Mục Con', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}" }), priority=4, active=False) ], scripts=[ ScriptZalo(name='tra_cuu_cuoc_phi_script', message='#TraCuuCuocPhi', zalo_oa_id=zalo_oa_user.id) ]), TemplateZalo( name='Hỗ trợ kỹ thuật', zalo_oa_id=zalo_oa_user.id, elements=[ ElementZalo( title='Hỗ trợ kỹ thuật', subtitle= 'Vui lòng chọn mục bên dưới để được hỗ trợ về mặc kỹ thuật', image_url= 'https://cover.talk.zdn.vn/6/6/5/f/2/db78e63ab8ea409c458d7060661a2d91.jpg', priority=0, active=True), ElementZalo( title='Danh sách tàu cá', image_url= 'https://s160-ava-talk.zadn.vn/e/d/5/e/1/160/db78e63ab8ea409c458d7060661a2d91.jpg', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}/{app_id}/{recipient_id}/HoTro/support" }), priority=1, active=True), ElementZalo(title='Mục Con', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}" }), priority=3, active=False), ElementZalo(title='Mục Con', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}" }), priority=3, active=False), ElementZalo(title='Mục Con', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}" }), priority=3, active=False) ], scripts=[ ScriptZalo(name='ho_tro_ky_thuat_script', message='#HoTro', zalo_oa_id=zalo_oa_user.id) ]), TemplateZalo( name='Hotline', zalo_oa_id=zalo_oa_user.id, elements=[ ElementZalo( title='Hotline', subtitle= 'Vui lòng liên hệ những chăm sóc khác hàng bên dưới', image_url= 'https://cover.talk.zdn.vn/6/6/5/f/2/db78e63ab8ea409c458d7060661a2d91.jpg', priority=0, active=True), ElementZalo( title='CSKH: Nguyễn Thị Hồng Thi', image_url= 'https://s160-ava-talk.zadn.vn/e/d/5/e/1/160/db78e63ab8ea409c458d7060661a2d91.jpg', default_action=json.dumps({ "type": "oa.open.phone", "payload": "{\"phone_code\":\"0934000785\"}}" }), priority=1, active=True), ElementZalo( title='CSKH: Lê Phương Nhung', image_url= 'https://s160-ava-talk.zadn.vn/e/d/5/e/1/160/db78e63ab8ea409c458d7060661a2d91.jpg', default_action=json.dumps({ "type": "oa.open.phone", "payload": "{\"phone_code\":\"0784464720\"}}" }), priority=2, active=True), ElementZalo(title='Nội dung: Nguyễn văn Hòa', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.phone", "payload": "{\"phone_code\":\"0911109489\"}}" }), priority=3, active=True), ElementZalo(title='Mục Con', image_url='{domain}/static/zalo_icon.png', default_action=json.dumps({ "type": "oa.open.url", "url": "{domain}" }), priority=4, active=False) ], scripts=[ ScriptZalo(name='hotline_script', message='#Hotline', zalo_oa_id=zalo_oa_user.id) ]) ] db.session.add_all(templates) db.session.commit()
def update_user(): """Updates the data of a user only if the user making the request is an admin .. :quickref: User; Update a user. **Example request**: .. sourcecode:: http PUT /api/user HTTP/1.1 Host: localhost Accept: application/json Content-Type: application/json { "admin_username": 1, "username": "******", "f_name": "John", "l_name": "Doe", "email": "*****@*****.**", "password": "******", "confirm_password": "******", "role": 2, } **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "message": "Success" } .. sourcecode:: http HTTP/1.1 401 UNAUTHORIZED Content-Type: application/json { "message": { "user": ["User is not an admin."] } } :<json string admin_username: the username of the person updating the user :<json string username: the updated username of the user :<json string f_name: the updated first name of the user :<json string l_name: the updated last name of the user :<json string email: the updated email of the user :<json string password: the updated password of the user, optional :<json string confirm_password: field that must match the original password, optional :<json int role: the cost_per_hour of the car being updated :>json message: repsonse information such as error information :resheader Content-Type: application/json :status 200: updating user was successful :status 400: missing or invalid fields :status 401: user is not an admin """ response = { 'message': '', } status = 200 form_schema = UpdateUserFormSchema() form_errors = form_schema.validate(request.json) if form_errors: response['message'] = form_errors status = 400 else: # Checking if user making the request is an admin admin_user = User.query.get(request.json["admin_username"]) if admin_user.role is not Role.admin: response['message'] = { 'user': ['User is not an admin.'] } status = 401 else: user = User.query.get(request.json["username"]) user.username = request.json["username"] user.f_name = request.json["f_name"] user.l_name = request.json["l_name"] user.email = request.json["email"] user.role = Role(int(request.json["role"])) if "password" in request.json: password = request.json["password"] hashed_password = bcrypt.generate_password_hash(password) user.password = hashed_password db.session.commit() response['message'] = "Success" return response, status
from app import db from app.models.user import Role, User from app.models.event import Event wam="austin" db.drop_all() db.create_all() db.session.commit() Role.insert_roles() user = User(username='******', fullname='Account', password="******",email='austinwam', role_id=3) user1 = User(username='******', fullname='Account', password="******",email='austinwam3', role_id=3) user2 = User(username='******', fullname='Account', password="******",email='austinwam4', role_id=3) user3 = User(username='******', fullname='Account', password="******",email='austinwam1', role_id=2) user4 = User(username='******', fullname='Account', password="******",email='austinwam2', role_id=2) event = Event(location='othaya',title='immunatioztion', date='1241993',) db.session.add(user) db.session.add(user1) db.session.add(user2) db.session.add(user4) db.session.add(user3) db.session.add(event) db.session.commit() print('Added administrator')