def registrar_usuario(): """ CREATE Registar un nuevo usuario desde usuario admin ID 7 USER_NEW permisos """ id_usuario = current_user.get_id() if User.tiene_permiso(id_usuario, 7): form = RegistrationForm() # POST. if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, first_name=form.first_name.data, last_name=form.last_name.data, active=form.active.data, password=form.password.data) if form.admin.data: user.roles.append(Role.query.get(1)) if form.operator.data: user.roles.append(Role.query.get(2)) # agrega nuevo user a la db. db.session.add(user) db.session.commit() # redirecciona a pagina login. return redirect(url_for('admin.listar_usuarios')) return render_template('admin/register.html', form=form, title='Centros de Ayuda GBA - Registro') else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))
def create_user(): """ 用户注册 --- tags: - 用户相关接口 description: 用户注册接口,json格式 parameters: - name: body description: 用户注册接口的body数据 in: body type: object required: true schema: id: 用户 required: - username - password properties: username: type: string description: 用户账号. name: type: string description: 用户名字. password: type: string description: 密码. email: type: string description: 邮箱. remark: type: string description: 备注. department_id: type: integer description: 部门id. responses: 200: description: """ data = request.get_json() if not data: code = ResponseCode.InvalidParameter return ResMsg(code=code, data='You must post JSON data.').data user = User() user.from_dict(data, new_user=True) db.session.add(user) db.session.commit() return ResMsg(data='用户创建成功').data
def turnos(page=1): """ READ Listar Todos los turnos reservados de los proximos tres dias. ID 1 CENTRO_INDEX permisos """ usuarios_por_pag = Config.query.first().n_elements id_usuario = current_user.get_id() if User.tiene_permiso(id_usuario, 1): fecha_hoy = datetime.datetime.today().strftime('%Y-%m-%d') fecha_man = (datetime.datetime.today() + datetime.timedelta(days=1)).strftime('%Y-%m-%d') fecha_pas = (datetime.datetime.today() + datetime.timedelta(days=2)).strftime('%Y-%m-%d') turnos_hoy = Appointment.query.filter_by(appointment_date=fecha_hoy) turnos_man = Appointment.query.filter_by(appointment_date=fecha_man) turnos_pas = Appointment.query.filter_by(appointment_date=fecha_pas) turnos = turnos_hoy.union(turnos_man, turnos_pas) turnos = turnos.paginate(page, per_page=usuarios_por_pag) return render_template('admin/turnos.html', turnos=turnos) else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))
def configuracion(): """ Vista de configuracion de sistema en administracion. """ id_usuario = current_user.get_id() if User.tiene_permiso(id_usuario, 10): # Trae la informacion ya cargada para mostrarla en el formulario cuando method=GET config = Config.query.first() if not config: form = ConfigForm() # Guarda la informacion cargada desde el template cuando method=POST if form.validate_on_submit(): config = Config(title=form.title.data, description=form.description.data, email=form.email.data, n_elements=form.n_elements.data, site_enabled=form.site_enabled.data) db.session.add(config) flash('Los cambios se guardaron correctamente.', 'success') else: form = ConfigForm(obj=config) # Guarda la informacion cargada desde el template cuando method=POST if form.validate_on_submit(): form.populate_obj(config) flash('Los cambios se guardaron correctamente.', 'success') db.session.commit() return render_template('admin/configuracion.html', form=form, title='Centros de Ayuda GBA - Configuración') else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))
def verify_wxapp(encrypted_data, iv, code, db_conn): ''' 功能: 通过get_wxapp_userinfo函数获取到user_info和session_key 根据user_info中的openId判断是否新用户 新用户直接注册,然后返回,老用户直接返回 参数: encrypted_data,iv,code 同 get_wxapp_userinfo方法 db_conn 数据库操作对象 返回格式: user_info: {"openId":"xxxxxxx",.......}, session_key ''' user_info, session_key = get_wxapp_userinfo(encrypted_data, iv, code) openid = user_info.get('openId', None) print(user_info) if openid: #user = User.query.get_or_404(openid) user = User.query.get(openid) if not user: user = User() user.from_dict(user_info) db_conn.session.add(user) db_conn.session.commit() return user_info, session_key
def get_followeds(id): '''返回用户已关注的人的列表''' user = User.query.get_or_404(id) page = request.args.get('page', 1, type=int) per_page = min( request.args.get('per_page', current_app.config['USERS_PER_PAGE'], type=int), 100) data = User.to_collection_dict(user.followeds, page, per_page, 'api.get_followeds', id=id) # 为每个 followed 添加 is_following 标志位 for item in data['items']: item['is_following'] = g.current_user.is_following( User.query.get(item['id'])) # 获取用户开始关注 followed 的时间 res = db.engine.execute( "select * from followers where follower_id={} and followed_id={}". format(user.id, item['id'])) item['timestamp'] = datetime.strptime( list(res)[0][2], '%Y-%m-%d %H:%M:%S.%f') # 按 timestamp 排序一个字典列表(倒序,最新关注的人在最前面) data['items'] = sorted(data['items'], key=itemgetter('timestamp'), reverse=True) return jsonify(data)
def get_department_members(id): """ 返回部门内用户具体信息 --- tags: - 部门相关接口 description: 部门信息接口 parameters: - name: id in: path type: integer description: 部门id responses: 200: description: """ department = Department.query.get_or_404(id) page = request.args.get('page', 1, type=int) per_page = min( request.args.get('per_page', current_app.config['USERS_PER_PAGE'], type=int), 100) data = User.to_collection_dict(department.members.order_by(User.id.desc()), page, per_page, 'api.get_department_members', id=id) return ResMsg(data=data).data
def register(): if re.match(r'[^@]+@[^@]+\.[^@]+', request.headers['user_mail']) is None: return jsonify({"code": "-2"}) user = User.query.filter( User.email == request.headers["user_mail"]).first() if user is not None: return jsonify({"code": "-1"}) user = User() user.email = request.headers['user_mail'] user.password = request.headers['user_pwd'] user.nickname = request.headers['user_nickname'] db.session.add(user) db.session.commit() return jsonify({"code": "1"})
def regist(): if request.method == "GET": return render_template("regist.html") else: username = request.form["username"] password = request.form["password"] print(username, password) db.session.add(User(username, password)) db.session.commit() return redirect("/")
def rechazar_centro(id): id_admin = current_user.get_id() if User.tiene_permiso(id_admin, 4): centro = HelpCenter.query.filter_by(id=id).first().status_id = 3 db.session.commit() flash('Centro Rechazado', 'success') return redirect(url_for('admin.centros_ayuda')) else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))
def verify_token(token): '''用于检查用户请求是否有token,并且token真实存在,还在有效期内''' g.current_user = User.verify_jwt(token) if token else None if g.current_user: # 每次认证通过后(即将访问资源API),更新 last_seen 时间 g.current_user.ping() db.session.commit() # department_id = g.current_user.get('department_id') # g.current_auth = Department.query.get(department_id).get('auth') return g.current_user is not None
def register(): form = RegisterForm() if form.validate_on_submit(): # 如果验证通过,则注册成功,将用户存进数据库 data = form.data user = User() # 实例化User user.username = data['username'] # form.data[''] 、request.form['']和request.form.get('')都可以获取form表单数据 user.email = data['email'] user.phone = data['phone'] user.uuid = uuid.uuid4().hex # 通用唯一识别码 user.role_id = data['role_id'] user.set_password(data['pwd']), db.session.add(user) # 插入数据至User表 db.session.commit() # 确认 flash("注册成功!") # flash('消息','flag') return redirect(url_for('home.login')) # 注册成功重定向至登录页面 return render_template('home/register.html', form=form)
def register(): error = None forms_register = forms.Register_Form() if forms_register.validate_on_submit(): user = User(name=forms_register.name.data, pwd=generate_password_hash(forms_register.password.data)) db.session.add(user) db.session.commit() flash('注册成功') print('-----------------------<>') return redirect(request.args.get('next') or url_for('home_view.index')) return render_template('register.html', form=forms_register, error=error)
def actualizar_centro(id): id_admin = current_user.get_id() if User.tiene_permiso(id_admin, 4): results = [] response = requests.get( 'https://api-referencias.proyecto2020.linti.unlp.edu.ar/municipios' ).json() per_page = response['per_page'] total = response['total'] for page in range(1, math.ceil(total / per_page) + 1): response = requests.get( 'https://api-referencias.proyecto2020.linti.unlp.edu.ar/municipios', params={ 'page': page }).json() data = response['data'] municipios = data['Town'] for v in municipios.values(): results.append((v['name'])) municipios_list = sorted(results) current_center = HelpCenter.query.filter_by(id=id).first() current_protocol = current_center.visit_protocol current_protocol_name = str(current_protocol).split('/')[-1:][0] form = HelpCenterForm(obj=current_center) form.town.choices = municipios_list form.center_type_id.choices = CenterType.query.with_entities( CenterType.id, CenterType.name_center_type).all() if form.validate_on_submit(): if form.visit_protocol.data != current_protocol: protocol_file = form.visit_protocol.data filename_vp = secure_filename(protocol_file.filename) protocol_path = path.join(current_app.root_path, 'static/uploads', filename_vp) protocol_file.save(protocol_path) form.visit_protocol.data = protocol_path form.populate_obj(current_center) db.session.commit() flash('Los cambios se guardaron correctamente.', 'success') return redirect(url_for('admin.centros_ayuda')) return render_template('admin/centro_edit.html', form=form, current_protocol=current_protocol_name, edit_mode=True) else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))
def turnos_centro(id=0, page=1): id_usuario = current_user.get_id() usuarios_por_pag = Config.query.first().n_elements centro = HelpCenter.query.filter_by(id=id).first() if User.tiene_permiso(id_usuario, 1): turnos = Appointment.query.filter_by(center_id=centro.id).paginate( page, per_page=usuarios_por_pag) return render_template('admin/turnos.html', turnos=turnos, centro=centro) else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))
def listar_usuarios(page=1): """ READ Vista de modulo CRUD usuarios en administracion. ID 6 USER_INDEX permisos """ usuarios_por_pag = Config.query.first().n_elements id_usuario = current_user.get_id() if User.tiene_permiso(id_usuario, 6): users = User.query.paginate(page, per_page=usuarios_por_pag) return render_template('admin/usuarios.html', users=users) else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))
def actualizar_turno(id): """ UPDATE Actualiza un turno ID 14 TURNO_UPDATE permisos """ id_admin = current_user.get_id() if User.tiene_permiso(id_admin, 14): turno_edit = Appointment.query.get(id) if not turno_edit: flash('El turno solicitado no existe.', 'danger') return redirect(url_for('admin.index')) centro = HelpCenter.query.get(turno_edit.center_id) centro_nombre = centro.name_center form = AppointmentForm(obj=turno_edit, id=id) # POST. if form.validate_on_submit(): form.populate_obj(turno_edit) delta = datetime.timedelta(minutes=30) start = form.start_time.data turno_edit.end_time = ( datetime.datetime.combine(datetime.date(1, 1, 1), start) + delta).time() # Me trae el turno del centro recibido, con esa fecha y esa hora de inicio turnos_del_dia = Appointment.query.filter_by( center_id=turno_edit.center_id, appointment_date=turno_edit.appointment_date, start_time=turno_edit.start_time) if turnos_del_dia.count() == 1: db.session.commit() # redirecciona al listado de usuarios flash('Los cambios se guardaron correctamente.', 'success') return redirect(url_for('admin.turnos_centro', id=centro.id)) else: flash('Turno no disponible', 'danger') return render_template( 'admin/turno_edit.html', form=form, center_name=centro_nombre, title='Centros de Ayuda GBA - Actualizar turno') return render_template('admin/turno_edit.html', form=form, center_name=centro_nombre, center_id=centro.id, title='Centros de Ayuda GBA - Actualizar turno') else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))
def usuarios_bloqueados(page=1): """ READ Devuelve una lista de los usuarios bloqueados ID 6 USER_INDEX permisos """ usuarios_por_pag = Config.query.first().n_elements id_usuario = current_user.get_id() if User.tiene_permiso(id_usuario, 6): users = User.query.filter_by(active=False).paginate( page, per_page=usuarios_por_pag) return render_template('admin/usuarios.html', users=users) else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))
def actualizar_usuario(id_user): """ Vista de actualizacion de un usuario enviado como parámetro con un usuario admin Requiere permiso con ID 9 (USER_UPDATE) """ id_admin = current_user.get_id() if User.tiene_permiso(id_admin, 9): user_edit = User.query.filter_by(id=id_user).first() if not user_edit: flash('El usuario solicitado no existe.', 'danger') return redirect(url_for('admin.index')) roles = user_edit.roles.all() es_admin = Role.query.filter_by(name='admin').first() in roles es_operador = Role.query.filter_by(name='operador').first() in roles form = EditForm(obj=user_edit, id=id_user, admin=es_admin, operator=es_operador) # POST. if form.validate_on_submit(): form.populate_obj(user_edit) if form.admin.data: if not es_admin: user_edit.roles.append(Role.query.get(1)) elif es_admin: user_edit.roles.remove(Role.query.get(1)) if form.operator.data: if not es_operador: user_edit.roles.append(Role.query.get(2)) elif es_operador: user_edit.roles.remove(Role.query.get(2)) db.session.commit() # redirecciona al listado de usuarios flash('Los cambios se guardaron correctamente.', 'success') return redirect(url_for('admin.listar_usuarios')) return render_template('admin/update_user.html', form=form, title='Centros de Ayuda GBA - Configuración') else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))
def reset_password(token): '''用户点击邮件中的链接,通过验证 JWT 来重置对应的账户的密码''' data = request.get_json() if not data: return bad_request('You must post JSON data.') if 'password' not in data or not data.get('password', None).strip(): return bad_request('Please provide a valid password.') user = User.verify_reset_password_jwt(token) if not user: return bad_request( 'The reset password link is invalid or has expired.') user.set_password(data.get('password')) db.session.commit() return jsonify({ 'status': 'success', 'message': 'Your password has been reset.' })
def post(self): data = request.get_json() hashed_password = generate_password_hash(data['password'], method='sha256') new_user = User(public_id=str(uuid.uuid4()), username=data['username'], password=hashed_password, admin=False) db.session.add(new_user) db.session.commit() responseObject = {'status': 'success', 'message': 'New user created!'} return responseObject, 201
def wx_login_or_register(wx_user_info): """ 验证该用户是否注册本平台,如果未注册便注册后登陆,否则直接登陆。 :param wx_user_info:拉取到的微信用户信息 :return: """ # 微信统一ID unionid = wx_user_info.get("unionid") # 用户昵称 nickname = wx_user_info.get("nickname") # 拉取微信用户信息失败 if unionid is None: return None # 判断用户是否存在与本系统 user_login = db.session(UserLoginMethod). \ filter(UserLoginMethod.login_method == "WX", UserLoginMethod.identification == unionid, ).first() # 存在则直接返回用户信息 if user_login: user = db.session.query( User.id, User.name).filter(User.id == user_login.user_id).first() data = dict(zip(user.keys(), user)) return data # 不存在则先新建用户然后返回用户信息 else: try: # 新建用户信息 new_user = User(name=nickname, age=20) db.session.add(new_user) db.session.flush() # 新建用户登陆方式 new_user_login = UserLoginMethod(user_id=new_user.id, login_method="WX", identification=unionid, access_code=None) db.session.add(new_user_login) db.session.flush() # 提交 db.session.commit() except Exception as e: print(e) return None data = dict(id=new_user.id, name=User.name) return data
def add_user(username: str, password: str, parent: int, role: int): """ 新建用户 :param username: :param password: :param parent: :param role: 用户角色 :return: """ user = User( username=username, password=password, nickname=username, role=role, parent_id=parent, ) db.session.add(user) session_commit()
def turnos_buscar(page=1): search_name = request.form.get('buscar-nombre') search_date = request.form.get('buscar-fecha') if search_name or search_date: return redirect( url_for('admin.turnos_buscar', buscar=search_name, fecha=search_date)) else: search_name = request.args.get('buscar') search_date = request.args.get('fecha') id_usuario = current_user.get_id() usuarios_por_pag = Config.query.first().n_elements if User.tiene_permiso(id_usuario, 1): if search_name: results = HelpCenter.query.filter( HelpCenter.name_center.contains(search_name)).with_entities( HelpCenter.id) help_centers_ids = [value for value, in results] turnos = Appointment.query.filter( Appointment.center_id.in_(help_centers_ids)).union( Appointment.query.filter( Appointment.email.contains(search_name))) if search_date: turnos = turnos.filter_by(appointment_date=search_date) else: if search_date: turnos = Appointment.query.filter_by( appointment_date=search_date) else: turnos = Appointment.query turnos = turnos.paginate(page, per_page=usuarios_por_pag) return render_template('admin/turnos.html', turnos=turnos, search_name=search_name, search_date=search_date) else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))
def register(): if request.method == 'GET': return render_template('register.html') openid = session.get('wechat_user_id') phone = request.form['cellphone'] code = request.form['code'] user_phone = User.query.filter_by(phone=phone).first() if user_phone: return render_template('dashboard.html', user=user_phone) sess_code = session.get(phone) if not sess_code: return "<h1>验证码无效!</h1>" if code.strip() == str(sess_code).strip(): user = User(phone=phone, openid=openid, head_pic=session.get('wechat_user_header')) db.session.add(user) session.pop(phone) # 清除掉缓存中的验证码 generate_qrcode(openid) # 生成用户二维码 db.session.commit() # 判断是否是由扫码,未注册用户跳转过来 flag1 = session.get('caller-{0}'.format(openid)) flag2 = session.get('callee-uuid') if flag1 and flag2: callee = User.query.filter_by(uuid=flag2).first() session.pop('caller-{0}'.format(openid)) session.pop('callee-uuid') if not callee: abort(404) # print(user) # print(callee) return render_template('index.html', caller=user, callee=callee) else: return render_template('dashboard.html', user=user) else: return "<h1>验证码不匹配!</h1>"
def eliminar_centro(id): id_admin = current_user.get_id() if User.tiene_permiso(id_admin, 3): center_delete = HelpCenter.query.filter_by(id=id).first() if not center_delete: flash('El centro de ayuda solicitado no existe.', 'danger') return redirect(url_for('admin.centros_ayuda')) Appointment.query.filter_by(center_id=id).delete() db.session.delete(center_delete) db.session.commit() flash('El centro de ayuda se eliminó correctamente', 'success') return redirect(url_for('admin.centros_ayuda')) else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index')) return 'Borrado de Centro de ayuda'
def buscar_por_nombre(page=1): """ READ Devuelve una lista de usuarios con nombre enviado como parametro ID 6 USER_INDEX permisos """ usuarios_por_pag = Config.query.first().n_elements search = request.form.get('buscar-nombre') id_usuario = current_user.get_id() if User.tiene_permiso(id_usuario, 6): users = User.query.filter( or_(User.first_name.contains(search), User.last_name.contains(search))).paginate( page, per_page=usuarios_por_pag) return render_template('admin/usuarios.html', users=users, search=search) else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))
def post(self): data = request.get_json() username = data['username'] password = data['password'] db_obj = DBManager(app.config['DATABASE_URL']) user = db_obj.auth_user(username) query = db_obj.fetch_by_param('users', 'username', data['username']) if not query: return { 'message': 'Please either register, enter right values or User does not exist' }, 400 the_user = User(query[0], query[1], query[2], query[3]) if check_password_hash( user['password'], password) and the_user.username == data['username']: access_token = create_access_token(identity=user) return {'access_token': access_token}, 200 else: return {'message': 'Wrong password'}, 400
def turnos_centro_buscar(id=0, page=1): search_date = request.form.get('buscar-fecha') search_name = request.form.get('buscar-nombre') id_usuario = current_user.get_id() usuarios_por_pag = Config.query.first().n_elements centro = HelpCenter.query.filter_by(id=id).first() if User.tiene_permiso(id_usuario, 1): turnos = Appointment.query.filter_by(center_id=centro.id) if search_name: turnos = turnos.filter(Appointment.email.contains(search_name)) if search_date: turnos = turnos.filter_by(appointment_date=search_date) turnos = turnos.paginate(page, per_page=usuarios_por_pag) return render_template('admin/turnos.html', turnos=turnos, search_date=search_date, search_name=search_name, centro=centro) else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))
def eliminar_turno(id): """ DELETE Eliminar un turno ID 13 TURNO_DESTROY permisos """ id_usuario = current_user.get_id() if User.tiene_permiso(id_usuario, 13): turno = Appointment.query.get(id) if not turno: flash('El turno no existe.', 'danger') return redirect(url_for('admin_index')) db.session.delete(turno) db.session.commit() flash('El turno se eliminó correctamente.', 'success') return redirect(url_for('admin.turnos')) else: flash('No tienes permisos para realizar esa acción.', 'danger') return redirect(url_for('admin.index'))