예제 #1
0
def user_login():
    username = request.form.get('Username')
    password = request.form.get('Password')

    if not username:
        raise BenomeControllerException('Username required')

    user_details = user_manager.get_user(username=username, exception=False)
    if not user_details:
        raise BenomeControllerException('Login failed')

    user_id = None
    context_id = None

    if current_user and not current_user.is_anonymous and current_user.get_name() == username:
        user_id = current_user.get_id()
        context_id = current_user.get_root_context_id()
        user = current_user
    else:
        user = init_user(username=username, password=password)
        if user:
            login_user(user, remember=True)
            user_id = user.get_id()
            context_id = user.get_root_context_id()
        else:
            raise BenomeControllerException('Login failed')

    return json_response(auth_result(user))
예제 #2
0
def user_root(username):
    display_username = ''

    if current_user and not current_user.is_anonymous:
        current_username = current_user.get_name()
        if current_username != username:
            return redirect('/' + current_username)

        else:
            display_username = '******'s' % current_username.title()
    else:
        auth_token = request.args.get('autologin')

        token_map = {
            'fzEp98ABbvrM': ('ycf', 'rwu2Dfg37rsY'),
            '2MLxLxmwjVUw': ('ycf2', 'ZH4ysaFQHfbs'),
            'UNp9Z9EmwMHp': ('ycf3', 'L9FnxeL3vC6u')
        }

        if auth_token in token_map:
            username, password = token_map[auth_token]

            user = init_user(username=username, password=password)
            if user:
                login_user(user, remember=True)

    return render_template('base.html', **{
        'Username': display_username
        })
예제 #3
0
    def test_2_login(self):
        print ''
        print 'test login/logout process'

        with self.app:
            print 'get login page'
            rv = self.app.get('/login')
            assert '<form id="login"' in rv.data

            print 'login refused - credentials'
            rv = self.login('admin', 'default')
            assert 'Invalid credentials: username is unknown or password is invalid.' in rv.data

            print 'login refused - credentials'
            rv = self.login('admin', '')
            assert 'Invalid credentials: username is unknown or password is invalid.' in rv.data

            print 'login accepted - home page'
            rv = self.login('admin', 'admin')
            assert '<title>Home page</title>' in rv.data
            print 'login accepted - user attributes'
            assert current_user.username == 'admin'
            print 'user:'******'user name:', current_user.get_name()
            print 'token:', current_user.get_auth_token()
            print 'username:'******'user role:', current_user.get_role()
            print 'user picture:', current_user.get_picture()
            print 'admin:', current_user.can_admin()
            print 'action:', current_user.can_action()

            print 'reload home page'
            rv = self.app.get('/')
            assert '<title>Home page</title>' in rv.data

            print 'reload home page'
            rv = self.app.get('/?search=test')
            assert '<title>Home page</title>' in rv.data

            print 'reload home page'
            rv = self.app.get('/index')
            assert '<title>Home page</title>' in rv.data

            print 'refresh header'
            rv = self.app.get('/refresh_header')
            assert 'html_livesynthesis' in rv.data

            print 'refresh livestate'
            rv = self.app.get('/refresh_livestate')
            assert 'livestate' in rv.data

            print 'refresh livesynthesis'
            rv = self.app.get('/livesynthesis')
            assert 'livesynthesis' in rv.data

            print 'logout - go to login page'
            rv = self.logout()
            assert '<form id="login"' in rv.data
예제 #4
0
파일: users.py 프로젝트: ByReaL/OctoPrint
def getSettingsForUser(username):
	if not userManager.enabled:
		return jsonify(SUCCESS)

	if current_user is None or current_user.is_anonymous() or (current_user.get_name() != username and not current_user.is_admin()):
		return make_response("Forbidden", 403)

	try:
		return jsonify(userManager.getAllUserSettings(username))
	except users.UnknownUser:
		return make_response("Unknown user: %s" % username, 404)
예제 #5
0
파일: users.py 프로젝트: ByReaL/OctoPrint
def getUser(username):
	if not userManager.enabled:
		return jsonify(SUCCESS)

	if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
		user = userManager.findUser(username)
		if user is not None:
			return jsonify(user.asDict())
		else:
			abort(404)
	else:
		abort(403)
