8
8
891099838382014-12-09 04:42:11
Flask
89109983838, 2014-12-09 04:42:11

How to "fasten" simple authorization to flask-admin?

Good time of the day!
I am mastering flask-admin, at the moment for authorization I use a slightly corrected "for myself" package https://github.com/MrJoes/Flask-Admin/tree/master/...
But there was a need to do authorization without using a database, according means of storing the login and password in the application configuration file (because there will be only one user) ... so I'm racking my brains on how to fasten the simplest option following the example from flask-russian-docs.readthedocs.org/ru/latest/tutor. ..

tell me how to correctly implement the above simple example in is_accessible instead of login.current_user.is_authenticated()

class MyView(BaseView):
    def is_accessible(self):
        return login.current_user.is_authenticated()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
8
89109983838, 2014-12-10
@89109983838

problem solved _ solution at the very bottom of the post! ;)))
Tried to implement! by forwarding the authorization code through the database to the account from the config.
verification passes!
then, with a valid account, Traceback
jinja2.exceptions.UndefinedError
UndefinedError: 'form' is undefined

File "..........\app\templates\admin\index.html", line 17, in block "body"
........
17 {{ form.hidden_tag() if form.hidden_tag }} <----- swears at this
18 {% for f in form if f.type != 'CSRFTokenField' %}
19
.......
The main code for this situation:

# -*- coding: utf-8 -*-
import os
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from flask.ext.sqlalchemy import SQLAlchemy
from wtforms import form, fields, validators
from flask.ext import admin
from flask.ext.admin.contrib import sqla
from flask.ext.admin import helpers, expose



# Create Flask application
app = Flask(__name__)

# Create dummy secrey key so we can use sessions
app.config['CSRF_ENABLED'] = True
app.config['SECRET_KEY'] = '12345678290244'
#app.config['DEBUG'] = 'True'
app.config['USERNAME'] = 'admin'
app.config['PASSWORD'] = '1234'


# Create in-memory database (база для примера, для авторизации не используется)
app.config['DATABASE_FILE'] = 'db.sqlite'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + app.config['DATABASE_FILE']
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)


# Create user model (модель для примера, для авторизации не используется).
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(100))
    last_name = db.Column(db.String(100))
    login = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120))
    password = db.Column(db.String(64))
   # Отображение в административном интерфейсе
    def __unicode__(self):
        return self.username

# Define login and registration forms
class LoginForm(form.Form):
    login = fields.TextField(validators=[validators.required()])
    password = fields.PasswordField(validators=[validators.required()])

    def validate_login(self, field):
        
        if app.config['USERNAME'] != self.login.data:
            raise validators.ValidationError('Invalid user')

        if app.config['PASSWORD'] != self.password.data:
            raise validators.ValidationError('Invalid password')
    # присудствовало в оригинальном файле при хранение акаунта в базе данных         
    #def get_user(self):
    #    return db.session.query(User).filter_by(login=self.login.data).first()

def logged_in():
    # в сессии будет храниться информация о том, что пользователь вошёл
    return session.get('logged')
        
# Create customized model view class
class MyModelView(sqla.ModelView):

    def is_accessible(self):
        return logged_in()
    
    def _handle_view(self, name, **kwargs):
        if not logged_in():
            # делать редирект в некоторых случаях не стоит
            return redirect(url_for('.login_view'))


# Create customized index view class that handles login & registration
class MyAdminIndexView(admin.AdminIndexView):

    @expose('/')
    def index(self):
        if not logged_in():
            return redirect(url_for('.login_view'))
        return super(MyAdminIndexView, self).index()

    @expose('/login/', methods=('GET', 'POST'))
    def login_view(self):
        # handle user login
        form = LoginForm(request.form)
        if helpers.validate_form_on_submit(form):
            #использовалось в оригинальном фале при авторизацию через базу данных
            #user = form.get_user()
            #login.login_user(user)
            session.update({'logged':True}) # возможно задаю не правильно, подправте если не так!
            session.modified = True

        if logged_in():
            return redirect(url_for('.index'))
        link = '<p>Don\'t have an account? <a href="' + url_for('.register_view') + '">Click here to register.</a></p>'
        self._template_args['form'] = form
        self._template_args['link'] = link
        return super(MyAdminIndexView, self).index()
  
    @expose('/logout/')
    def logout_view(self):
        session.pop('logged', None)
        return redirect(url_for('.index'))


# views клиентской части  #############################################################
@app.route('/')
def index():
    return render_template('index.html')

########################################################################################  

# Create admin
admin = admin.Admin(app, 'Админка', index_view=MyAdminIndexView(), base_template='my_master.html')

# Add view
admin.add_view(MyModelView(User, db.session))

if __name__ == '__main__':
    # Start app
    app.run(debug=True)

I'll add:
until you change the value of app.config['SECRET_KEY'] = '12345678290244', you won't be able to enter the authorization page. constantly issues the above Traceback
###########################################
Instead of :
session.update({'logged':True})
session.modified = True
indicated:
session['logged'] = True Same
result. :(
You just need to file ...\app\templates\admin\index.html change:
to
The only thing I would like to know from knowledgeable people is this method safe???

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question