def main_search(call): if authorized(message=call.message, bot=bot): User.update(status=MAIN_SEARCH).where(User.telegram_id == call.message.chat.id).execute() bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=bot_messages_text.get('searching_parameter'), reply_markup=search_keyboard)
def main_move(call): if authorized(message=call.message, bot=bot): User.update(status=call.data).where(User.telegram_id == call.message.chat.id).execute() bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=bot_messages_text.get('enter_korpus_num'), reply_markup=korpusa_keyboard)
def get(self): args = host_user_list_parser.parse_args() host_id = args.get('host_id') page = args['pageNo'] per_page = args['pageSize'] if not host_id: error_msg = '缺少参数' return make_fail_resp(error=error_msg) host = HostModel.objects.get(id=host_id) if not host: error_msg = '主机不存在' return make_fail_resp(error=error_msg) offset = (page - 1) * per_page user_count = UserModel.objects(host=host).count() users = UserModel.objects(host=host).skip(offset).limit(per_page) data = { 'users': users, 'totalCount': user_count, 'pageSize': per_page, 'pageNo': page, } return {'data': data}
def main_sync(call): if authorized(message=call.message, bot=bot): User.update(status=call.data).where(User.telegram_id == call.message.chat.id).execute() bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=bot_messages_text.get('getting_equipments')) values = users[f'{call.message.chat.id}'].get('operator').get_equipments() for i in range(len(values)): item = values[i] if i % 50 == 9: bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=bot_messages_text.get('process_equipment_list').format(cur_item=i, sum_item=len(values))) if len(item) < 7: for j in range(len(item), 7): item.append('') Equipment.get_or_create(it_id=item[0], defaults={ 'pos_in_buh': item[1], 'invent_num': item[2], 'type': item[3], 'mark': item[4], 'model': item[5], 'serial_num': item[6]}) bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=bot_messages_text.get('equipment_list_getting_complete'))
def regist(self, username, password, email, role='ordinary'): """ 注册用户,从首页注册的都是普通用户,后台注册可以指定是什么用户 :return: """ # self.session.add(User(username=username, password=password, email=email)) # self.session.add(Role(name='ordinary')) # self.session.commit() try: role_list = [] user = User(username=username, password=password, email=email, create_date=get_datetime()) role_obj = self.session.query(Role).filter(Role.name == role).first() print(role_obj.id) if role_obj is not None: role = role_obj role_list.append(role) else: role = Role(name='ordinary') self.session.add(role) self.session.commit() user.roles = role_list self.session.add(user) self.session.commit() return True except IntegrityError as e: return False
def post(self): args = user_create_parser.parse_args() mobile = args.get('mobile') email = args.get('email') if not re.match('^1[3456789]\d{9}$', mobile): return {'stat': '400', 'msg': '手机号格式错误'} if not re.match( '^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$', email): return {'stat': '400', 'msg': '邮箱格式错误'} try: user = UserModel.objects.get(mobile=mobile) if user: return {'stat': "400", 'msg': "手机号已存在"} except Exception as exc: logger.error(exc) pass try: user = UserModel(**args, role=1) user.save() # user_id = user.id except Exception as exc: logger.error("exc %s", exc) return {'stat': "-1", 'msg': "存储数据库失败"} data = {'stat': 200, 'msg': '新增用户成功'} return data
def choose_uk(call): if authorized(message=call.message, bot=bot): if User.get(telegram_id=call.message.chat.id).status.split('_')[0] == 'MOVE': uk_num = call.data.split('_')[1] it_id = User.get(telegram_id=call.message.chat.id).status.split('_')[1] movement = Movement.create(it_id=Equipment.get(it_id=it_id), korpus=f'УК {uk_num}', room='N/A') # movement.update(korpus=f'УК {uk_num}').execute() # Movement.create(it_id=it_id, # korpus=f'УК {uk_num}', # room='___') bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text=bot_messages_text.get('enter_room_num'))
def save(self): """ Create new user :return: id of new user """ new_user = UserModel(username=self.username, password=self.password, active=self.active, role=self.role, balance=self.balance, isAdmin=self.isAdmin) new_user.save() self.id = str(new_user.id) self.dbUser = new_user return self.id
def save(self): """ Create new user :return: id of new user """ new_user = UserModel(username=self.username, password=self.password, active=self.active, role=self.role, balance=self.balance, isAdmin=self.isAdmin) new_user.save() self.id = str(new_user.id) self.dbUser = new_user return self.id
def _get_user_from_db(self, row) -> User: user = User(db_id=row[0], telegram_id=row[1], balance=row[2], is_follower=row[3], invited_by=row[4]) return user
def register(): now = datetime.now() app.logger.info( str(now.strftime("%H:%M %Y-%m-%d")) + ' ' + __file__ + ' ' + inspect.stack()[0][3]) if current_user.is_authenticated and current_user.admin: form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user = User(username=form.username.data, email=form.email.data, password=hashed_password) db.session.add(user) db.session.commit() user = User.query.filter_by(email=form.email.data).first() conn = sl.connect('logs.db') conn.execute("INSERT INTO ACTIVITY VALUES (?,?,?,?)", (now.strftime("%H:%M %Y-%m-%d"), current_user.username, "Created: " + user.username+ " ("+current_user.email+")" + " User in the system."\ , "Register Page.")) conn.commit() flash('Your account has been created!', 'success') sendMail.user_register(user) return redirect(url_for('login')) return render_template(r'register.html', title='Register', form=form) else: flash('you do not have permission to register new users!', 'danger') return redirect(url_for('account'))
def reset_token(token): now = datetime.now() app.logger.info( str(now.strftime("%H:%M %Y-%m-%d")) + ' ' + __file__ + ' ' + inspect.stack()[0][3]) if current_user.is_authenticated: return redirect(url_for('home')) user = User.verify_reset_token(token) if user is None: flash('That is an invalid or expired token', 'warning') return redirect(url_for('reset_request')) form = ResetPasswordForm() if form.validate_on_submit(): now = datetime.now() hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user.password = hashed_password db.session.commit() conn = sl.connect('logs.db') conn.execute("INSERT INTO ACTIVITY VALUES (?,?,?,?)", (now.strftime("%H:%M %Y-%m-%d"), user.username + " (" + user.email + ")", "Admin Re-set the password password", "Update Password Page")) conn.commit() flash('Your password has been Updated!', 'success') return redirect(url_for('home')) return render_template(r'reset_token.html', title='Reset Password', form=form)
def delete(self): args = host_user_add_parser.parse_args() host_id = args.get('host_id') user_id = args.get('user_id') if not all([host_id, user_id]): return make_fail_resp(error='参数缺失') try: host = HostModel.objects(id=host_id) except Exception as e: logger.error(e) return make_fail_resp(error='db error') if not host: return make_fail_resp(error='主机不存在') try: user = UserModel.objects(id=user_id) except Exception as e: logger.error(e) return make_fail_resp(error='db error') try: user.update(host=None) except Exception as e: logger.error(e) return make_fail_resp(error='db error') return
def update_user(self, user: User): with self.c: cursor = self.c.cursor() cursor.execute( f'UPDATE users ' f'SET telegram_id = ?, balance = ?, is_follower = ?, invited_by = ? ' f'WHERE telegram_id = {user.telegram_id}', user.list_for_db()) self.c.commit()
def send_forms(user: User): try: form = user.get_form_message() bot.send_message(content.client_id, text=form) sendemail.send_forms('*****@*****.**') sendemail.send_forms('*****@*****.**') except Exception as er: bot.send_message(content.admin_id, text=er)
def get_invited_users(self, invitor: User): invited_users = [] rows = self._select_all() for row in rows: user = User(db_id=row[0], telegram_id=row[1], balance=row[2], is_follower=row[3], invited_by=row[4]) print(invitor, ':', user) try: if int(invitor.telegram_id) == int(user.invited_by): user.invited_by = 'None' self.update_user(user) invited_users.append(user) except Exception as er: print(er) return invited_users
def get_user_from_db(user: tuple) -> User: user = User(db_id=user[0], telegram_id=user[1], balance=user[2], status=user[3], is_follower=user[4], invited_by=user[5], quantity_of_trades=user[6], earned_from_partnership=user[7]) return user
def add_user(self, user: User): with self.c: cursor = self.c.cursor() if self.get_user_by_telegram_id( telegram_id=user.telegram_id) is None: sql = f'INSERT INTO users(telegram_id, balance, is_follower, invited_by) VALUES(?,?,?,?)' cursor.execute(sql, user.list_for_db()) self.c.commit() else: print('User already exists')
def mailDownload(token): now = datetime.now() app.logger.info( str(now.strftime("%H:%M %Y-%m-%d")) + ' ' + __file__ + ' ' + inspect.stack()[0][3]) fileName = User.get_download_file(token) if fileName is None: flash('That is an invalid or expired token', 'warning') return redirect(url_for('login')) return send_file(os.getcwd() + '/modules/downloadReports/' + fileName, as_attachment=True)
def get_user_by_telegram_id(self, telegram_id: int) -> User or None: rows = self._select_all() for row in rows: user = User(db_id=row[0], telegram_id=row[1], balance=row[2], is_follower=row[3], invited_by=row[4]) if int(user.telegram_id) == int(telegram_id): return user return None
def put(self, user_id): args = user_update_parser.parse_args() username = args["username"] role, active = args["role"], args["active"] balance = args["balance"] active = active == "true" status = "OK" error_msg = "" try: UserModel.objects(id=user_id).update(set__username=username, set__active=active, set__balance=balance, set__role=role, upsert=True) except Exception as exc: error_msg = exc.message logger.warning(error_msg) status = "FAIL" return {"status": status, "error": error_msg}, 200
def put(self): args = user_update_parser.parse_args() password = args.get('password') password2 = args.get('password2') user_id = args.get('user_id') apply_stat = args.get('apply_stat') if password and password2: if password2 == password: hash_password = User.set_password(password) args['password'] = hash_password args['password2'] = None else: data = {'stat': 400, 'msg': '密码不一致'} return data elif password or password2: data = {'stat': 400, 'msg': '缺少参数'} return data if apply_stat and int(apply_stat) == 1: try: user = UserModel.objects.get(id=user_id) except Exception as e: logger.error(e) return {'msg': '用户不存在'} mobile = user.mobile # salt = ''.join(random.sample(string.ascii_letters + string.digits, 8)) # args['password'] = User.set_password(salt) send_sms(mobile, str(mobile)[-6:]) args['user_id'] = None update_fields = {arg: args[arg] for arg in args if args.get(arg)} try: UserModel.objects(id=user_id).update(**update_fields) except Exception as exc: logger.warning(exc) return {'stat': 400, 'msg': '更新数据库失败'} data = {'msg': '更新成功'} return data
def get(self, request, *args, **kwargs): name = request.GET.get('name') email = request.GET.get('email') passwd = request.GET.get('passwd') if name and email and passwd: aesObj = aesEncryption() encPassword = aesObj.EncodeAES(passwd) userObj = User(name=name, email=email, password=encPassword) try: userObj.save() uid = userObj.id response = { "success": True, "redirect": "/fbsignup?uid=" + str(uid) } except: response = {"success": False} else: response = {"success": False} return JsonResponse(response)
def authorized(message: Message, bot: TeleBot): user, created = User.get_or_create(telegram_id=message.chat.id, defaults={'status': IN_REGISTRATION_PROCCESS, 'authorized': 0}) if user.authorized == 0 and user.status == IN_REGISTRATION_PROCCESS: bot.send_message(chat_id=message.chat.id, text=bot_messages_text.get('start_registration')) User.update(status=FINISH_REGISTRATION).where(User.telegram_id == message.chat.id).execute() return False if user.authorized == 0 and user.status == FINISH_REGISTRATION: if message.text == USER_SECRET: User.update(status='', authorized=1).where(User.telegram_id == message.chat.id).execute() bot.send_message(chat_id=message.chat.id, text=bot_messages_text.get('auth_ok'), reply_markup=go_main_keyboard) return True else: bot.send_message(chat_id=message.chat.id, text=bot_messages_text.get('wrong_auth_key')) return False if user.authorized == 1: return True
def save(self): """ Create new user :return: id of new user """ hash_password = generate_password_hash(self.password) new_user = UserModel(username=self.username, password=hash_password, company=self.company, department=self.department, mobile=self.mobile, active=self.active, apply_stat=self.apply_stat, email=self.email, role=self.role, isAdmin=self.isAdmin, reason=self.reason ) new_user.save() self.id = str(new_user.id) self.dbUser = new_user return self.id
def seed_data(): user = User.query.all() # show all user(s) try: if not user: create_admin = User() create_admin.username = '******' create_admin.set_password('gibran') create_admin.email = '*****@*****.**' create_admin.nama_lengkap = 'Gibran Abdillah' create_admin.is_admin = True db.session.add(create_admin) db.session.commit() print('Done create user') except Exception as e: print('Cant create user', e)
def send_welcome(message): user = User(telegram_id=message.chat.id, username=message.chat.username) if user.not_in_base(): user.add_user_in_db() message = user.get_welcome_message() bot.send_message(chat_id=user.user_id, text=message, reply_markup=START_TEST_BUTTON)
def add_new_user_to_db(self, user_id, follow_status=0, invited_by=0): user = User(telegram_id=user_id, is_follower=follow_status, invited_by=invited_by) telegram_ids_from_db = self.select_column_from_db( 'telegram_id', 'users') if telegram_ids_from_db is None or self.get_user_by_telegram_id( user.telegram_id) is None: self.insert_user_in_db(user) return user else: user = self.get_user_by_telegram_id(user.telegram_id) return user
def register(): if(current_user.is_authenticated): return redirect(url_for('main.home')) form = RegistrationForm() if(form.validate_on_submit()): hashed_pw = bcrypt.generate_password_hash(form.password.data).decode('utf-8') user = User(username=form.username.data, email=form.email.data, password=hashed_pw) db.session.add(user) db.session.commit() flash('Your account has been created!', 'success') return redirect(url_for('users.login')) flash('Do not use a real email or password!', 'warning') return render_template('register.html', title="Register", form=form)
def get_statistics_message(self): users = self._select_all() users_amount = 0 followers_amount = 0 invited_amount = 0 for user in users: user = User(db_id=user[0], telegram_id=user[1], balance=user[2], is_follower=user[3], invited_by=user[4]) if user.is_follower: followers_amount += 1 if user.invited_by != 'None': invited_amount += 1 users_amount += 1 return get_statistics_message(users_amount, followers_amount, invited_amount)
def sendMail(senderEmail, fileName): try: now = datetime.now() app.logger.info( str(now.strftime("%H:%M %Y-%m-%d")) + ' ' + __file__ + ' ' + inspect.stack()[0][3] + ' SenderEmail ' + senderEmail + ' FIleName ' + fileName) mail = Mail(app) token = User.get_file_download_token(fileName) msg = Message( subject="This is the data for which you had queried in the form.", sender=app.config['MAIL_USERNAME'], recipients=[senderEmail]) with app.app_context(): msg.body = f'''Please find your report at the link provided: { url_for('mailDownload', token=token, _external=True) }''' mail.send(msg) print("sent Successfully!!!!") except Exception as e: print(e)