def register(request): data = request.json print("===================", data) user = db.session.query(User).filter( or_(User.email == data["email"], User.phone_number == data["phone_number"])).first() if user is not None: return json( { "error_code": "USER_EXISTED", "error_message": "Email hoặc phone đã tồn tại" }, status=520) else: new_user = User() new_user.name = data["name"] new_user.email = data["email"] new_user.phone_number = data["phone_number"] # new_user.user_image = data["user_image"] new_user.password = auth.encrypt_password(data["password"]) new_user.rank = data["rank"] db.session.add(new_user) db.session.commit() result = user_to_dict(new_user) return json(result)
async def reset_password(request): if request.method == 'GET': token = request.args.get("token", None) static_url = app.config.get("DOMAIN_URL")+"/"+app.config.get("STATIC_URL", "") return jinja.render('email/reset_password.html', request, static_url = static_url, token=token) if request.method == 'POST': token = request.form.get("token", None) password = request.form.get("password", None) confirm_password = request.form.get("confirm_password", None) if token is None or password is None: return json({"error_code": "PARAM_ERROR", "error_message": "Tham số không hợp lệ, vui lòng thực hiện lại"}, status=520) uid_current = redisdb.get("sessions:" + token) if uid_current is None: return json({"error_code": "SESSION_EXPIRED", "error_message": "Hết thời gian thay đổi mật khẩu, vui lòng thực hiện lại"}, status=520) redisdb.delete("sessions:" + token) user = User.query.filter(User.id == str(uid_current.decode('ascii'))).first() if (user is not None): user.password = auth.encrypt_password(password) auth.login_user(request, user) db.session.commit() return text(u'bạn đã lấy lại mật khẩu thành công. mời bạn đăng nhập lại để sử dụng!') else: return text('Không tìm thấy tài khoản trong hệ thống, vui lòng thử lại sau!')
async def reset_password(request): if request.method == 'GET': token = request.args.get("token", None) static_url = app.config.get("DOMAIN_URL")+"/"+app.config.get("STATIC_URL", "") return jinja.render('email/reset_password.html', request, static_url = static_url, token=token) if request.method == 'POST': token = request.form.get("token", None) password = request.form.get("password", None) confirm_password = request.form.get("confirm_password", None) if token is None or password is None: return json({"error_code": "PARAM_ERROR", "error_message": "Invalid value, please check again"}, status=520) uid_current = redisdb.get("sessions:" + token) if uid_current is None: return json({"error_code": "SESSION_EXPIRED", "error_message": "Timeout to change password, please select again"}, status=520) redisdb.delete("sessions:" + token) user = User.query.filter(User.id == str(uid_current.decode('ascii'))).first() if (user is not None): user.password = auth.encrypt_password(password) auth.login_user(request, user) db.session.commit() return text(u'Password change was successful.') else: return text('User account not found, please select again!')
def create_admin(password='******'): """ Create default data. """ role_admin = Role.query.filter(Role.role_name == "admin").first() if (role_admin is None): role_admin = Role(role_name='admin', display_name="Admin") db.session.add(role_admin) db.session.flush() role_user = Role.query.filter(Role.role_name == "user").first() if (role_user is None): role_user = Role(role_name='user', display_name="User") db.session.add(role_user) db.session.flush() user = User.query.filter(User.user_name == "admin").first() if user is None: # create salt letters = string.ascii_lowercase user_salt = ''.join(random.choice(letters) for i in range(64)) print("user_salt", user_salt) # create user password user_password = auth.encrypt_password(password, user_salt) #create user user = User(user_name='admin', full_name="Admin User", email="*****@*****.**",\ password=user_password, salt=user_salt) db.session.add(user) db.session.commit() return
async def reset_user_passwd(instance_id=None, data=None, **kw): if (data is not None) and ('password' in data) and ('confirmpassword' in data): if (data['password'] is not None): if (data['password'] == data['confirmpassword']): data['password'] = auth.encrypt_password(data['password']) del data['confirmpassword'] else: return json( { "error_code": "PARAM_ERROR", "error_message": "Xác nhận mật khẩu không khớp" }, status=520) else: del data['confirmpassword'] del data['password'] else: return json( { "error_code": "PARAM_ERROR", "error_message": "Tham số không hợp lệ" }, status=520)
async def checkpass(request): password = "******" pass_hash = auth.encrypt_password(password) #pass_hash = "$6$rounds=656000$Nap.kHgpqAP5EXur$ZQpja3EUTx3nf4pZQY2XiAfEmiieDYDuuJ.0NcRN7odAEdVK.azltozKKYft3KYlzP7d.rUd7S/vmX/jHUXQ3/" is_pw = auth.verify_password(password, pass_hash) print(is_pw) return text(pass_hash)
async def pre_process_create_user(request, data=None, **kw): if data is not None: tenant_id = None if data.get('tenant_id') is None: current_tenant = get_current_tenant(request) if current_tenant is None or 'error_code' in current_tenant: return json(current_tenant, status=523) tenant_id = current_tenant.get('id') else: tenant_id = data.get('tenant_id') if data.get('password') is not None: salt = generate_salt() data['salt'] = salt data['password'] = auth.encrypt_password(data.get('password'), salt) if 'confirm_password' in data: del data['confirm_password'] if request.method == 'POST': data['tenant_id'] = tenant_id elif request.method == 'PUT': exclude_attrs = ['tenant_id'] for key in exclude_attrs: if key in data: del data[key] if 'password' in data and data.get('password') == None: del data['password']
async def changepassword(request): data = request.json print("==================data", data) password_old = data['password_old'] password_new = data['password_new'] current_uid = data['user_id'] print("==================PASSWORD_OLD", password_old) print("==================PASSWORD_NEW", password_new) print("===================current_uid============", current_uid) user = db.session.query(User).filter(or_(User.id == current_uid)).first() if current_uid and password_new is not None and auth.verify_password( password_old, user.password): print("==============USER INFO", auth.verify_password(password_old, user.password)) user_info = db.session.query(User).filter( User.id == current_uid).first() print("==============USER INFO", user_info) if user_info is not None: user_info.password = auth.encrypt_password(password_new) db.session.commit() return json({})
def update_admin(password='******'): user = User.query.filter(User.user_name == "admin").first() if user is not None: # create user password user_password = auth.encrypt_password(password, user.salt) user.password = user_password db.session.commit()
async def changepassword(request): data = request.json id = data['id'] password_new = data['password'] user_info = db.session.query(User).filter(User.id == id).first() user_info.password = auth.encrypt_password(password_new) db.session.commit() return json({})
async def change_password(request): currentUser = await current_user(request) if currentUser is None: return json( { "error_code": "SESSION_EXPIRED", "error_message": "Phiên làm việc hết hạn!" }, status=520) data = request.json if data is not None: if 'newpassword' not in data or 'confirm' not in data or data[ 'newpassword'] != data['confirm']: return json( { "error_code": "PASSWORD_NOT_MATCH", "error_message": "Mật khẩu không khớp, vui lòng kiểm tra lại!" }, status=520) if 'newpassword' in data and data[ 'newpassword'] is not None and 'password' in data: user = db.session.query(User).filter( User.id == currentUser.id).first() if user is not None: if auth.verify_password(data['password'], user.password) != True: return json( { "error_code": "PASSWORD_WRONG", "error_message": "Mật khẩu hiện tại không đúng, vui lòng kiểm tra lại!" }, status=520) user.password = auth.encrypt_password(data['newpassword']) # db.session.add(user) db.session.commit() return json({"error_message": "Thay đổi mật khẩu thành công!"}) else: return json( { "error_code": "NOT_FOUND_USER", "error_message": "Không tìm thấy tài khoản trong hệ thống!" }, status=520) else: return json( { "error_code": "PARAMS_ERROR", "error_message": "Có lỗi xảy ra, vui lòng thực hiện lại sau" }, status=520)
def create_test_models(): from application.config.development import Config app.config.from_object(Config) init_database(app) salt = str(generator_salt()) role1 = Role(name='admin') db.session.add(role1) user1 = User(email='admin', name='Admin', password=auth.encrypt_password('123456',salt), active=1, salt = salt) user1.roles.append(role1) db.session.add(user1) user2 = User(email='tw', name='Ban chỉ đạo TW', password=auth.encrypt_password('123456',salt), active=1, salt = salt) user2.roles.append(role1) db.session.add(user2) db.session.flush() db.session.commit()
def create_default_models(): #add tuyen donvi SITE_ROOT = os.path.realpath(os.path.dirname(__file__)) json_url_tuyendonvi = os.path.join(SITE_ROOT, "static/js/app/enum", "TuyenDonViEnum.json") data_tuyendonvi = json.load(open(json_url_tuyendonvi)) for item_tdv in data_tuyendonvi: print (item_tdv) dmTuyenDonVi = TuyenDonVi(id = item_tdv["value"],ma = item_tdv["name"], ten = item_tdv["text"]) db.session.add(dmTuyenDonVi) tuyendonvi = TuyenDonVi.query.filter(TuyenDonVi.ma == "TW").first() donvi = DonVi( ten=u'Cục quản lý môi trường bộ Y Tế ', captren = None, tuyendonvi_id = tuyendonvi.id) db.session.add(donvi) db.session.flush() db.session.commit() #add role role1 = Role(id=1,name='Admin') db.session.add(role1) role2 = Role(id=2,name='CanBo') db.session.add(role2) role3 = Role(id=3,name='User') db.session.add(role3) db.session.commit() #add user test user1 = User(email='admin', fullname='Admin', password=auth.encrypt_password('123456'),donvi_id=donvi.id,active=True) user1.roles.append(role1) user4 = User(email='namdv', fullname='Dang Nam', password=auth.encrypt_password('123456'),donvi_id=donvi.id,active=True) user4.roles.append(role1) db.session.add(user1) user2 = User(email='cucmtyy', fullname='Cục Môi Trường Y Tế', password=auth.encrypt_password('123456'),donvi_id=donvi.id,active=True) user2.roles.append(role2) db.session.add(user2) db.session.commit() #add dantoc json_url_dantoc = os.path.join(SITE_ROOT, "static/js/app/enum", "DanTocEnum.json") data_dantoc = json.load(open(json_url_dantoc)) for item_dantoc in data_dantoc: dantoc = DanToc(ma = item_dantoc["value"], ten = item_dantoc["text"]) db.session.add(dantoc) db.session.commit()
def preprocess_hash_password(data=None, **kw): if data is not None: if data.get('id', None) is None: data['id'] = str(uuid.uuid4()) data['secret_key'] = generate_unique_key(128, True) data['salt'] = generate_salt() data['password'] = auth.encrypt_password(data['password'], data['salt'])
def create_default_user(): #add user user3 = User(email='admin3', name='admin3', active=True, password=auth.encrypt_password('123456')) db.session.add(user3) db.session.flush() db.session.commit() print('________________________________', user3)
def user_register(request): param = request.json phone = param['phone'] password = param['password'] display_name = param['display_name'] unsigned_display_name = no_accent_vietnamese(param['display_name']) # print(param) check_user_match = db.session.query(User).filter( User.phone == phone).first() letters = string.ascii_lowercase user_salt = ''.join(random.choice(letters) for i in range(64)) user_password = auth.encrypt_password(password, user_salt) new_user = None if check_user_match is None: new_user = User(phone=phone, unsigned_display_name=unsigned_display_name, password=user_password, display_name=display_name, salt=user_salt) else: new_user = check_user_match new_user.phone = phone new_user.unsigned_display_name = unsigned_display_name new_user.password = user_password new_user.display_name = display_name new_user.salt = user_salt new_user.is_active = True db.session.add(new_user) db.session.flush() new_group = Group( group_name="GROUP " + str(display_name), unsigned_name="GROUP " + str(unsigned_display_name), assignee_id=new_user.id, # members=[new_user] ) db.session.add(new_group) db.session.flush() new_relation = GroupsUsers(user_id=new_user.id, group_id=new_group.id, role_id=db.session.query(Role.id).filter( Role.role_name == "admin").scalar()) db.session.add(new_relation) new_user.group_last_access_id = new_group.id new_user.group_last_access = new_group db.session.add(new_user) db.session.commit() return json({ "id": str(new_user.id), "phone": phone, "display_name": display_name, "password": password })
async def prepost_user(request=None, data=None, Model=None, **kw): currentUser = await current_user(request) if (currentUser is None): return json( { "error_code": "SESSION_EXPIRED", "error_message": "Hết phiên làm việc, vui lòng đăng nhập lại!" }, status=520) if "name" not in data or data[ 'name'] is None or "password" not in data or data[ 'password'] is None: return json( { "error_code": "PARAMS_ERROR", "error_message": "Tham số không hợp lệ" }, status=520) if ('phone_number' in data) and ('email' in data): user = db.session.query( User).filter((User.phone_number == data['phone_number']) | (User.email == data['email'])).first() if user is not None: if user.phone_number == data['phone_number']: return json( { "error_code": "USER_EXISTED", "error_message": 'Số điện thoại đã được sử dụng, vui lòng chọn lại' }, status=520) else: return json( { "error_code": "USER_EXISTED", "error_message": 'Email đã được sử dụng trong tài khoản khác' }, status=520) salt = generator_salt() data['salt'] = salt password = data['password'] data['password'] = auth.encrypt_password(password, salt) data['active'] = True
async def changepassword(request): error_msg = None params = request.json # password = params['password'] password = params['password'] cfpassword = params['confirm_password'] uid_current = current_uid(request) if uid_current is None: return json( { "error_code": "SESSION_EXPIRED", "error_message": "Hết hạn phiên làm việc" }, status=520) if ((error_msg is None)): if (password != cfpassword): error_msg = u"Xin mời nhập lại mật khẩu!" salt = generator_salt() user = db.session.query(User).filter(User.id == uid_current).first() if user is None: return json( { "error_code": "SESSION_EXPIRED", "error_message": "Hết hạn phiên làm việc" }, status=520) newpassword = auth.encrypt_password(str(password), str(salt)) user.password = newpassword user.salt = salt db.session.commit() return json({ "error_code": "OK", "error_message": "successfilly" }, status=200)
async def register_active(request): data = request.json uid = data.get('uid', None) password = data.get('password', None) active = data.get('active', None) check_token = redisdb.get("session-reset-password:"******"error_code": "ACTIVE_FAILED", "error_message": "Mã số không hợp lệ" }, status=520) else: user = db.session.query(User).filter( and_(User.id == uid, User.deleted == False)).first() if user is None: return json( { "error_code": "ACTIVE_FAILED", "error_message": "Tham số không hợp lệ" }, status=520) user.password = auth.encrypt_password(password, user.salt) db.session.commit() result = response_current_user(user) return json(result, status=200) else: return json( { "error_code": "ACTIVE_FAILED", "error_message": "Mã số hết hạn sử dụng, vui lòng thử lại" }, status=520)
def user_register(request=None, Model=None, result=None, **kw): currentUser = auth.current_user(request) if (currentUser is None): return json( { "error_code": "SESSION_EXPIRED", "error_message": "Hết phiên làm việc, vui lòng đăng nhập lại!" }, status=520) if result['id'] is not None: param = request.json role_admin = Role.query.filter(Role.role_name == "admin").first() role_user = Role.query.filter(Role.role_name == "user").first() role_employee = Role.query.filter(Role.role_name == "employee").first() role_leader = Role.query.filter(Role.role_name == "leader").first() # print("model==========",result) letters = string.ascii_lowercase user_salt = ''.join(random.choice(letters) for i in range(64)) print("user_salt", user_salt) user_password = auth.encrypt_password(param['password'], user_salt) user = User(email=param['email'], password=user_password, salt=user_salt, user_name=param['user_name'], full_name=param['full_name']) if (param['position'] == 'employee' or param['position'] is None): user.roles = [role_employee] if (param['position'] == 'leader'): user.roles = [role_leader] employee = db.session.query(Employee).filter( Employee.id == result['id']).first() employee.user = [user] db.session.add(employee) db.session.commit()
async def change_profile_web(request): error_msg = None if request.method == 'POST': address = request.json.get('address', None) email = request.json.get('email', None) phone = request.json.get('phone', None) name = request.json.get('name', '') birthday = request.json.get('birthday', None) gender = request.json.get('gender', None) ma_bhyt = request.json.get('ma_bhyt', None) organization_id = request.json.get('organization_id', '') organization = request.json.get('organization', '') xaphuong_id = request.json.get('xaphuong_id', '') quanhuyen_id = request.json.get('quanhuyen_id', '') tinhthanh_id = request.json.get('tinhthanh_id', '') xaphuong = request.json.get('xaphuong', '') quanhuyen = request.json.get('quanhuyen', '') tinhthanh = request.json.get('tinhthanh', '') ma_kcbbd = request.json.get('ma_kcbbd', None) accountName = request.json.get('accountName', None) password = request.json.get('password', None) # if(phone is None): # if not valid_phone_number(phone): # error_msg = u"Số điện thoại không đúng định dạng, xin mời nhập lại!" uid_current = current_uid(request) if uid_current is None: return json( { "error_code": "SESSION_EXPIRED", "error_message": "Hết hạn phiên làm việc" }, status=520) if accountName is None: return json( { "error_code": "PARAM_ERROR", "error_message": "Tên đăng nhập không được để trống." }, status=520) user = db.session.query(User).filter( or_(User.phone == phone, User.email == email, User.accountName == accountName)).first() if user is not None and user.id != uid_current: return json( { "error_code": "SESSION_EXPIRED", "error_message": "Tên đăng nhập hoặc số điện thoại hoặc email đã tồn tại trong hệ thống." }, status=520) current_user = db.session.query(User).filter( User.id == uid_current).first() if current_user is None: return json( { "error_code": "SESSION_EXPIRED", "error_message": "Hết hạn phiên làm việc" }, status=520) salt = generator_salt() if password is not None: newpassword = auth.encrypt_password(str(password), str(salt)) current_user.password = newpassword current_user.salt = salt current_user.name = name current_user.phone = phone current_user.email = email current_user.unsigned_name = convert_text_khongdau(name) current_user.accountName = accountName db.session.commit() patient = db.session.query(Patient).filter( or_(Patient.user_id == uid_current, Patient.mabaohiem == ma_bhyt)).all() if isinstance(patient, list) and len(patient) > 1: return json( { "error_message": "Mã thẻ bảo hiểm đã tồn tại trong hệ thống", "error_code": "PARAM_ERROR" }, status=520) if len(patient) == 1: object_patient = patient[0] check_patient = db.session.query(Patient).filter( Patient.id == object_patient.id).first() if check_patient is None: return json( { "error_message": "Lỗi truy cập dữ liệu.Vui lòng thử lại sau", "error_code": "PARAM_ERROR" }, status=520) check_patient.name = name check_patient.phone = phone check_patient.email = email check_patient.mabaohiem = ma_bhyt check_patient.gender = gender # patient.organization_id = organization_id check_patient.address = address check_patient.birthday = birthday check_patient.xaphuong_id = xaphuong_id check_patient.quanhuyen_id = quanhuyen_id check_patient.tinhthanh_id = tinhthanh_id check_patient.user_id = uid_current check_patient.xaphuong = xaphuong check_patient.quanhuyen = quanhuyen check_patient.tinhthanh = tinhthanh if organization is not None: check_patient.noi_kcbbd = organization.get("name", "") check_patient.organization_id = organization.get("id") check_patient.ma_kcbbd = organization.get("code", "") check_patient.unsigned_name = convert_text_khongdau( check_patient.name) db.session.commit() elif len(patient) == 0: newpatient = Patient() newpatient.name = name newpatient.phone = phone newpatient.email = email newpatient.mabaohiem = ma_bhyt newpatient.gender = gender # newpatient.organization_id = organization_id newpatient.address = address newpatient.birthday = birthday newpatient.user_id = uid_current newpatient.xaphuong_id = xaphuong_id newpatient.quanhuyen_id = quanhuyen_id newpatient.tinhthanh_id = tinhthanh_id newpatient.xaphuong = xaphuong newpatient.quanhuyen = quanhuyen newpatient.tinhthanh = tinhthanh if organization is not None: newpatient.noi_kcbbd = organization.get("name", "") newpatient.organization_id = organization.get("id") newpatient.ma_kcbbd = organization.get("code", "") newpatient.unsigned_name = convert_text_khongdau(newpatient.name) db.session.add(newpatient) db.session.commit() return json( { "error_code": "Ok", "error_message": "successfully", "data": response_current_user(current_user) }, status=200)
async def change_password(request): verify_access(request) current_tenant = get_current_tenant(request) if current_tenant is None or 'error_code' in current_tenant: return json( { 'error_code': 'TENANT_UNKNOW', 'error_message': 'Request Unknown' }, status=523) current_user = auth.current_user(request) if current_user is None: auth.logout_user(request) return json( { 'error_code': 'E523', 'error_message': 'Phiên làm việc hết hạn, đăng nhập lại.' }, status=523) current_tenant_id = current_tenant.get('id') current_user_id = current_user['uid'] if current_user_id is None: auth.logout_user(request) return json( { 'error_code': 'E523', 'error_message': 'Phiên làm việc hết hạn, đăng nhập lại.' }, status=523) user_info = db.session.query(User).filter(and_(User.tenant_id == current_tenant_id,\ User.id == current_user_id)).first() if user_info is None: return json( { 'error_code': 'E523', 'error_message': 'Tài khoản không tồn tại.' }, status=520) body_data = request.json current_password = body_data.get('current_password', None) new_password = body_data.get('new_password', None) # CHECK CURRENT PASSWORD CORRECT OR NOT if auth.verify_password(current_password, user_info.password, user_info.salt) == False: return json( { 'error_code': 'E523', 'error_message': 'Tên tài khoản hoặc mật khẩu không đúng' }, status=523) user_info.password = auth.encrypt_password(new_password, user_info['salt']) user_info.updated_at = now_timestamp() db.session.commit() return json({'code': 'S200', 'message': 'Thành công'}, status=200)
async def makesalt(request, password): letters = string.ascii_lowercase user_salt = ''.join(random.choice(letters) for i in range(64)) user_password = auth.encrypt_password(password, user_salt) return json({'user_password': user_password, 'user_salt': user_salt})
async def preput_user(request=None, data=None, Model=None, **kw): currentUser = await current_user(request) if (currentUser is None): return json( { "error_code": "SESSION_EXPIRED", "error_message": "Hết phiên làm việc, vui lòng đăng nhập lại!" }, status=520) if "name" not in data or data['name'] is None or "id" not in data or data[ 'id'] is None: return json( { "error_code": "PARAMS_ERROR", "error_message": "Tham số không hợp lệ" }, status=520) if ('phone_number' in data) and ('email' in data): check_user = db.session.query( User).filter((User.phone_number == data['phone_number']) | (User.email == data['email'])).filter( User.id != data['id']).first() if check_user is not None: if check_user.phone_number == data['phone_number']: return json( { "error_code": "USER_EXISTED", "error_message": 'Số điện thoại đã được sử dụng, vui lòng chọn lại' }, status=520) else: return json( { "error_code": "USER_EXISTED", "error_message": 'Email đã được sử dụng trong tài khoản khác' }, status=520) user = db.session.query(User).filter(User.id == data['id']).first() if user is None: return json( { "error_code": "NOT_FOUND", "error_message": "Không tìm thấy tài khoản người dùng" }, status=520) if currentUser.has_role("Giám Đốc") or str(currentUser.id) == data['id']: password = data['password'] data['password'] = auth.encrypt_password(password, user.salt) else: return json( { "error_code": "PERMISSION_DENY", "error_message": "Không có quyền thực hiện hành động này" }, status=520)
async def change_profile_user(data, Model, **kw): param = data if ("id" not in param or param['id'] is None): return json( { "error_message": "Tham số không hợp lệ", "error_code": "PARAM_ERROR" }, status=520) user = db.session.query(User).filter( and_(User.id == param["id"], User.deleted == False)).first() if user is None: return json( { "error_code": "USER_NOT_FOUND", "error_message": "Không tìm thấy tài khoản cán bộ" }, status=520) phone = param["phone"] if phone is not None and (phone[0] == 0 or phone[0] == '0'): check_phone = db.session.query(User).filter( and_(User.id != user.id, User.deleted == False)).filter( User.phone == param["phone"]).first() if check_phone is not None: return json( { "error_message": "Số điện thoại đã tồn tại, vui lòng nhập lại", "error_code": "PARAM_ERROR" }, status=520) user.phone = param["phone"] if ("email" in param) and (param["email"] is not None) and (len(param["email"]) > 0): check_email = db.session.query(User).filter( and_(User.id != user.id, User.deleted == False)).filter( User.email == param["email"]).first() if check_email is not None: return json( { "error_message": "Email đã tồn tại trong hệ thống, vui lòng chọn email khác", "error_code": "PARAM_ERROR" }, status=520) if ("accountName" in param) and (param["accountName"] is not None) and (len(param["accountName"]) > 0): check_accountName = db.session.query(User).filter( and_(User.id != user.id, User.deleted == False)).filter( User.accountName == param["accountName"]).first() if check_accountName is not None: return json( { "error_message": "Tên đăng nhập đã tồn tại trong hệ thống, vui lòng nhập lại tên đăng nhập.", "error_code": "PARAM_ERROR" }, status=520) user.email = param["email"] user.active = param["active"] user.name = param["name"] user.unsigned_name = convert_text_khongdau(user.name) user.accountName = param["accountName"] roles_dict = [] role_admin_donvi = db.session.query(Role).filter( Role.name == "admin_donvi").first() role_canbo = db.session.query(Role).filter(Role.name == "canbo").first() role_admin = db.session.query(Role).filter(Role.name == "admin").first() if role_admin_donvi is None or role_canbo is None or role_admin is None: print("quanlycanbo.change_profile.role_user>>> role không tồn tại") return json( { "error_code": "ERROR_PARAM", "error_message": "Tham số không hợp lệ" }, status=520) user.roles = [] for role_user in param["roles"]: if isinstance(role_user, str): if (role_user == role_admin_donvi.name): roles_dict.append(role_admin_donvi) if (role_user == role_canbo.name): roles_dict.append(role_canbo) if (role_user == role_admin.name): roles_dict.append(role_admin) else: if (role_user["name"] == role_admin_donvi.name): roles_dict.append(role_admin_donvi) if (role_user["name"] == role_canbo.name): roles_dict.append(role_canbo) if (role_user["name"] == role_admin.name): roles_dict.append(role_admin) user.roles = roles_dict if ("password" in param and param["password"] is not None and param["password"] != ""): newpassword = auth.encrypt_password(str(param['password']), str(user.salt)) user.password = newpassword user.deleted = param['deleted'] user.deleted_by = param['deleted_by'] db.session.commit() return json({"error_message": "successfully"}, status=200)
async def preprocess_create_user(data, Model, **kw): param = data user = User() phone = param["phone"] if phone is not None and (phone[0] == 0 or phone[0] == '0'): check_phone = db.session.query(User).filter( and_(User.phone == param["phone"], User.deleted == False)).first() if check_phone is not None: return json( { "error_message": "Số điện thoại đã tồn tại, vui lòng nhập lại", "error_code": "PARAM_ERROR" }, status=520) user.phone = param["phone"] if ("email" in param) and (param["email"] is not None) and (len(param["email"]) > 0): check_email = db.session.query(User).filter( and_(User.email == param["email"], User.deleted == False)).first() if check_email is not None: return json( { "error_message": "Email đã tồn tại trong hệ thống, vui lòng chọn email khác", "error_code": "PARAM_ERROR" }, status=520) user.email = param["email"] user.active = 1 user.name = param["name"] user.unsigned_name = convert_text_khongdau(user.name) user.organization_id = param["organization_id"] user.accountName = param["accountName"] roles_dict = [] role_admin_donvi = db.session.query(Role).filter( Role.name == "admin_donvi").first() role_canbo = db.session.query(Role).filter(Role.name == "canbo").first() role_admin = db.session.query(Role).filter(Role.name == "admin").first() if role_admin_donvi is None or role_canbo is None or role_admin is None: print("quanlycanbo.change_profile.role_user>>> role không tồn tại") return json( { "error_code": "ERROR_PARAM", "error_message": "Tham số không hợp lệ" }, status=520) user.roles = [] for role_user in param["roles"]: if isinstance(role_user, str): if (role_user == role_admin_donvi.name): roles_dict.append(role_admin_donvi) if (role_user == role_canbo.name): roles_dict.append(role_canbo) if (role_user == role_admin.name): roles_dict.append(role_admin) else: if (role_user["name"] == role_admin_donvi.name): roles_dict.append(role_admin_donvi) if (role_user["name"] == role_canbo.name): roles_dict.append(role_canbo) if (role_user["name"] == role_admin.name): roles_dict.append(role_admin) user.roles = roles_dict salt = generator_salt() if ("password" in param and param["password"] is not None and param["password"] != ""): newpassword = auth.encrypt_password(str(param['password']), str(salt)) user.password = newpassword user.salt = salt db.session.add(user) db.session.commit() return json({"error_message": "successfully"}, status=200)
def import_data_donvi_and_admin(): SITE_ROOT = os.path.realpath(os.path.dirname(__file__)) # path = os.path.join(SITE_ROOT, "application/data", "donvi_yte_79_TPHCM.xlsx") path = os.path.join(SITE_ROOT, "application/data", "donvi_yte_01_HN.xlsx") loc = (path) wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) # print(sheet.row_values(1)) # print("cell1",sheet.cell_value(0, 0)) # print("number_rows===",sheet.nrows) count =0 for i in range(sheet.nrows): if i == 0: continue ma_donvi = str(sheet.cell_value(i,1)).strip() ten_donvi = str(sheet.cell_value(i,2)).strip() level_donvi = convert_columexcel_to_string(sheet.cell_value(i,3)).strip() hinhthuc_tochuc = str(sheet.cell_value(i,4)).strip() matinhthanh = convert_columexcel_to_string(sheet.cell_value(i,5)) maquanhuyen = convert_columexcel_to_string(sheet.cell_value(i,6)) maxaphuong = convert_columexcel_to_string(sheet.cell_value(i,7)) diachi_donvi = str(sheet.cell_value(i,8)).strip() email_donvi = str(sheet.cell_value(i,9)).strip() dienthoai_donvi = str(sheet.cell_value(i,10)).strip() account = str(sheet.cell_value(i,11)).strip() email_admin = str(sheet.cell_value(i,12)).strip() dienthoai_admin = str(sheet.cell_value(i,13)).strip() matkhau = convert_columexcel_to_string(sheet.cell_value(i,14)) ten_admin = str(sheet.cell_value(i,15)).strip() if account is None: continue elif level_donvi != "1" and level_donvi != "2": continue check_donvi = db.session.query(Organization).filter(Organization.code == ma_donvi).first() if check_donvi is not None: continue donvi = Organization() donvi.id = default_uuid() donvi.code = ma_donvi donvi.name = ten_donvi donvi.email = email_donvi donvi.phone = dienthoai_donvi donvi.address = diachi_donvi donvi.type_donvi = hinhthuc_tochuc donvi.level = int(float(level_donvi)) donvi.unsigned_name = convert_text_khongdau(donvi.name) donvi.active = 1 check_tinhthanh = db.session.query(TinhThanh).filter(TinhThanh.ma == matinhthanh).first() if check_tinhthanh is not None: donvi.tinhthanh_id = check_tinhthanh.id check_quanhuyen = db.session.query(QuanHuyen).filter(QuanHuyen.ma == maquanhuyen).first() if check_quanhuyen is not None: donvi.quanhuyen_id = check_quanhuyen.id check_xaphuong = db.session.query(XaPhuong).filter(XaPhuong.ma == maxaphuong).first() if check_xaphuong is not None: donvi.xaphuong_id = check_xaphuong.id db.session.add(donvi) db.session.commit() check_admin = db.session.query(User).filter(User.accountName == account).first() if check_admin is not None: continue admin = User() admin.id = default_uuid() admin.accountName = account admin.name = ten_admin admin.unsigned_name = convert_text_khongdau(admin.name) admin.organization_id = donvi.id admin.active = 1 if email_admin is not None and email_admin != '': admin.email = email_admin else: admin.email = None if dienthoai_admin is not None and dienthoai_admin != '': admin.phone = dienthoai_admin else: admin.phone = None role_admin_tyt = db.session.query(Role).filter(Role.name == 'admin_tyt').first() role_admin_benhvien = db.session.query(Role).filter(Role.name == 'admin_benhvien').first() if donvi.level == 1: admin.roles.append(role_admin_benhvien) elif donvi.level == 2: admin.roles.append(role_admin_tyt) salt = generator_salt() if matkhau is not None: newpassword = auth.encrypt_password(str(matkhau), str(salt)) admin.password = newpassword admin.salt = salt db.session.add(admin) db.session.commit() count = count + 1 print("total_sync====",count)
async def addUserDonvi(request): error_msg = None if request.method == 'GET': donvi_diachi = request.json.get('donvi_diachi') donvi_sodienthoai = request.json.get('donvi_sodienthoai') captren_id = request.json.get('captren_id', None) donvi_tuyendonvi_id = request.json.get('donvi_tuyendonvi_id') password = request.json.get('password') cfpassword = request.json.get('password_confirm') email = request.json.get('email') phone = request.json.get('phone') fullname = request.json.get('fullname') if ((email is None) or (email == '')): error_msg = u"Xin mời nhập email!" if ((error_msg is None)): if ((password is None) or (password == '')): error_msg = u"Xin mời nhập lại mật khẩu!" if (error_msg is None): checkemail = User.query.filter(User.email == email).first() if (checkemail is not None): error_msg = u"Email đã có người sử dụng, xin mời nhập lại!" if (error_msg is None): if ((phone is None) or (phone == '')): error_msg = u"Xin nhập phone!" if (error_msg is None): checkphone = User.query.filter(User.phone == phone).first() if (checkphone is not None): error_msg = u"Số điện thoại đã có người sử dụng, xin mời nhập lại!" if ((error_msg is None)): if (password != cfpassword): error_msg = u"Mật khẩu không khớp!" if ((error_msg is None)): if (donvi_tuyendonvi_id is None): error_msg = u"Tham số đơn vị không đúng!" if (error_msg is None): userinfo = User() userinfo.donvi_diachi = donvi_diachi userinfo.donvi_sodienthoai = donvi_sodienthoai userinfo.fullname = fullname userinfo.email = email userinfo.password = auth.encrypt_password(password) userinfo.phone = phone_number userinfo.donvi_tuyendonvi_id = donvi_tuyendonvi_id userinfo.trangthai = TrangThaiDangKyDonViEnum.taomoi userinfo.macongdan = str(uuid.uuid1()) db.session.add(userinfo) db.session.commit() return json( { "uid": userinfo.id, "name": userinfo.fullname, "phone": userinfo.phone }, status=200) return json( { "error_code": "ADD_USER_FAILED", "error_message": error_msg }, status=520)
async def addDonViWillUser(request): id = request.args.get('id', None) error_msg = None if ((id is None) or (id == '')): error_msg = u"Tham số không đúng" if (error_msg is None): #id = int(id) dangky = UserDonvi.query.filter(UserDonvi.id == id).first() if (dangky is not None): checkdonvi = DonVi.query.filter( DonVi.ten == dangky.fullname).first() checkuser = User.query.filter(User.email == dangky.email).first() checkphone = User.query.filter(User.phone == dangky.phone).first() if checkdonvi is not None: return json( { "error_code": "PARAMS_ERROR", "error_message": "Tên đơn vị đã tồn tại, vui lòng nhập tên đơn vị khác" }, status=520) if checkuser is not None: return json( { "error_code": "PARAMS_ERROR", "error_message": "Email của người dùng đã tồn tại, vui lòng chọn email khác" }, status=520) if checkphone is not None: return json( { "error_code": "PARAMS_ERROR", "error_message": "Số điện thoại của người dùng đã tồn tại, vui lòng chọn SĐT khác" }, status=520) donvi = DonVi( ten=dangky.donvi_ten, captren=dangky.captren, tuyendonvi_id=dangky.donvi_tuyendonvi_id, ) donvi.diachi = dangky.donvi_diachi donvi.sodienthoai = dangky.donvi_sodienthoai donvi.coquanchuquan = dangky.captren.ten donvi.tinhthanh_id = dangky.tinhthanh_id donvi.tinhthanh = dangky.tinhthanh donvi.quanhuyen_id = dangky.quanhuyen_id donvi.quanhuyen = dangky.quanhuyen donvi.xaphuong_id = dangky.xaphuong_id donvi.xaphuong = dangky.xaphuong donvi.active = True db.session.add(donvi) db.session.flush() role = Role.query.get(2) user = User(email=dangky.email, fullname=dangky.fullname, active=True, phone=dangky.phone, password=auth.encrypt_password(dangky.password), donvi_id=donvi.id, roles=[role]) db.session.add(user) db.session.flush() dangky.donvi_id = donvi.id dangky.user_id = user.id dangky.trangthai = TrangThaiDangKyDonViEnum.dongbo db.session.commit() return json({ "user_id": str(user.id), "donvi_id": str(donvi.id) }, status=200) else: error_msg = u"Không tìm thấy thông tin đăng ký!" return json( { "error_code": "Đăng ký không thành công", "error_message": error_msg }, status=520)
def create_admin(password='******'): """ Create default data. """ role_admin = Role.query.filter(Role.role_name == "admin").first() if (role_admin is None): role_admin = Role(role_name='admin', display_name="Admin") db.session.add(role_admin) db.session.flush() role_user = Role.query.filter(Role.role_name == "user").first() if (role_user is None): role_user = Role(role_name='user', display_name="User") db.session.add(role_user) db.session.flush() role_employee = Role.query.filter(Role.role_name == "employee").first() if (role_employee is None): role_employee = Role(role_name='employee', display_name="Employee") db.session.add(role_employee) db.session.flush() role_leader = Role.query.filter(Role.role_name == "leader").first() if (role_leader is None): role_leader = Role(role_name='leader', display_name="Leader") db.session.add(role_leader) db.session.flush() role_member = Role.query.filter(Role.role_name == "member").first() if (role_member is None): role_member = Role(role_name='member', display_name="member") db.session.add(role_member) db.session.flush() user = User.query.filter(User.email == "*****@*****.**").first() # employee = Employee(full_name="Admin User", email="*****@*****.**",phone_number="0968244158",\ # id_identifier=123456) # user.employee = employee # user.roles = [role_admin] # db.session.add(user) db.session.commit() if user is None: # create salt letters = string.ascii_lowercase user_salt = ''.join(random.choice(letters) for i in range(64)) print("user_salt", user_salt) # create user password user_password = auth.encrypt_password(password, user_salt) #create user # employee = Employee(full_name="Admin User", email="*****@*****.**",phone_number="0968244158",\ # id_identifier=123456) user = User(display_name="Admin User", email="*****@*****.**",\ password=user_password, salt=user_salt, phone="0333333333") db.session.add(user) db.session.flush() new_group = Group( group_name="group Admin User", unsigned_name="group Admin User", assignee_id=user.id, # members=[user] ) db.session.add(new_group) db.session.flush() new_relation = GroupsUsers(user_id=user.id, group_id=new_group.id, role_id=role_admin.id) db.session.add(new_relation) db.session.commit() return