예제 #6
0
파일: users.py 프로젝트: ByReaL/OctoPrint
def generateApikeyForUser(username):
	if not userManager.enabled:
		return jsonify(SUCCESS)

	if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
		try:
			apikey = userManager.generateApiKey(username)
		except users.UnknownUser:
			return make_response(("Unknown user: %s" % username, 404, []))
		return jsonify({"apikey": apikey})
	else:
		return make_response(("Forbidden", 403, []))
예제 #7
0
def getUser(username):
    if not userManager.enabled:
        return jsonify(SUCCESS)

    if current_user is not None and not current_user.is_anonymous and (
            current_user.get_name() == username or current_user.is_admin):
        user = userManager.findUser(username)
        if user is not None:
            return jsonify(user.asDict())
        else:
            abort(404)
    else:
        abort(403)
예제 #8
0
def generateApikeyForUser(username):
    if not userManager.enabled:
        return jsonify(SUCCESS)

    if current_user is not None and not current_user.is_anonymous and (
            current_user.get_name() == username or current_user.is_admin):
        try:
            apikey = userManager.generateApiKey(username)
        except users.UnknownUser:
            return make_response(("Unknown user: %s" % username, 404, []))
        return jsonify({"apikey": apikey})
    else:
        return make_response(("Forbidden", 403, []))
예제 #9
0
def getSettingsForUser(username):
    if not userManager.enabled:
        return jsonify(SUCCESS)

    if current_user is None or current_user.is_anonymous() or (
            current_user.get_name() != username
            and not current_user.is_admin()):
        return make_response("Forbidden", 403)

    try:
        return jsonify(userManager.getAllUserSettings(username))
    except users.UnknownUser:
        return make_response("Unknown user: %s" % username, 404)
예제 #10
0
    def __unregister_an_event(self, event_name):
        """Метод отмены регистрации юзера на заданное событие"""

        # FIXME: Сделать нормальные именя методов, полностью отображающие их ф-ии.
        if self.__db_connector.validate_event(event_name):
            flash("Такого события не существует.", "error")
            # Проверка на существование события.
        elif not self.__db_connector.event_open_for_registration(event_name):
            # Проверка, что от события еще можно отписаться без
            # записи результатов юзера в этом событии.
            flash("Это событие уже началось.", "error")
        elif not self.__db_connector.user_in_event(current_user.get_name(),
                                                   event_name):
            # Проверка, что данный юзер есть в этом событии.
            flash("Вы не зарегистрированы на это событие.", "error")
        else:
            # Если все проверки пройдены, отменяем регистрацию юзера на событие.
            self.__db_connector.unregister_user_from_event(
                current_user.get_name(), event_name)
            flash("Регистрация успешно отменена!", "success")

        return redirect(url_for("__profile"))
예제 #11
0
    def __event(self, event_name):
        """Рендеринг страницы события и загрузки решения"""
        event = self.__db_connector.load_event(event_name=event_name)

        if not event or event.get_run_date() >= dt.datetime.now():
            flash("Событие еще не началось.", "error")
            return redirect(url_for("__profile"))
        if not self.__db_connector.user_in_event(current_user.get_name(),
                                                 event_name):
            flash("Вы не зарегистрированны на это событие.")
            return redirect(url_for("__index"))

        return render_template("loading.html", event=event)
예제 #12
0
def generate_apikey_for_user(username):
    if not userManager.enabled:
        return jsonify(SUCCESS)

    if (current_user is not None and not current_user.is_anonymous
            and (current_user.get_name() == username
                 or current_user.has_permission(Permissions.ADMIN))):
        try:
            apikey = userManager.generate_api_key(username)
        except users.UnknownUser:
            abort(404)
        return jsonify({"apikey": apikey})
    else:
        abort(403)
