Commit e6c4fa01 authored by erreur401's avatar erreur401

Merge branch 'master' of gitlab.com:bemaker/eu.bemaker.flask

parents 8060b9a2 8484f566
#!/usr/bin/python
# -*- coding: <utf-8> -*-
from flask import Flask, render_template, redirect, flash, request
from flask import Flask, render_template, redirect, flash, request, url_for
from flask_flatpages import FlatPages
import markdown
from flask_mongoengine import *
from flask_security import Security, MongoEngineUserDatastore, UserMixin, RoleMixin, login_required, current_user
from flask_security import Security, MongoEngineUserDatastore, UserMixin, RoleMixin, login_required, current_user, user_registered
from flask_login import user_logged_in
from flask_mail import Mail
from flask_security.forms import RegisterForm, StringField
from wtforms.validators import DataRequired
......@@ -20,7 +22,7 @@ from bson import ObjectId
from flask_admin import Admin
from flask_admin.form import rules
from flask_admin.contrib.pymongo import ModelView, filters
from flask_admin.contrib.mongoengine import ModelView, filters
from flask_admin.model.fields import InlineFormField, InlineFieldList
from wtforms import form, fields
......@@ -42,7 +44,7 @@ pages = FlatPages(app)
app.config['SECRET_KEY'] = 'super-secret'
app.config['SECURITY_REGISTERABLE'] = True
app.config['SECURITY_RECOVERABLE'] = True
#app.config['SECURITY_TRACKABLE'] = True
# app.config['SECURITY_TRACKABLE'] = True
app.config['SECURITY_PASSWORD_HASH'] = 'bcrypt'
app.config['SECURITY_PASSWORD_SALT'] = '$2a$16$PnnIgfMwkOjGX4SkHqSOPO'
......@@ -63,18 +65,47 @@ app.config['MONGODB_PORT'] = 27017
# Create database connection object
db = MongoEngine(app)
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
bdd = client.mydatabase
bddusers = bdd.users
class Role(db.Document, RoleMixin):
name = db.StringField(max_length=80, unique=True)
description = db.StringField(max_length=255)
def __unicode__(self):
return self.name
# badges = {
# 'impression3d': '0',
# 'cnc': '0',
# 'laser': '0',
# 'maker': '0',
# 'electronique': '0'
# }
badges = {
"cnc": {
"lvl": "0"
},
"laser": {
"lvl": "0"
},
"impression3d": {
"lvl": "0"
},
"maker": {
"lvl": "0"
},
"electronique": {
"lvl": "0"
}
}
# class Badges(db.Document):
2
# name = db.StringField(unique=True)
# value = db.StringField()
#
# def __unicode__(self):
# return self.name
class User(db.Document, UserMixin):
active = db.BooleanField(default=True)
first_name = db.StringField(max_length=255)
......@@ -82,23 +113,55 @@ class User(db.Document, UserMixin):
email = db.StringField(max_length=255)
password = db.StringField(max_length=255)
confirmed_at = db.DateTimeField()
# badges = db.DictField(default=[('cnc', 0),('laser', 0),('electronique', 0),('cad', 0),('impression3d', 0), ('maker', 0) ] )
roles = db.ListField( db.ReferenceField(Role), default=[])
badges = db.ListField(default=[{'name':'cnc', 'lvl': 0},{'name':'laser', 'lvl': 0},{'name':'electronique', 'lvl': 0},{'name':'cad', 'lvl': 0},{'name':'impression3d', 'lvl': 0},{'name':'maker', 'lvl': 0}])
dashboard_view_count = db.StringField(max_length=3)
badges = db.DictField(default = badges)
roles = db.ListField(db.ReferenceField(Role))
# badges = db.ListField( db.ReferenceField(Badges))
# dashboard_view_count = db.StringField(max_length=3, default=[0])
meta = {'strict': False}
class ExtendedRegisterForm(RegisterForm):
first_name = StringField('First Name', validators=[DataRequired()])
last_name = StringField('Last Name', validators=[DataRequired()])
def __unicode__(self):
return self.name
# Setup Flask-Security
user_datastore = MongoEngineUserDatastore(db, User, Role)
#security = Security(app, user_datastore)
security = Security(app, user_datastore, register_form=ExtendedRegisterForm)
@app.before_first_request
def before_first_request():
user_datastore.find_or_create_role(name='admin', description='Administrator, adminstration view, sees these backend views ')
user_datastore.find_or_create_role(name='user', description='default for all users, status for students, teachers, anybody who uses the register form')
@app.before_first_request
def create_user():
# check that we have at least one user that has admin role, if existing, continue
if not user_datastore.get_user('admin@bemaker.eu'):
print('creating default admin user because unexisting')
user_datastore.create_user(email='admin@bemaker.eu', password='xedmewv)Faf8#yhQ', roles=['admin'])
@user_registered.connect_via(app)
def on_user_registered(sender, user, confirm_token):
default_role = user_datastore.find_role("user")
user_datastore.add_role_to_user(user, default_role)
# user_datastore.add_badges_to_user(user, default_badges)
# @user_logged_in.connect_via(app)
# def attribute_empty_badges(sender, user):
# print("user logged in")
# print(user)
# if badg:
# print("user already has badges")
# else:
# print("no badges found, adding default array of badges with values at 0")
# default_badges = { "cnc" : { "lvl" : "0"}, "laser" : {"lvl" : "0"}, "impression3d" : {"lvl" : "0"} }
# User.objects(id = user).update(set__badges = default_badges, upsert=True)
@app.route("/")
@app.route("/index")
def index():
......@@ -186,9 +249,9 @@ def check_quiz(id):
print('award badge ' + badge)
#bdd.user.update({"_id": ObjectId(user), "badges.name": badge}, {"$set": {"badges.$.lvl": 1}}, multi=True)
# .objects(id=post.id).update(title='Example Post')
update_Query = str('set__badges__' + badge + '__lvl = 10')
update_Query = str('"set__badges__' + badge + '__lvl = 1", upsert = True')
print(update_Query)
User.objects(id = C_user).update(update_Query ,True)#set__badges__laser__lvl = 22 , upsert=True) #{'badge.lvl' : 1 }, upsert = True )
User.objects(id = C_user).update(update_Query)#set__badges__laser__lvl = 22 , upsert=True) #{'badge.lvl' : 1 }, upsert = True )
# print({ "badges.name": badge,"_id": ObjectId(user)}, {"$set": {"badges.$.lvl": 2}})
#({'badges.name': 'electronique', '_id': ObjectId('5b3f847e5087266741cf1fef')}, {'$set': {'badges.$.lvl': 1}})
......@@ -223,31 +286,53 @@ def not_found(error):
def dashboard():
C_user = current_user.get_id()
print('user: ' + C_user)
db_user = User.objects.get(id=C_user).update(inc__dashboard_view_count=1, upsert=True)
#db_user = User.objects.get(id=C_user).update(inc__dashboard_view_count=1, upsert=True)
message = 'Welcome to your dashboard ' + current_user.get_id()
flash(message , "alert-info")
return render_template('dashboard.html', user=C_user)
def inaccessible_callback(self, name, **kwargs):
# redirect to login page if user doesn't have access
return redirect(url_for('security.login', next=request.url))
# class UserForm(form.Form):
# name = fields.StringField('Name')
# email = fields.StringField('Email')
# password = fields.StringField('Password')
class UserView(ModelView):
column_list = ('first_name', 'email' , 'badges')
def is_accessible(self):
return current_user.has_role('admin')
def inaccessible_callback(self, name, **kwargs):
# redirect to login page if user doesn't have access
return redirect(url_for('security.login', next=request.url))
column_list = ('first_name', 'email' , 'roles')
column_sortable_list = ('email')
form = ExtendedRegisterForm
# form_ajax_refs = {
# 'badges': {
# 'badge': ('lvl',)
# }
# }
form_ajax_refs = {
'roles': {
'fields': ['name']
}
}
class RoleView(ModelView):
def is_accessible(self):
return current_user.has_role('admin')
def inaccessible_callback(self, name, **kwargs):
# redirect to login page if user doesn't have access
return redirect(url_for('security.login', next=request.url))
# APP RUN
if __name__ == '__main__':
admin = Admin(app, name='bemaker', template_mode='bootstrap3')#,base_template='microblog_master.html')
admin.add_view(UserView(bdd.user, 'User'))
admin.add_view(UserView(User))
admin.add_view(RoleView(Role))
# admin.add_view(ModelView(Badges))
app.run(host='0.0.0.0', debug=True)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment