Skip to content

Commit

Permalink
tests login logout register done, add of TODO file, decorators for pe…
Browse files Browse the repository at this point in the history
…rmissions and flask admin. Admin panel set with admin permissions, home button removed from admin panel, flask-admin bootstrap4 personnalized has been installed: git+git://github.com/ryanbeymer/flask-admin.git.
  • Loading branch information
pdamoune committed Aug 20, 2019
1 parent cfceccf commit df0f3cb
Show file tree
Hide file tree
Showing 18 changed files with 402 additions and 192 deletions.
11 changes: 11 additions & 0 deletions TODO
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
*v0.5

[V] Register
[V] Login
[V] Logout
[X] Permissions anonymous/user/admin

[V] Test Register
[V] Test Login
[V] Test Logout
[X] Test Permissions anonymous/user/admin
4 changes: 3 additions & 1 deletion app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@


from config import config

from .admin import Admin, SecuredHomeView

bootstrap = Bootstrap()
db = SQLAlchemy()
toolbar = DebugToolbarExtension()
admin = Admin(template_mode='bootstrap4', base_template='/admin/new_master.html')

login_manager = LoginManager()
login_manager.login_view = 'auth.login'
Expand All @@ -25,6 +26,7 @@ def create_app(config_name):
toolbar.init_app(app)
db.init_app(app)
login_manager.init_app(app)
admin.init_app(app, index_view=SecuredHomeView())

from app import blueprints
blueprints.init_app(app)
Expand Down
30 changes: 26 additions & 4 deletions app/admin.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,34 @@
from flask import redirect, url_for, request
from flask_admin import Admin as FlaskAdmin, AdminIndexView, expose, BaseView
from flask_admin.contrib.sqla import ModelView as FlaskModelView
import flask_login as login

from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView


class _Admin(Admin):
class Admin(FlaskAdmin):
def add_model_view(self, model, db):
self.add_view(ModelView(model, db.session))

def add_model_views(self, models, db):
for model in models:
self.add_model_view(model, db)

class ModelView(FlaskModelView):
def is_accessible(self):
return login.current_user.is_administrator()

def inaccessible_callback(self, name, **kwargs):
return redirect(url_for('auth.login', next=request.url_rule))


class SecuredHomeView(AdminIndexView):
@expose('/')
def index(self):
if self.admin._menu[0].name == 'Home':
del self.admin._menu[0]
return self.render('/admin/index.html')

def is_accessible(self):
return login.current_user.is_administrator()

def inaccessible_callback(self, name, **kwargs):
return redirect(url_for('auth.login', next=request.url_rule))
6 changes: 2 additions & 4 deletions app/blueprints.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
from .models import User, Role
from .main import main as main_blueprint
from .auth import auth as auth_blueprint
from .admin import _Admin
from .models import User, Role
from app import db


def init_app(app):
app.register_blueprint(main_blueprint)
app.register_blueprint(auth_blueprint, url_prefix='/auth')