예제 #13
0
def delete_apikey_for_user(username):
    if not userManager.enabled:
        return jsonify(SUCCESS)

    if current_user is not None and not current_user.is_anonymous and (
            current_user.get_name() == username
            or current_user.has_permission(Permissions.ADMIN)):
        try:
            userManager.delete_api_key(username)
        except users.UnknownUser:
            return make_response(("Unknown user: %s" % username, 404, []))
        return jsonify(SUCCESS)
    else:
        return make_response(("Forbidden", 403, []))
def user_tasks(user, apiver=fg_config['fgapiver']):
    global fgapisrv_db

    logging.debug('user_tasks(%s)/%s: %s' %
                  (request.method, user, request.values.to_dict()))
    api_support, state, message = check_api_ver(apiver)
    if not api_support:
        status = 400
        response = {"message": message}
    else:
        application = request.values.get('application')
        user_name = current_user.get_name()
        user_id = current_user.get_id()
        logging.debug("user_name: '%s'" % user_name)
        logging.debug("user_id: '%s'" % user_id)
        user = request.values.get('user', user)
        if request.method == 'GET':
            auth_state, auth_msg = \
                authorize_user(current_user, None, user, "users_tasks_view")
            if auth_state is True:
                if fgapisrv_db.user_exists(user):
                    tasks_list = []
                    user_task_ids =\
                        fgapisrv_db.user_tasks_retrieve(user, application)
                    for task_id in user_task_ids:
                        task_record = fgapisrv_db.get_task_record(task_id)
                        tasks_list += [
                            task_record,
                        ]
                    status = 200
                    response = {'tasks': tasks_list}
                else:
                    status = 404
                    response = {
                        'message': 'User \'%s\' does not exists' % user
                    }
            else:
                status = 402
                response = {
                    "message":
                    "Not authorized to perform this request:\n%s" % auth_msg
                }
        else:
            status = 400
            response = {"message": "Unhandled method: '%s'" % request.method}
    logging.debug('message: %s' % response.get('message', 'success'))
    js = json.dumps(response, indent=fg_config['fgjson_indent'])
    resp = Response(js, status=status, mimetype='application/json')
    resp.headers['Content-type'] = 'application/json'
    return resp
예제 #15
0
def get_user(username):
    if not userManager.enabled:
        return jsonify(SUCCESS)

    if current_user is not None and not current_user.is_anonymous and (
            current_user.get_name() == username
            or current_user.has_permission(Permissions.ADMIN)):
        user = userManager.find_user(username)
        if user is not None:
            return jsonify(user)
        else:
            abort(404)
    else:
        abort(403)
예제 #16
0
def get_settings_for_user(username):
    if (
        current_user is None
        or current_user.is_anonymous
        or (
            current_user.get_name() != username
            and not current_user.has_permission(Permissions.ADMIN)
        )
    ):
        abort(403)

    try:
        return jsonify(userManager.get_all_user_settings(username))
    except users.UnknownUser:
        abort(404)
예제 #17
0
def viewGroups():
    therapistLiteral = "{} {} {}".format(current_user.get_name(), current_user.get_surname1(), \
        current_user.get_surname2())

    form = SearchGroupsForm()

    if form.validate_on_submit():
        rowGroups = searchGroups(form)
        return render_template('viewGroups.html',
                               form=form,
                               rowGroups=rowGroups,
                               therapistLiteral=therapistLiteral)

    return render_template('viewGroups.html',
                           form=form,
                           therapistLiteral=therapistLiteral)
예제 #18
0
def change_settings_for_user(username):
    if (current_user is None or current_user.is_anonymous
            or (current_user.get_name() != username
                and not current_user.has_permission(Permissions.ADMIN))):
        abort(403)

    data = request.get_json()

    if data is None:
        abort(400, description="Malformed JSON body in request")

    try:
        userManager.change_user_settings(username, data)
        return jsonify(SUCCESS)
    except users.UnknownUser:
        abort(404)
