-
Notifications
You must be signed in to change notification settings - Fork 8
Commit v0.31
kwmccabe edited this page Apr 17, 2018
·
8 revisions
v0.31 - Convert user.active to user.user_role
- +3 -3 [M] mysql/scripts/seeddata.sql
- +2 -2 [M] mysql/scripts/tables.sql
- +1 -1 [M] web/app/api/authentication.py
- +17 -13 [M] web/app/decorators.py
- +2 -1 [M] web/app/user/forms.py
- +6 -8 [M] web/app/user/models.py
- +7 -3 [M] web/app/user/templates/user_edit.html
- +11 -14 [M] web/app/user/templates/user_list.html
- +15 -2 [M] web/app/user/templates/user_profile.html
- +17 -3 [M] web/app/user/templates/user_view.html
- +9 -6 [M] web/app/user/views.py
- +6 -0 [M] web/config.py
- Update test data for
user.user_role
column.
DELETE FROM `user`;
-INSERT INTO `user` (active,keyname,user_email) VALUES (True,"admin","[email protected]");
-INSERT INTO `user` (active,keyname,user_email) VALUES (False,"user","[email protected]");
-INSERT INTO `user` (active,keyname,user_email) VALUES (False,"user2","[email protected]");
+INSERT INTO `user` (user_role,keyname,user_email) VALUES (4,"admin","[email protected]");
+INSERT INTO `user` (user_role,keyname,user_email) VALUES (1,"user","[email protected]");
+INSERT INTO `user` (user_role,keyname,user_email) VALUES (0,"user2","[email protected]");
OPTIMIZE TABLE `user`;
- Replace
user.active
column withuser.user_role
. - Update index definitions.
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
- `active` tinyint(1) NOT NULL DEFAULT '1',
`keyname` varchar(63) NOT NULL,
+ `user_role` tinyint(1) NOT NULL DEFAULT '1',
`user_email` varchar(255) DEFAULT NULL,
...
UNIQUE KEY `user_keyname` (`keyname`),
- KEY `user_active` (`active`),
+ KEY `user_role` (`user_role`),
KEY `user_email` (`user_email`),
- Replace
user.active
withuser.user_role
.
@api.before_request
@auth.login_required
def before_request():
- if not g.current_user.active:
+ if not g.current_user.user_role:
return forbidden('Inactive Account')
- Add and update
user_role
withinsession
info for/list
pages.
if not session_key in session:
logging.debug('create session[%s]' % (session_key))
session[session_key] = { \
- 'itemcnt' : 0, \
- 'pagecnt' : 0, \
- 'status' : 'all', \
- 'sort' : 'id', \
- 'order' : 'asc', \
- 'offset' : 0, \
- 'limit' : 10, \
- 'page' : 1, \
+ 'itemcnt' : 0, \
+ 'pagecnt' : 0, \
+ 'status' : 'all', \
+ 'user_role' : -1, \
+ 'sort' : 'id', \
+ 'order' : 'asc', \
+ 'offset' : 0, \
+ 'limit' : 10, \
+ 'page' : 1, \
}
# get updates
S = session[session_key]
- status = request.values.get('status', S['status'])
- sort = request.values.get('sort', S['sort'])
- order = request.values.get('order', S['order'])
- limit = int(request.values.get('limit', S['limit']))
- page = int(request.values.get('page', S['page']))
+ status = request.values.get('status', S['status'])
+ user_role = request.values.get('user_role', S['user_role'])
+ sort = request.values.get('sort', S['sort'])
+ order = request.values.get('order', S['order'])
+ limit = int(request.values.get('limit', S['limit']))
+ page = int(request.values.get('page', S['page']))
if status in ['all','active','inactive']:
S['status'] = status
+ if user_role in ['-1','0','1','2','4']:
+ S['user_role'] = int(user_role)
if len(sort) > 0 and sort != S['sort']:
S['sort'] = sort
S['order'] = 'asc'
- Replace
active
checkbox withuser_role
dropdown menu. - Populate
user_role.choices
with static data.
class EditUserForm(FlaskForm):
id = HiddenField('id')
- active = BooleanField('Active')
+ user_role = SelectField('User Role')
keyname = StringField('Username', validators=[InputRequired(),Length(2,63),validate_username], filters=[filter_username])
...
def __init__(self, user, *args, **kwargs):
super(EditUserForm, self).__init__(*args, **kwargs)
+ self.user_role.choices = [('4','Administrator'),('2','Editor'),('1','User'),('0','Inactive')]
self.user = user
- Replace
active
boolean withuser_role
small integer. - Update
is_active()
function.
class UserModel(db.Model):
__tablename__ = 'user'
id = db.Column(db.BigInteger, autoincrement=True, primary_key=True)
- active = db.Column(db.Boolean, nullable=False, index=True, default=1)
+ user_role = db.Column(db.SmallInteger, nullable=False, index=True, default=1)
keyname = db.Column(db.String(63), nullable=False, index=True, unique=True, default='')
...
def is_active(self):
- return self.active
+ return (self.user_role > current_app.config['USER_ROLE_NONE'])
...
json_user = {
'url': url_for('api.get_user', id=self.id, _external=True),
'id' : self.id,
- 'active' : self.active,
+ 'user_role' : self.user_role,
'keyname' : self.keyname,
...
def __init__(self, **kwargs):
super(UserModel, self).__init__(**kwargs)
self.id = kwargs.get('id', None)
- self.active = kwargs.get('active', True)
+ self.user_role = kwargs.get('user_role', current_app.config['USER_ROLE_VIEW'])
self.keyname = kwargs.get('keyname', None)
...
def __repr__(self):
- return '<UserModel(id=%r,active=%r,keyname=%r,user_email=%r,cnt_login=%r,mod_login=%r,mod_create=%r,mod_update=%r)>' \
- % (self.id,self.active,self.keyname,self.user_email,self.cnt_login,self.mod_login,self.mod_create,self.mod_update)
+ return '<UserModel(id=%r,user_role=%r,keyname=%r,user_email=%r,cnt_login=%r,mod_login=%r,mod_create=%r,mod_update=%r)>' \
+ % (self.id,self.user_role,self.keyname,self.user_email,self.cnt_login,self.mod_login,self.mod_create,self.mod_update)
- Replace
active
form elements withuser_role
label and select menu. - Change panel color per
user_role
.
<!-- BLOCK: content -->
{% block content %}
-<div id="item_edit_panel" class="panel {% if form.active.data %}panel-info{% else %}panel-warning{% endif %}">
+<div id="item_edit_panel" class="panel {%
+ if form.user_role.data == '4' %}panel-success{%
+ elif form.user_role.data == '0' %}panel-danger{%
+ else %}panel-info{%
+ endif %}">
<div class="panel-heading">
...
<div class="form-group">
- {{ form.active.label }}
- {{ form.active(class_='form-control') }}
+ {{ form.user_role.label }}
+ {{ form.user_role(class_='form-control') }}
</div>
{{ form.submit(class_='btn btn-primary') }}
- Replace
All | Active | Inactive
links withRole
dropdown. - Replace
Create User
link withNew User...
button.
<tr>
<td>
- [ <a href="{{ url_for('.user_create') }}">Create User</a> ]
+ <a href="{{ url_for('.user_create') }}" class="btn btn-default btn-sm" role="button">New User...</a>
</td>
<td class="text-right">
- {% if session[opts_key]['status'] == 'active' %}
- [<a href="{{ url_for('.user_list') }}?status=all">All</a>]
- [Active]
- [<a href="{{ url_for('.user_list') }}?status=inactive">Inactive</a>]
- {% elif session[opts_key]['status'] == 'inactive' %}
- [<a href="{{ url_for('.user_list') }}?status=all">All</a>]
- [<a href="{{ url_for('.user_list') }}?status=active">Active</a>]
- [Inactive]
- {% else %}
- [All]
- [<a href="{{ url_for('.user_list') }}?status=active">Active</a>]
- [<a href="{{ url_for('.user_list') }}?status=inactive">Inactive</a>]
- {% endif %}
+ <div id="list-user-role" class="form-group-sm">
+ <label for="user_role" class="sr-only">Role</label>
+ <select id="user_role" name="user_role" class="form-control" onchange="window.location='{{ url_for('.user_list') }}?user_role='+this.value;">
+ <option value="-1"{% if session[opts_key]['user_role'] == -1 %} selected{% endif %}>All Users</option>
+ <option value="4"{% if session[opts_key]['user_role'] == 4 %} selected{% endif %}>Administrators</option>
+ <option value="2"{% if session[opts_key]['user_role'] == 2 %} selected{% endif %}>Editors</option>
+ <option value="1"{% if session[opts_key]['user_role'] == 1 %} selected{% endif %}>Users</option>
+ <option value="0"{% if session[opts_key]['user_role'] == 0 %} selected{% endif %}>Inactive</option>
+ </select>
+ </div>
</td>
</tr>
</table>
- Change panel color per
user_role
. - Translate
user_role
values to strings values:Administrator | Editor | User | Inactive
.
<!-- BLOCK: content -->
{% block content %}
-<div id="item_list_panel" class="panel {% if user.active %}panel-info{% else %}panel-warning{% endif %}">
+<div id="item_list_panel" class="panel {%
+ if user.user_role == 4 %}panel-success{%
+ else %}panel-info{%
+ endif %}">
<div class="panel-heading">
...
{% for col in cols %}
<tr>
<td>{{ col }}</td>
- <td>{{ user[col] }}</td>
+ <td>
+ {% if col == "user_role" %}{%
+ if user[col] == 4 %}Administrator{%
+ elif user[col] == 2 %}Editor{%
+ elif user[col] == 1 %}User{%
+ else %}Inactive{%
+ endif %}
+ {% else %}
+ {{ user[col] }}
+ {% endif %}
+ </td>
</tr>
{% endfor %}
- Change panel color per
user_role
. - Translate
user_role
values to strings values:Adminstrator | Editor | User | Inactive
.
<!-- BLOCK: content -->
{% block content %}
-<div id="item_list_panel" class="panel {% if user.active %}panel-info{% else %}panel-warning{% endif %}">
+<div id="item_list_panel" class="panel {%
+ if user.user_role == 4 %}panel-success{%
+ elif user.user_role == 0 %}panel-danger{%
+ else %}panel-info{%
+ endif %}">
<div class="panel-heading">
...
- <h3 class="condensed">User '{{ user.keyname }}'{% if not user.active %} - inactive{% endif %}</h3>
+ <h3 class="condensed">User '{{ user.keyname }}'</h3>
...
{% for col in cols %}
<tr>
<td>{{ col }}</td>
- <td>{{ user[col] }}</td>
+ <td>
+ {% if col == "user_role" %}{%
+ if user[col] == 4 %}Administrator{%
+ elif user[col] == 2 %}Editor{%
+ elif user[col] == 1 %}User{%
+ else %}Inactive{%
+ endif %}
+ {% else %}
+ {{ user[col] }}
+ {% endif %}
+ </td>
</tr>
{% endfor %}
- Update
active
andinactive
actions foruser_role
. - Update
rows.filter()
foruser_role
.
-from flask import abort, flash, redirect, render_template, request, session, url_for
+from flask import abort, current_app, flash, redirect, render_template, request, session, url_for
...
if action == 'active':
for id in user_ids:
user = UserModel.query.get_or_404(id)
- user.active = True
- db.session.add(user)
+ if user.user_role == current_app.config['USER_ROLE_NONE']:
+ user.user_role = current_app.config['USER_ROLE_VIEW']
+ db.session.add(user)
db.session.commit()
flash('Users Activated (id='+id_str+')')
if action == 'inactive':
for id in user_ids:
user = UserModel.query.get_or_404(id)
- user.active = False
+ user.user_role = current_app.config['USER_ROLE_NONE']
db.session.add(user)
db.session.commit()
flash('Users Deactivated (id='+id_str+')')
...
- if S['status'] in ['active', 'inactive']:
- rows = rows.filter(UserModel.active == (S['status'] == 'active'))
+ if S['user_role'] == current_app.config['USER_ROLE_NONE']:
+ rows = rows.filter(UserModel.user_role == S['user_role'])
+ elif S['user_role'] >= current_app.config['USER_ROLE_VIEW']:
+ rows = rows.filter(UserModel.user_role >= S['user_role'])
- Create constant
config
values foruser.user_role
.
+ # user.user_role
+ USER_ROLE_NONE = 0
+ USER_ROLE_VIEW = 1
+ USER_ROLE_EDIT = 2
+ USER_ROLE_ADMIN = 4
Commit-v0.30 | Commit-v0.31 | Commit-v0.32
- FlaskApp Tutorial
- Table of Contents
- About
- Application Setup
- Modules, Templates, and Layouts
- Database Items, Forms, and CRUD
- List Filter, Sort, and Paginate
- Users and Login
- Database Relationships
- API Module, HTTPAuth and JSON
- Refactoring User Roles and Item Status
- AJAX and Public Pages