Beispiel #1
0
    def put(self, setting_id):
        '''
        http://jsonapi.org/format/#crud-updating
        The PATCH request MUST include a single resource object as primary data. The resource object MUST contain
        type and id members.

        If a request does not include all of the attributes for a resource, the server MUST interpret the missing
        attributes as if they were included with their current values. The server MUST NOT interpret missing
        attributes as null values.

        If a server accepts an update but also changes the resource(s) in ways other than those specified by the
        request (for example, updating the updated-at attribute or a computed sha), it MUST return a 200 OK
        response. The response document MUST include a representation of the updated resource(s) as if a GET request was made to the request URL.

        A server MUST return 404 Not Found when processing a request to modify a resource that does not exist.
        '''
        setting = Setting.query.get_or_404(setting_id)
        raw_dict = request.get_json(force=True)

        try:
            # schema.validate(raw_dict)
            set_config(setting.application, setting.name, setting.value,
                       raw_dict['value'])
            setting_dict = raw_dict
            for key, value in setting_dict.items():

                setattr(setting, key, value)

            setting.update()

            response = jsonify({"code": 1})
            response.status_code = 200
            return response

        except ValidationError as err:
            resp = jsonify({"error": err.messages})
            resp.status_code = 401
            return resp

        except SQLAlchemyError as e:
            db.session.rollback()
            resp = jsonify({"error": str(e)})
            resp.status_code = 401
            return resp
Beispiel #2
0
def admin_config():
    user = Users.query.filter_by(username=session.get('username')).first_or_404()
    date = {
        'user':user,
        'blog_des':'test',
    }
    if request.method == "POST":
        blog_meta_key = set_config("blog_meta_key",request.form.get('key',None))
        #blog_icp = set_config("blog_icp",request.form.get('blog_icp',None))
        if check_value_none(request.form.get('blog_icp',None)):
            blog_icp = set_config("blog_icp",request.form.get('blog_icp'))
        if check_value_none(request.form.get('blog_name',None)):
            blog_name = set_config("blog_name", request.form.get('blog_name'))
        if check_value_none(request.form.get('blog_saying',None)):
            blog_saying = set_config("blog_saying", request.form.get('blog_saying'))
        if check_value_none(request.form.get('blog_des',None)):
            blog_desc = set_config("blog_desc", request.form.get('blog_des'))
        if check_value_none(request.form.get('key',None)):
            blog_meta_key = set_config("blog_meta_key", request.form.get('key'))
    return render_template('admin/config/config.html',**date)
Beispiel #3
0
def create_app(config="app.config"):
    app = Flask(__name__)
    with app.app_context():
        app.config.from_object(config)
        app.jinja_loader = BlogthemeLoader(os.path.join(
            app.root_path, app.template_folder),
                                           followlinks=True)

        from app.models import db, Users

        url = make_url(app.config['SQLALCHEMY_DATABASE_URI'])
        if url.drivername == 'postgres':
            url.drivername = 'postgresql'

        db.init_app(app)

        try:
            if not (url.drivername.startswith('sqlite')
                    or database_exists(url)):
                create_database(url)
            db.create_all()
        except OperationalError:
            db.create_all()
        else:
            db.create_all()

        app.db = db
        cache.init_app(app)
        app.cache = cache
        app.debug = False

        configure_uploads(app, photos)

        redis_store = FlaskRedis()
        redis_store.init_app(app)
        login_manager = LoginManager()
        login_manager.session_protection = 'strong'
        login_manager.login_view = 'auth.oauth'
        login_manager.init_app(app)

        toolbar = DebugToolbarExtension(app)
        #toolbar.DEBUG_TB_INTERCEPT_REDIRECTS = False
        md = Misaka()
        md.init_app(app)
        Analytics(app)
        app.config['ANALYTICS']['GAUGES']['SITE_ID'] = 'XXXXXXXXXXXXX'
        if not get_config('blog_theme'):
            set_config('blog_theme', 'blog')

        from app.views import views
        from app.utils import init_errors, init_utils, init_logs
        from app.post import blog
        from app.auth import auth
        from app.admin import admin
        from app.status import web
        #from app.api import
        init_errors(app)
        init_utils(app)
        init_logs(app)

        app.register_blueprint(views)
        app.register_blueprint(blog)
        app.register_blueprint(auth)
        app.register_blueprint(admin)
        app.register_blueprint(web)

        @login_manager.user_loader
        def load_user(user_id):
            try:
                return Users.query.get(int(user_id))
            except Users.DoesNotExist:
                return None

        return app
Beispiel #4
0
def setup():
    if not is_setup():
        if request.method == "POST":
            # Admin Account
            uid = request.form.get("uid")
            email = request.form.get("email")
            password = request.form.get("password")

            account = Users(uid=uid,
                            email=email,
                            password=hashlib.sha3_512(
                                password.encode()).hexdigest())

            # Commit admin account
            try:
                db.session.add(account)
            except Exception as e:
                flash(message=f"Admin  : {e._message}", category="error")
                db.session.rollback()
                return redirect(url_for("admin.setup"))

            # Domain Check
            wol_domain = request.form.get("wol_domain")
            domain_check = request.form.get("domain_check")

            set_config('wol_domain', wol_domain)
            set_config('domain_check', domain_check)

            # Page Settings
            title_tag = request.form.get("title_tag")
            main_title = request.form.get("main_title")

            set_config('title_tag', title_tag)
            set_config('main_title', main_title)

            # reCaptcha Settings
            recaptcha_site_key = request.form.get("recaptcha_site_key")
            recaptcha_secret_key = request.form.get("recaptcha_secret_key")
            recaptcha_status = request.form.get("recaptcha_status")

            set_config('recaptcha_site_key', recaptcha_site_key)
            set_config('recaptcha_secret_key', recaptcha_secret_key)
            set_config('recaptcha_status', recaptcha_status)

            # Setup completed
            set_config("setup", True)

            return redirect(url_for("admin.index"))

        # if setup is not completed
        return render_template(f"/admin/configs/setup.html")

    else:
        flash(message="Your flask had been set already.", category="info")
        return redirect(url_for("admin"))
Beispiel #5
0
def configs():
    if request.method == "POST":
        # Admin Account
        user_idx = request.form.get("idx", type=int)
        email = request.form.get("email", type=str)
        password = request.form.get("password", type=str)

        # Get Admin Account Information
        user_admin = Users.query.filter_by(idx=user_idx).one_or_none()

        if password != "":
            user_admin.password = sha3_512(password.encode()).hexdigest()

        user_admin.email = email

        # Commit into database
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            flash(message="Failed to edit config.", category="error")
            return redirect(url_for(".configs", user_idx=user_idx))
        else:
            db.session.commit()

        # Domain Check
        wol_domain = request.form.get("wol_domain")
        domain_check = request.form.get("domain_check")

        set_config('wol_domain', wol_domain)
        set_config('domain_check', domain_check)

        # Page Settings
        title_tag = request.form.get("title_tag")
        main_title = request.form.get("main_title")

        set_config('title_tag', title_tag)
        set_config('main_title', main_title)

        # reCaptcha Settings
        recaptcha_site_key = request.form.get("recaptcha_site_key")
        recaptcha_secret_key = request.form.get("recaptcha_secret_key")
        recaptcha_status = request.form.get("recaptcha_status")

        set_config('recaptcha_site_key', recaptcha_site_key)
        set_config('recaptcha_secret_key', recaptcha_secret_key)
        set_config('recaptcha_status', recaptcha_status)

        flash(message="Configs are changed successfully.", category="success")
        return redirect(url_for("admin.index"))

    user = Users.query.filter_by(idx=session.get("idx")).one_or_none()
    configs = db.session.query(Configs.key, Configs.value).all()

    return render_template(f"/admin/configs/configs.html",
                           configs=configs,
                           user=user)
Beispiel #6
0
def setup():
    if not is_setup():
        if not session.get('wslove'):
            session['wslove'] = sha512(os.urandom(10))
        if request.method == 'POST':
            blog_name = request.form['blog_name']
            blog_name = set_config('blog_name', blog_name)
            blog_info = request.form['blog_info']
            blog_info = set_config('blog_info', blog_info)
            username = request.form['blog_admin']
            password = request.form['password']
            email = request.form['email']
            anhao = request.form['reset_anhao']
            github = request.form['github']
            avatar_hash = hashlib.md5(email.encode('utf-8')).hexdigest()

            first_user = Users(username=username,
                               password=password,
                               email=email,
                               githubname=github,
                               anhao=anhao,
                               avatar_hash=avatar_hash)
            first_user.admin = True
            first_user.verified = True

            setup = set_config('setup', 'True')
            domain = set_config('domain', request.form['domain'])
            github_id = request.form['github_id']
            github_secret = request.form['github_secret']
            github_status = set_config('github_status', 'False')
            if github_id and github_secret:
                set_config('github_id', github_id)
                set_config('github_secret', github_secret)
                set_config('github_status', 'True')
            db.session.add(first_user)
            db.session.commit()
            db.session.close()
            logger = logging.getLogger('login')
            logger.info("[{0}] {1} reg ok".format(time.strftime("%m/%d/%Y %X"),
                                                  username.encode('utf-8')))

            app.setup = False
            with app.app_context():
                cache.clear()
            return redirect(url_for('views.static_html'))
        return render_template('install/setup.html',
                               wslove=session.get('wslove'))
    return redirect(url_for('views.static_html'))