예제 #19
0
def changePasswordForUser(username):
    if userManager is None:
        return jsonify(SUCCESS)

    if current_user is not None and not current_user.is_anonymous and (
            current_user.get_name() == username or current_user.is_admin()):
        if "application/json" in request.headers["Content-Type"]:
            data = request.json
            if "password" in data.keys() and data["password"]:
                try:
                    userManager.changeUserPassword(username, data["password"])
                except users.UnknownUser:
                    return make_response(
                        ("Unknown user: %s" % username, 404, []))
        return jsonify(SUCCESS)
    else:
        return make_response(("Forbidden", 403, []))
예제 #20
0
파일: users.py 프로젝트: ByReaL/OctoPrint
def changeSettingsForUser(username):
	if not userManager.enabled:
		return jsonify(SUCCESS)

	if current_user is None or current_user.is_anonymous() or (current_user.get_name() != username and not current_user.is_admin()):
		return make_response("Forbidden", 403)

	try:
		data = request.json
	except BadRequest:
		return make_response("Malformed JSON body in request", 400)

	try:
		userManager.changeUserSettings(username, data)
		return jsonify(SUCCESS)
	except users.UnknownUser:
		return make_response("Unknown user: %s" % username, 404)
def groups_group(group, apiver=fg_config['fgapiver']):
    global fgapisrv_db

    logging.debug('groups_group(%s)/%s: %s' %
                  (request.method, group, request.values.to_dict()))
    api_support, state, message = check_api_ver(apiver)
    if not api_support:
        status = 400
        response = {"message": message}
    else:
        user_name = current_user.get_name()
        user_id = current_user.get_id()
        logging.debug("user_name: '%s'" % user_name)
        logging.debug("user_id: '%s'" % user_id)
        user = request.values.get('user', user_name)
        if request.method == 'GET':
            auth_state, auth_msg = \
                authorize_user(current_user, None, user, "groups_view")
            if auth_state is True:
                group_info = fgapisrv_db.group_retrieve(group)
                if group_info is not None:
                    status = 200
                    response = group_info
                else:
                    status = 404
                    response = {
                        'message':
                        'No groups found with name or id: %s' % group
                    }
            else:
                status = 402
                response = {
                    "message":
                    "Not authorized to perform this request:\n%s" % auth_msg
                }
        elif request.method == 'POST':
            status = 404
            response = {"message": "Not yet implemented"}
        else:
            status = 404
            response = {"message": "Unhandled method: '%s'" % request.method}
    logging.debug('message: %s' % response.get('message', 'success'))
    js = json.dumps(response, indent=fg_config['fgjson_indent'])
    resp = Response(js, status=status, mimetype='application/json')
    resp.headers['Content-type'] = 'application/json'
    return resp
예제 #22
0
def viewPattern(idPattern):

    if mongoClient["patterns"].count_documents({
            "therapist":
            current_user.get_id(),
            "id":
            idPattern
    }) == 0:
        flash("No existe la pauta especificada", "error")
        return redirect(url_for('index'))

    cursorPattern = mongoClient["patterns"].find_one({
        "therapist":
        current_user.get_id(),
        "id":
        idPattern
    })

    intensity1 = "Sí" if 1 in cursorPattern["intensities"] else "no"
    intensity2 = "Sí" if 2 in cursorPattern["intensities"] else "no"
    intensity3 = "Sí" if 3 in cursorPattern["intensities"] else "no"

    patternInfo = {
        "id": idPattern,
        "name": cursorPattern["name"],
        "description": cursorPattern["description"],
        "intensity1": intensity1,
        "intensity2": intensity2,
        "intensity3": intensity3
    }

    therapistLiteral = "{} {} {}".format(current_user.get_name(), current_user.get_surname1(), \
        current_user.get_surname2())

    form = PaginationForm(1)
    form2 = PaginationForm2(1)

    queryResultGroups = searchGroupsPattern(idPattern, 1)
    queryResultPatients = searchPatientsPattern(idPattern, 1)

    return render_template('viewPattern.html', therapistLiteral=therapistLiteral, patternInfo=patternInfo,
        rowsGroups=queryResultGroups["rows"], rowsPatients=queryResultPatients["rows"], form=form, form2=form2, \
        idPattern=idPattern, pagesGroups=queryResultGroups["numberPages"], \
        pagesPatients=queryResultPatients["numberPages"], numberRowsPatient=queryResultPatients["numberTotalRows"], \
        numberRowsGroup=queryResultGroups["numberTotalRows"])
