def register(): lst = ls_path('home') if current_user.is_authenticated: return redirect('/index') form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() u = User.query.filter_by(email=form.email.data).first().id r = Role.query.filter_by(type='student').first().id a = UserRoles(user_id=u, role_id=r) db.session.add(a) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect('/login') return render_template('register.html', title='Register', files=lst, Course=Course, User=User, Role=Role, UserRoles=UserRoles, form=form, get_admin=get_admin, get_tutor=get_tutor, get_student=get_student)
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): user = User(first_name=form.first_name.data, last_name=form.last_name.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() if len(User.query.all()) == 1: roles = UserRoles(user_id=User.query.filter_by(email=user.email).first().id, role_id=7) else: roles = UserRoles(user_id=User.query.filter_by(email=user.email).first().id, role_id=5) db.session.add(roles) db.session.commit() flash('Your account has been successfully created!') return redirect(url_for('login')) return render_template('login.html', title="Register", form=form)
def toggle_admin_user(username): user = User.query.filter_by(username=username).first_or_404() admin_role = Role.query.filter_by(name='admin').first_or_404() if not user.is_admin: action = UserRoles(user_id=user.id, role_id=admin_role.id) db.session.add(action) else: action = UserRoles.query.filter_by(user_id=user.id).filter_by(role_id=admin_role.id).first() db.session.delete(action) db.session.commit() return jsonify({'success': True})
def registerNewUser(username, password, email, role): status = {} student_exist = User.query.filter_by(email=email).first() if not student_exist: u = User(username=username, email=email) u.set_password(password) db.session.add(u) db.session.commit() r = Role.query.filter_by(name=role).first().id uadded = User.query.filter_by(email=email).first().id a = UserRoles(user_id=uadded, role_id=r) db.session.add(a) db.session.commit() status[username] = "created" status["role"] = role else: status[username] = "alread exists" return status
def add_admin_user(self, username, password, email): with self.app.test_request_context(): role_existance = Role.query.filter_by(name='admin').first() if not role_existance: self.add_role('admin') with self.app.test_request_context(): role_existance = Role.query.filter_by(name='admin').first() user = User(username=username, password=password, email=email, image_file='') self._add_to_db(user) with self.app.test_request_context(): user = User.query.filter_by(username=username).first() userRole = UserRoles(user_id=user.id, role_id=role_existance.id) self._add_to_db(userRole)
def admin_add(): # check if user is actually admin id = current_user.id this_user = UserRoles.query.filter_by(user_id=id).first() if this_user.role_id != 7: return redirect(url_for('profile')) # create forms form = AddNewUserForm() if form.validate_on_submit(): user = User(first_name=form.first_name.data, last_name=form.last_name.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() roles = UserRoles(user_id=User.query.filter_by(email=user.email).first().id, role_id=int(form.role.data)) db.session.add(roles) db.session.commit() flash('New user successfully created!') return redirect(url_for('admin')) return render_template('admin_add.html', form=form)
def adduser(): if request.method == 'GET': roles = Role.query.filter().order_by(Role.id).all() return render_template('admin/adduser.html', name=current_user.name, roles=roles) else: email = request.form.get('email') name = request.form.get('name') password = request.form.get('password') #role = request.form.get('role') roleid = request.form.get('role') if not name or not email or not password: flash('Please fill in all the fields and try again.') return redirect(url_for('admin.adduser')) else: user = User.query.filter_by(email=email).first( ) # if this returns a user, then the email already exists in database if user: # if a user is found, we want to redirect back to signup page so user can try again flash('Email address already exists') return redirect(url_for('admin.adduser')) # create a new user with the form data. Hash the password so the plaintext version isn't saved. new_user = User(email=email, name=name, password=generate_password_hash(password, method='sha256')) #new_user.roles.append(Role(rolename=role)) # dokumentáció szerint igy kéne működnie, de a meglévő szerepkör nevét bővítené és ez hiba # add the new user to the database db.session.add(new_user) db.session.commit() #ez egy menekülö út userrole = UserRoles(user_id=new_user.id, role_id=roleid) db.session.add(userrole) db.session.commit() return redirect(url_for('main.index'))
def ModifyUser(user_id): if current_user.role == UserRoles.admin: user = User.query.filter(User.id == user_id).first() if user: form = UserForm() departments = Department.query.all() departments_list = [(d.id, d.name) for d in departments] departments_list.append((0, 'Без отдела')) form.department.choices = departments_list if form.validate_on_submit(): user.name = form.full_name.data.strip() user.role = UserRoles(form.role.data) if form.department.data != 0: user.dep_id = form.department.data else: user.dep_id = None db.session.commit() flash('Пользователь успешно обновлён.') else: for error in form.full_name.errors + form.role.errors + form.department.errors: flash(error) else: flash('Такого пользователя не существует.') elif user_id == current_user.id: form = UserForm() form.department.choices = [(current_user.dep_id, current_user.department.name)] if form.validate_on_submit(): current_user.name = form.full_name.data.strip() db.session.commit() flash('Пользователь успешно обновлён.') else: for error in form.full_name.errors + form.role.errors + form.department.errors: flash(error) else: return render_template('errors/403.html'), 403 return redirect(url_for('main.ShowUsers'))
def add_user(): ls_adm = ls_path('admin') lst = ls_path('home') if not get_admin(current_user.email) == True: return render_template('errors_page/unauthorized.html', title='unauthorized', files=lst, Course=Course, url=url, get_admin=get_admin, get_tutor=get_tutor, get_student=get_student) form = RegistrationForm() if form.validate_on_submit(): user = User(username=form.username.data, email=form.email.data) user.set_password(form.password.data) db.session.add(user) db.session.commit() u = User.query.filter_by(email=form.email.data).first().id r = Role.query.filter_by(type='tutor').first().id a = UserRoles(user_id=u, role_id=r) db.session.add(a) db.session.commit() flash('Congratulations, registered a new user!') return redirect('/add_user') return render_template('add_user.html', title='add a new user', files=lst, fbase=ls_adm, Course=Course, User=User, Role=Role, UserRoles=UserRoles, form=form, get_admin=get_admin, get_tutor=get_tutor, get_student=get_student)
from app.models import User, UserRoles, Role from werkzeug.security import generate_password_hash, check_password_hash admin = User(username="******", email="*****@*****.**", password_hash=generate_password_hash("admin")) db.session.add(admin) db.session.commit() user = User(username="******", email="*****@*****.**", password_hash=generate_password_hash("user")) db.session.add(user) db.session.commit() admin_role = Role(name='Admin') db.session.add(admin_role) db.session.commit() user_role = Role(name='User') db.session.add(user_role) db.session.commit() admin_user_role = UserRoles(user_id=1, role_id=1) db.session.add(admin_user_role) db.session.commit() user_user_role = UserRoles(user_id=2, role_id=2) db.session.add(admin_user_role) db.session.commit()
from app import db from app.models import User, Role, UserRoles admin = User(username='******', email='*****@*****.**', password='******') admin_role = Role(name='admin') user_role = UserRoles(user_id=admin.id, role_id=admin_role.id) db.session.add(admin) db.session.add(admin_role) db.session.commit()
def ShowSettings(): locations = Location.query.filter(Location.ecwid_id == current_user.ecwid_id).order_by(Location.name).all() categories = CacheCategories.query.filter(CacheCategories.ecwid_id == current_user.ecwid_id).all() if current_user.role == UserRoles.admin: if current_user.hub is None: current_user.hub = Ecwid() db.session.commit() ecwid_form = EcwidSettingsForm() role_form = UserRolesForm() api_data = ApiData.query.filter_by(ecwid_id = current_user.ecwid_id).first() if api_data is None: notify1C_form = Notify1CSettingsForm() else: notify1C_form = Notify1CSettingsForm(enable = api_data.notify_1C, email = api_data.email_1C) users = User.query.filter(or_(User.role == UserRoles.default, User.ecwid_id == current_user.ecwid_id)).order_by(User.name, User.email).all() if ecwid_form.submit1.data and ecwid_form.validate_on_submit(): current_user.hub.partners_key = ecwid_form.partners_key.data current_user.hub.client_id = ecwid_form.client_id.data current_user.hub.client_secret = ecwid_form.client_secret.data current_user.hub.store_id = ecwid_form.store_id.data try: current_user.hub.GetStoreToken() profile = current_user.hub.GetStoreProfile() db.session.commit() flash('Данные успешно сохранены.') except (SQLAlchemyError, EcwidAPIException): db.session.rollback() flash('Ошибка API или магазин уже используется.') flash('Возможно неверные настройки?') elif role_form.submit2.data and role_form.validate_on_submit(): user = User.query.filter(User.id == role_form.user_id.data).first() if user is not None: user.ecwid_id = current_user.ecwid_id user.role = UserRoles(role_form.role.data) if user.role in [UserRoles.validator,UserRoles.approver] and role_form.about_user.user_data.data is not None: user.data = ValidateUserData(role_form.about_user.user_data.data) else: user.data = None if role_form.about_user.phone.data is not None: user.phone = role_form.about_user.phone.data.strip() else: user.phone = '' if role_form.about_user.position.data is not None: user.position = role_form.about_user.position.data.strip() else: user.position = '' user.place = role_form.about_user.place.data user.email_new = role_form.about_user.email_new.data user.email_modified = role_form.about_user.email_modified.data user.email_disapproved = role_form.about_user.email_disapproved.data user.email_approved = role_form.about_user.email_approved.data user.name = role_form.about_user.full_name.data.strip() db.session.commit() flash('Данные успешно сохранены.') else: flash('Пользователь не найден.') location_form = AddRemoveLocationForm() errors_list = role_form.user_id.errors + role_form.role.errors + role_form.about_user.full_name.errors + role_form.about_user.phone.errors + role_form.about_user.user_data.errors for error in errors_list: flash(error) return render_template('settings.html', ecwid_form = ecwid_form, role_form = role_form, location_form = location_form,\ users = users, locations=locations, categories=categories, notify1C_form = notify1C_form) else: user_form = UserSettingsForm() if user_form.validate_on_submit(): if user_form.about_user.phone.data is not None: current_user.phone = user_form.about_user.phone.data.strip() else: current_user.phone = '' if user_form.about_user.position.data is not None: current_user.position = user_form.about_user.position.data.strip() else: current_user.position = '' current_user.place = user_form.about_user.place.data current_user.email_new = user_form.about_user.email_new.data current_user.email_modified = user_form.about_user.email_modified.data current_user.email_disapproved = user_form.about_user.email_disapproved.data current_user.email_approved = user_form.about_user.email_approved.data current_user.name = user_form.about_user.full_name.data.strip() if current_user.role in [UserRoles.validator,UserRoles.approver] and user_form.about_user.user_data.data is not None: current_user.data = ValidateUserData(user_form.about_user.user_data.data) db.session.commit() flash('Данные успешно сохранены.') else: errors_list = user_form.about_user.full_name.errors + user_form.about_user.phone.errors + user_form.about_user.user_data.errors for error in errors_list: flash(error) return render_template('settings.html', user_form=user_form, locations=locations, categories=categories)
def user_role(): UserForm = UserRoleForm() UserFilterForm = UserRoleFilterForm() page = request.args.get('page', 1, type=int) user_filter_id = session.get('user_filter_id') role_filter_id = session.get('role_filter_id') user_list = UserRoles.query if user_filter_id is not None: user_list = user_list.filter(UserRoles.user == user_filter_id) if role_filter_id is not None: user_list = user_list.filter(UserRoles.role == role_filter_id) pagination = user_list.paginate(page, 5, error_out=False) userroles = pagination.items if UserForm.submit_ok.data and UserForm.validate_on_submit(): # Обработка удаления и добавления данных user = Users.query.get(UserForm.user.data) role = Roles.query.get(UserForm.role.data) user_role = UserRoles.query.filter_by(user=user.id, role=role.id).first() if user_role is not None and UserForm.action.data == 1: flash('Данному пользователю роль уже назначена', category='warning') elif user_role is None and UserForm.action.data == 1: user_role = UserRoles(user=user.id, role=role.id) db.session.add(user_role) db.session.commit() flash('Полномочия назначены', category='info') elif user_role is None and UserForm.action.data == 2: flash('Таких полномочий нет', category='warning') elif user_role is not None and UserForm.action.data == 2: db.session.delete(user_role) db.session.commit() flash('Полномочия удалены', category='warning') return redirect(url_for('.user_role')) if UserFilterForm.submit_filter.data and UserFilterForm.validate_on_submit( ): # Фильтрация списка user_list = UserRoles.query if UserFilterForm.user_filter.data != 0: # Выбрано значение ( не All) user_list = user_list.filter( UserRoles.user == UserFilterForm.user_filter.data) session['user_filter_id'] = UserFilterForm.user_filter.data if UserFilterForm.role_filter.data != 0: user_list = user_list.filter( UserRoles.role == UserFilterForm.role_filter.data) session['role_filter_id'] = UserFilterForm.role_filter.data # Выбрано значение ALL - снять фильтр if UserFilterForm.user_filter.data == 0: session['user_filter_id'] = None if UserFilterForm.role_filter.data == 0: session['role_filter_id'] = None pagination = user_list.paginate(page, 5, error_out=False) userroles = pagination.items return render_template('admin/user_role.html', Panel='UserRoles', UserForm=UserForm, UserFilterForm=UserFilterForm, userroles=userroles, title='Назначение полномочий', Users=Users, Roles=Roles, pagination=pagination)