admin = _Admin()
admin.init_app(app)
from app import admin
admin.add_model_views([
User, Role
], db)
259 changes: 152 additions & 107 deletions app/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,130 +10,175 @@ def register(app):
"""
@app.cli.command()
def dropdb():
"""
Delete all database data.
"""
db.drop_all()
db.session.commit()
print('All data has been deleted.')
drop_db()

@app.cli.command()
def createdb():
"""
Creates a local database. You probably should not use this on
production.
"""
db.create_all()
print('Database created')
create_db()

@app.cli.command()
def recreatedb():
"""
Delete all database data and create a new one
"""
db.drop_all()
db.create_all()
db.session.commit()
print('Deleted all database data and created a new one')
recreate_db()

@app.cli.command()
def insertroles():
"""
Creates Roles in databases
"""
from .models import Role
Role.insert_roles()
print('Roles inserted')
def createroles():
create_roles()

@app.cli.command()
def createadmin():
"""
Create admin account
"""
u = User(
username=app.config['ADMIN_EMAIL'],
email=app.config['ADMIN_EMAIL'],
password=app.config['ADMIN_PASSWORD'],
role_id=3)
db.session.add(u)
db.session.commit()
print("[Created] " + str(u))
create_admin(app)

@app.cli.command()
def createtestusers():
"""Creates users."""
perm = {'user': 1, 'moderator': 2, 'administrator': 3}
users = [
[
'test_classic',
'[email protected]',
'test',
perm['user']],
[
'test_samepassword1',
'[email protected]',
'samepassword',
perm['user']],
[
'test_samepassword2',
'[email protected]',
'samepassword',
perm['user']],
[
'test_moderator',
'[email protected]',
'test',
perm['moderator']],
[
'test_administrator',
'[email protected]',
'test',
perm['administrator']],
]
for user in users:
if User.query.filter_by(username=user[0]).first():
print('Users already created')
break
u = User(
username=user[0],
email=user[1],
password=user[2],
role_id=user[3])
db.session.add(u)
print("[Created] " + str(user))
db.session.commit()
create_test_users()

@app.cli.command()
def createfakeusers():
"""
Creates fake users and posts. You probably should not use this on
production.
"""
from faker import Faker
fake = Faker()
i = 0
while i < 10:
u = User(email=fake.email(),
username=fake.user_name(),
password='password')
db.session.add(u)
i += 1
db.session.commit()
create_fake_users()

@app.cli.command()
def clean():
"""
Remove *.pyc and *.pyo files recursively starting at current directory
"""
for dirpath, dirnames, filenames in os.walk('.'):
for filename in filenames:
if filename.endswith('.pyc') or filename.endswith('.pyo'):
full_pathname = os.path.join(dirpath, filename)
print('Removing %s' % full_pathname)
os.remove(full_pathname)
if '__pycache__' in dirpath and not os.listdir(dirpath):
os.rmdir(dirpath)
if dirpath == "./tmp":
print('Removing %s' % dirpath)
shutil.rmtree(dirpath)
print('tmp, *.pyc and *.pyo files deleted')
clean_files()

@app.cli.command()
def createall():
create_all(app)


def drop_db():
"""
Delete all database data.
"""
db.drop_all()
db.session.commit()
print('All data has been deleted.')


def create_db():
"""
Creates a local database. You probably should not use this on
production.
"""
db.create_all()
print('Database created')


def recreate_db():
"""
Delete all database data and create a new one
"""
db.drop_all()
db.create_all()
db.session.commit()
print('Deleted all database data and created a new one')


def create_roles():
"""
Creates Roles in databases
"""
from .models import Role

Role.insert_roles()
print('Roles inserted')


def create_admin(app):
"""
Create admin account
"""
u = User(
username=app.config['ADMIN_EMAIL'],
email=app.config['ADMIN_EMAIL'],
password=app.config['ADMIN_PASSWORD'],
role_id=3)
db.session.add(u)
db.session.commit()
print("[Created] " + str(u))


def create_test_users():
"""Creates users."""
perm = {'user': 1, 'moderator': 2, 'administrator': 3}
users = [
[
'test_classic',
'[email protected]',
'test',
perm['user']],
[
'test_samepassword1',
'[email protected]',
'samepassword',
perm['user']],
[
'test_samepassword2',
'[email protected]',
'samepassword',
perm['user']],
[
'test_moderator',
'[email protected]',
'test',
perm['moderator']],
[
'test_administrator',
'[email protected]',
'test',
perm['administrator']],
]
for user in users:
if User.query.filter_by(username=user[0]).first():
print('Users already created')
break
u = User(
username=user[0],
email=user[1],
password=user[2],
role_id=user[3])
db.session.add(u)
print("[Created] " + str(user))
db.session.commit()

def create_fake_users():
"""
Creates fake users and posts. You probably should not use this on
production.
"""
from faker import Faker
fake = Faker()
i = 0
while i < 10:
u = User(email=fake.email(),
username=fake.user_name(),
password='password')
db.session.add(u)
i += 1
db.session.commit()
print("Fake users created")


def clean_files():
"""
Remove *.pyc and *.pyo files recursively starting at current directory
"""
for dirpath, dirnames, filenames in os.walk('.'):
for filename in filenames:
if filename.endswith('.pyc') or filename.endswith('.pyo'):
full_pathname = os.path.join(dirpath, filename)
print('Removing %s' % full_pathname)
os.remove(full_pathname)
if '__pycache__' in dirpath and not os.listdir(dirpath):
os.rmdir(dirpath)
if dirpath == "./tmp":
print('Removing %s' % dirpath)
shutil.rmtree(dirpath)
print('tmp, *.pyc and *.pyo files deleted')


def create_all(app):
recreate_db()
create_roles()
create_admin(app)
create_test_users()
create_fake_users()
19 changes: 19 additions & 0 deletions app/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# from functools import wraps
# from flask import abort
# from flask_login import current_user
# from .models import Permission
#
#
# def permission_required(permission):
# def decorator(f):
# @wraps(f)
# def decorated_function(*args, **kwargs):
# if not current_user.can(permission):
# abort(403)
# return f(*args, **kwargs)
# return decorated_function
# return decorator
#
#
# def admin_required(f):
# return permission_required(Permission.ADMIN)(f)
1 change: 1 addition & 0 deletions app/templates/admin/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{% extends 'admin/master.html' %}
Loading

0 comments on commit df0f3cb

Please sign in to comment.