def create_event():
    if current_user.is_authenticated:
        form = CreateEventsForm()
        if form.validate_on_submit():
            try:
                event = Events(author=current_user.get_name(),
                               begin=form.begin.data,
                               end=form.end.data,
                               topic=form.topic.data,
                               description=form.description.data)
                db.session.add(event)
                db.session.commit()
                flash("Registration success.", 'success')
                return redirect(url_for('events'))
            except:
                db.session.rollback()
                flash("Mistake in db.", 'danger')
        return render_template('createevent.html', form=form)
예제 #24
0
def getWsToken():
    publicKey = None
    userLogged = settings().get(["cloudSlicer", "loggedUser"])

    if userLogged:
        if current_user.is_anonymous or current_user.get_name() != userLogged:
            abort(401, "Unauthorized Access")

        user = userManager.findUser(userLogged)
        if user:
            publicKey = user.publicKey
        else:
            abort(403, 'Invalid Logged User')

    return Response(
        json.dumps({'ws_token': create_ws_token(publicKey)}),
        headers={'Access-Control-Allow-Origin': '*'}
        if settings().getBoolean(['api', 'allowCrossOrigin']) else None)
예제 #25
0
def changeSettingsForUser(username):
    if not userManager.enabled:
        return jsonify(SUCCESS)

    if current_user is None or current_user.is_anonymous() or (
            current_user.get_name() != username
            and not current_user.is_admin()):
        return make_response("Forbidden", 403)

    try:
        data = request.json
    except BadRequest:
        return make_response("Malformed JSON body in request", 400)

    try:
        userManager.changeUserSettings(username, data)
        return jsonify(SUCCESS)
    except users.UnknownUser:
        return make_response("Unknown user: %s" % username, 404)
예제 #26
0
def change_settings_for_user(username):
    if (current_user is None or current_user.is_anonymous
            or (current_user.get_name() != username
                and not current_user.has_permission(Permissions.ADMIN))):
        return make_response("Forbidden", 403)

    try:
        data = request.get_json()
    except BadRequest:
        return make_response("Malformed JSON body in request", 400)

    if data is None:
        return make_response("Malformed JSON body in request", 400)

    try:
        userManager.change_user_settings(username, data)
        return jsonify(SUCCESS)
    except users.UnknownUser:
        return make_response("Unknown user: %s" % username, 404)
예제 #27
0
파일: offer.py 프로젝트: RolfZurbrugg/lupon
def edit_offer(offer_id):
    logging.info('edit_offer with ID: ' + str(offer_id))
    offer = Workpackage.query.filter_by(id=offer_id).first()
    form = OfferEditForm(obj=offer)
    form.task.query = Task.query.filter_by(user_id=current_user.get_id())
    offers = Workpackage.get_all(current_user.get_id())
    tasks = offer.get_tasks()
    taskform = TaskForm()

    if form.validate_on_submit():
        logging.info('edit_offer, form validation successfull for ID: ' +
                     str(offer_id))
        form.populate_obj(offer)
        # taskform.populate_obj(task)

        if offer.assosiate_task is True:
            task = Task.query.get(form.task.data.id)
            offer.tasks.append(task)
            db.session.commit()

            return redirect(url_for('edit_offer', offer_id=offer_id))

    if taskform.validate_on_submit():
        task = Task(user_id=current_user.get_id(),
                    create_by=current_user.get_name())
        taskform.populate_obj(task)
        task.id = None

        logging.info('adding Task: ' + str(task.id) + str(task.name))
        if task.add_task is True:

            db.session.add(task)
            offer.tasks.append(task)
            db.session.commit()

            return redirect(url_for('edit_offer', offer_id=offer_id))

    return render_template('offer/edit_offer.html',
                           offers=offers,
                           form=form,
                           tasks=tasks,
                           taskform=taskform,
                           total=offer.total_value())
예제 #28
0
def viewGroup(idGroup):

    if mongoClient["groups"].count_documents({
            "therapist": current_user.get_id(),
            "id": idGroup
    }) == 0:
        flash("No existe el grupo de pautas especificado", "error")
        return redirect(url_for('index'))

    therapistLiteral = "{} {} {}".format(current_user.get_name(), current_user.get_surname1(), \
        current_user.get_surname2())
    therapist = current_user.get_id()

    form = PaginationForm(1)
    form2 = PaginationForm2(1)

    cursorGroup = mongoClient["groups"].find_one({
        "therapist":
        current_user.get_id(),
        "id":
        idGroup
    })

    groupInfo = {
        "id": idGroup,
        "name": cursorGroup["name"],
        "description": cursorGroup["description"]
    }

    queryResultPatients = searchPatientsGroup(idGroup, 1)
    queryResultPatterns = searchPatternsGroup(idGroup, 1)


    return render_template('viewGroup.html', therapistLiteral=therapistLiteral, groupInfo=groupInfo,
        form=form, form2=form2, idGroup=idGroup, rowsPatients=queryResultPatients["rows"], \
        pagesPatients=queryResultPatients["numberPages"], numberRowsPatient=queryResultPatients["numberTotalRows"], \
        rowsPatterns=queryResultPatterns["rows"], pagesPatterns=queryResultPatterns["numberPages"], \
        numberRowsPattern=queryResultPatterns["numberTotalRows"])

    return render_template('viewGroup.html',
                           rowPatterns=rowPatterns,
                           therapistLiteral=therapistLiteral)
예제 #29
0
def new_com(id):
    edu_daily_id = id
    if request.method == 'POST':
        rand = ''.join(
            random.choices(string.ascii_letters + string.digits, k=20))
        filename = '{}_{}.md'.format(current_user.get_name(), rand)
        os_path = os.path.join(app.root_path, 'edu_daily', filename)

        with open(os_path, mode='w') as f:
            f.write(request.form['text'])

        edudailycomment = EduDailyComment(edu_daily_id=id,
                                          commenter_id=current_user.get_id(),
                                          path=filename)
        db.session.add(edudailycomment)
        db.session.commit()

        flash('コメント投稿が完了しました。', 'success')
        return redirect(url_for('show_edu_daily', uid=edu_daily_id))

    return render_template('new_com.html', edu_daily_id=edu_daily_id)
예제 #30
0
def new():
    if request.method == 'POST':
        rand = ''.join(
            random.choices(string.ascii_letters + string.digits, k=20))
        filename = '{}_{}.md'.format(current_user.get_name(), rand)
        os_path = os.path.join(app.root_path, 'edu_daily', filename)
        ng_file_list = []

        if 'upload' in request.files:
            upload_files = request.files.getlist('upload')
            for upload_file in upload_files:
                if os.path.exists(
                        os.path.join(app.root_path, 'static',
                                     upload_file.filename)):
                    ng_file_list.append(upload_file.filename)

            if ng_file_list:
                ng_file = ', '.join(ng_file_list)
                flash('{} はすでに同名のファイルが存在します。'.format(ng_file), 'danger')
                return redirect(request.url)
            else:
                for upload_file in upload_files:
                    upload_file.save(
                        os.path.join(app.root_path, 'static',
                                     upload_file.filename))

        with open(os_path, mode='w') as f:
            f.write(request.form['text'])

        edudaily = EduDaily(user_id=current_user.get_id(),
                            title=request.form['title'],
                            path=filename)

        db.session.add(edudaily)
        db.session.commit()

        flash('新規投稿が完了しました。', 'success')
        return redirect(url_for('index'))

    return render_template('new.html')
예제 #31
0
파일: task.py 프로젝트: RolfZurbrugg/lupon
def task():

    # Prepoulate Form if task id is present in URL
    if request.args.get('task_id'):
        obj = Task.query.get(int(request.args['task_id']))
        taskform = TaskForm(obj=obj)

    else:
        taskform = TaskForm()

    # ToDo: only display where user_id = current_user
    tasks = Task.get_all(current_user.get_id())

    if taskform.validate_on_submit():
        logging.info('task from validated')
        task = Task()
        taskform.populate_obj(task)

        if task.update_task is True:
            tmp_task = Task.query.filter_by(id=task.id).first()
            taskform.populate_obj(tmp_task)
            tmp_task.modify_by = current_user.get_id()
            db.session.commit()
            flash("Task Updated! " + str(task.update_task), 'success')

        elif task.add_task is True:
            task.user_id = current_user.get_id()
            task.create_by = current_user.get_name()
            task.id = None
            db.session.add(task)
            db.session.commit()
            flash("Task created! " + str(task.add_task), 'success')

        elif task.del_task is True:
            tmp_task = Task.query.filter_by(id=task.id).first()
            tmp_task.delete()
            flash("Task deleted " + str(task.del_task), 'warning')

        return redirect(url_for('task'))
    return render_template("task.html", taskform=taskform, tasks=tasks)
예제 #32
0
def changepass():
    user_id = current_user.get_id()
    form = ChangepassForm()
    if form.validate_on_submit():
        user_name = current_user.get_name()
        hashOldPass = hashPassword(form.old_pass.data, user_name)
        hashNewPass = hashPassword(form.new_pass.data, user_name)
        kwargs = type('Dummy', (object, ), {
            "old_pass": hashOldPass,
            "new_pass": hashNewPass,
            "id": user_id
        })
        _db_process = DatabaseProcess(current_app.config['DB_CONNECTSTRING'])

        result = _db_process.user_change_pass(kwargs)
        if result > 0:
            return jsonify(result=1, msg='Success')
        else:
            msg = get_error_msg(result)
            return jsonify(result=-1, msg=msg)

    return render_template('user/changepass.html', form=form)
예제 #33
0
def viewPatterns():
    therapistLiteral = "{} {} {}".format(current_user.get_name(), current_user.get_surname1(), \
        current_user.get_surname2())
    form = SearchPatternsForm(current_user.get_id())
    form2 = PaginationForm(1)

    if form.validate_on_submit():
        form.submitDone.data = 1

        queryResult = searchPatterns(form, int(form.pageNumber.data))
        form2 = PaginationForm(queryResult["numberPages"])
        form2.pagination.data = form.pageNumber.data

        return render_template('viewPatterns.html', form=form, form2=form2, rowPatterns=queryResult["rows"], \
            therapistLiteral=therapistLiteral, numberTotalRows=queryResult["numberTotalRows"], \
            numberPages=queryResult["numberPages"])
    else:
        form.submitDone.data = 0
        return render_template('viewPatterns.html',
                               form=form,
                               form2=form2,
                               therapistLiteral=therapistLiteral)
예제 #34
0
def handleMessage(data):
    db_sess = db_session.create_session()

    try:
        if data['role'] == 'ban':  # Сообщения бана или разбана пользователя
            user = db_sess.query(User).filter(User.id == data['id']).first()
            if user.banned:
                user.banned = 0
            else:
                user.banned = 1
        elif data['role'] == 'del_mes':  # Сообщения удаления сообщений по id
            if db_sess.query(Message).filter(
                    Message.id == int(data['id'])).first():
                db_sess.query(Message).filter(
                    Message.id == int(data['id'])).delete()
            else:
                del_mes_inf = 'Сообщения с данным ID не найдено'
        db_sess.commit()

    except KeyError:  # Сообщения в чате
        if str(current_user).split(
                '>')[0] == '<User' and not current_user.banned:
            print(f"Message: {data}"
                  )  # Отображение полученного сообщения в консоли
            send(data, broadcast=True)
            message = Message()
            message.text = data['msg']

            try:  # Предотвращение ошибок в случае анонимного пользователя
                message.is_from_admin = current_user.get_role()
                message.user_name = current_user.get_name()

            except AttributeError:
                message.is_from_admin = False
                message.user_name = 'Anonymous'

            db_sess.add(message)
            db_sess.commit()
예제 #35
0
def registerGroup():
    therapistLiteral = "{} {} {}".format(current_user.get_name(), current_user.get_surname1(), \
        current_user.get_surname2())

    form = RegistrationGroupForm(current_user.get_id())

    if form.validate_on_submit():

        if mongoClient["groups"].count_documents({"name":
                                                  form.name.data}) == 0:
            idGroup = 1

            cursor = mongoClient["groups"].find({}).sort("id", -1).limit(1)
            #idGroup is incremental and univoque
            for cur in cursor:
                idGroup = cur["id"] + 1

            mongoClient["groups"].insert_one({'name': form.name.data, 'description': form.description.data, \
                'patients': list(map(int, form.patients.data)), 'patterns': list(map(int, form.patterns.data))})

            #Associate patients with patterns
            if len(form.patients.data) > 0 and len(form.patterns.data) > 0:
                for patient in list(map(int, form.patients.data)):
                    for pattern in list(map(int, form.patterns.data)):
                        mongoClient["patients"].update(
                            {"id": patient}, {"$push": {
                                "patterns": pattern
                            }})

            flash("Grupo creado correctamente", "info")
            return render_template('index.html')
        else:
            flash("Ya existe un grupo con ese nombre", "warning")

    return render_template('registerGroup.html',
                           form=form,
                           therapistLiteral=therapistLiteral)
예제 #36
0
파일: users.py 프로젝트: ByReaL/OctoPrint
def changePasswordForUser(username):
	if not userManager.enabled:
		return jsonify(SUCCESS)

	if current_user is not None and not current_user.is_anonymous() and (current_user.get_name() == username or current_user.is_admin()):
		if not "application/json" in request.headers["Content-Type"]:
			return make_response("Expected content-type JSON", 400)

		try:
			data = request.json
		except BadRequest:
			return make_response("Malformed JSON body in request", 400)

		if not "password" in data or not data["password"]:
			return make_response("password is missing from request", 400)

		try:
			userManager.changeUserPassword(username, data["password"])
		except users.UnknownUser:
			return make_response(("Unknown user: %s" % username, 404, []))

		return jsonify(SUCCESS)
	else:
		return make_response(("Forbidden", 403, []))
def roles(apiver=fg_config['fgapiver']):
    global fgapisrv_db

    logging.debug('groups(%s): %s' %
                  (request.method, request.values.to_dict()))
    api_support, state, message = check_api_ver(apiver)
    if not api_support:
        status = 400
        response = {"message": message}
    else:
        user_name = current_user.get_name()
        user_id = current_user.get_id()
        logging.debug("user_name: '%s'" % user_name)
        logging.debug("user_id: '%s'" % user_id)
        user = request.values.get('user', user_name)
        if request.method == 'GET':
            auth_state, auth_msg = \
                authorize_user(current_user, None, user, "roles_view")
            if auth_state is True:
                role_list = fgapisrv_db.roles_retrieve()
                status = 200
                response = {'roles': role_list}
            else:
                status = 402
                response = {
                    "message":
                    "Not authorized to perform this request:\n%s" % auth_msg
                }
        else:
            status = 400
            response = {"message": "Unhandled method: '%s'" % request.method}
    logging.debug('message: %s' % response.get('message', 'success'))
    js = json.dumps(response, indent=fg_config['fgjson_indent'])
    resp = Response(js, status=status, mimetype='application/json')
    resp.headers['Content-type'] = 'application/json'
    return resp
예제 #38
0
파일: index.py 프로젝트: NTUT-108-SE/SE-CMS
def change():
    form = json.loads(list(request.form.keys())[0])
    name = form.get('name', current_user.get_name())
    image = form.get('image', current_user.get_image())
    introduction = form.get('introduction', current_user.get_introduction())
    email = current_user.get_email()
    result = graphql.execute('''
    mutation {
        mutateUser(userData: {email: "%s", name: "%s",image: "%s", introduction: "%s"}){
            user {
                id
                email
                name
                image
                introduction
                role
            }
            ok
        }
    }
    ''' % (email, name, image, introduction)).data['mutateUser']
    ok = result['ok']
    user = result['user']
    return make_response(jsonify({'ok': ok, 'user': user}), 200 if ok else 400)