Пример #1
0
def create_role():
    """ Creates a new role. Requires the admin role.

    .. :quickref: Role; Creates a new role. Requires the admin role.

    **Example request**:

    .. sourcecode:: http

      POST /roles HTTP/1.1
      Host: 127.0.0.1
      Content-Type: application/json

      {
        "name": "analyst",
        "description": "Users that create and process intel"
      }

    **Example response**:

    .. sourcecode:: http

      HTTP/1.1 201 Created
      Content-Type: application/json

      {
        "id": 1,
        "name": "analyst",
        "description": "Users that create and process intel"
      }

    :reqheader Authorization: Optional Apikey value
    :resheader Content-Type: application/json
    :status 201: Role created
    :status 400: JSON does not match the schema
    :status 401: Invalid role to perform this action
    :status 409: Role already exists
    """

    data = request.get_json()

    # Verify this name does not already exist.
    existing = Role.query.filter_by(name=data['name']).first()
    if existing:
        return error_response(409, 'Role already exists')

    # Create and add the new value.
    role = Role(name=data['name'])

    # Add the description if one was given.
    if 'description' in data:
        role.description = data['description']

    db.session.add(role)
    db.session.commit()

    response = jsonify(role.to_dict())
    response.status_code = 201
    response.headers['Location'] = url_for('api.read_role', role_id=role.id)
    return response
Пример #2
0
 def setUp(self):
     db.create_all()
     user_role = Role(name='user')
     super_user_role = Role(name='superuser')
     user = User("admin", "*****@*****.**", "admin", "haslo", [
         user_role,
     ])
     db.session.add(user)
     db.session.add(
         Project("Test project", "This is a test. Only a test.", user.id,
                 'convergence behaviour'))
     db.session.commit()
Пример #3
0
def main():
    from django.contrib.auth.models import User
    from project.models import Role, Student, Teacher
    import xlrd
    filename = "user.xlsx"
    workbook = xlrd.open_workbook(filename)
    booksheet = workbook.sheet_by_index(0)
    for i in range(7):
        row = booksheet.row_values(i + 1)
        role = int(row[4])
        if role:
            user = User.objects.create_user(username=row[0], password=row[1])
            role = Role(role=int(role), user=user)
            role.save()
            teacher = Teacher(user=role)
            teacher.name = row[2]
            teacher.gender = int(row[3])
            teacher.save()
        else:

            user = User.objects.create_user(username=row[0], password=row[1])
            role = Role(role=int(role), user=user)
            role.save()
            student = Student(user=role)
            student.name = row[2]
            student.gender = int(row[3])
            student.save()
Пример #4
0
def seed_db():
    """Runs the set-up needed for both local development and production.
       Also sets up first admin user."""
    Role.insert_roles()
    admin_query = Role.query.filter_by(name='Administrator')
    if admin_query.first() is not None:
        if User.query.filter_by(email=Config.ADMIN_EMAIL).first() is None:
            user = User(first_name='Admin',
                        last_name='Account',
                        password=Config.ADMIN_PASSWORD,
                        confirmed=True,
                        email=Config.ADMIN_EMAIL)
            db.session.add(user)
            db.session.commit()
            print('Added administrator {}'.format(user.full_name()))
Пример #5
0
def initialize_extensions(app):
    db.init_app(app)
    rbac.init_app(app)
    login.init_app(app)
    Bootstrap(app)

    from project.models import User, Role, Entry

    with app.test_request_context():
        db.create_all()

        for role_name in ['anonymous', 'student', 'professor', 'admin']:
            if not Role.query.filter_by(name=role_name).first():
                role = Role(role_name)
                db.session.add(role)

        db.session.commit()

    rbac.set_user_model(User)
    rbac.set_role_model(Role)

    @login.user_loader
    def load_user(user_id):
        return User.query.filter(User.id == int(user_id)).first()

    def get_current_user():
        if session.get('logged_in'):
            return User.query.filter_by(
                username=session.get('username')).first()
        else:
            return User('anon', roles=[Role.get_by_name('anonymous')])

    rbac.set_user_loader(get_current_user)
Пример #6
0
def db(app):
    _db.app = app
    _db.create_all()

    # Admin role
    if not Role.query.filter_by(name='admin').first():
        admin_role = Role(name='admin')
        _db.session.add(admin_role)

    # Analyst role
    if not Role.query.filter_by(name='analyst').first():
        analyst_role = Role(name='analyst')
        _db.session.add(analyst_role)

    # Inactive user
    if not User.query.filter_by(username='******').first():
        user_datastore = SQLAlchemyUserDatastore(_db, User, Role)
        analyst_role = Role.query.filter_by(name='analyst').first()
        user_datastore.create_user(email='inactive@localhost', password=hash_password('inactive'), username='******',
                                   first_name='Inactive', last_name='Inactive', roles=[analyst_role])
        inactive_user = User.query.filter_by(username='******').first()
        inactive_user.active = False
        inactive_user.apikey = TEST_INACTIVE_APIKEY

    # Admin user
    if not User.query.filter_by(username='******').first():
        user_datastore = SQLAlchemyUserDatastore(_db, User, Role)
        admin_role = Role.query.filter_by(name='admin').first()
        user_datastore.create_user(email='admin@localhost', password=hash_password('admin'), username='******',
                                   first_name='Admin', last_name='Admin', roles=[admin_role])
        admin_user = User.query.filter_by(username='******').first()
        admin_user.apikey = TEST_ADMIN_APIKEY

    # Analyst user
    if not User.query.filter_by(username='******').first():
        user_datastore = SQLAlchemyUserDatastore(_db, User, Role)
        analyst_role = Role.query.filter_by(name='analyst').first()
        user_datastore.create_user(email='analyst@localhost', password=hash_password('analyst'), username='******',
                                   first_name='Analyst', last_name='Analyst', roles=[analyst_role])
        analyst_user = User.query.filter_by(username='******').first()
        analyst_user.apikey = TEST_ANALYST_APIKEY

    _db.session.commit()

    yield _db

    _db.drop_all()
Пример #7
0
def init_database():
    db.create_all()

    for role_name in ['anonymous', 'student', 'professor', 'admin']:
        role = Role(role_name)
        db.session.add(role)

    db.session.commit()

    student1 = User('Petya', roles=[Role.get_by_name('student')])
    student2 = User('Vasya', roles=[Role.get_by_name('student')])
    professor = User('teacher', roles=[Role.get_by_name('professor')])
    admin = User('root', roles=[Role.get_by_name('admin')])

    db.session.add(student1)
    db.session.add(student2)
    db.session.add(professor)
    db.session.add(admin)

    db.session.commit()

    yield db

    db.drop_all()
Пример #8
0
def login():
    if request.method == 'POST':
        username = str(request.form['username'])
        role = request.form.get('role')

        user = User.query.filter_by(username=username).first()
        if not user:
            user = User(username, roles=[Role.get_by_name(role)])

        user.authenticated = True
        session['logged_in'] = True
        session['username'] = username
        session['role'] = user.get_role()
        db.session.add(user)
        db.session.commit()
        login_user(user)

        return redirect(url_for(user.get_role() + '.index'))
    else:
        return render_template('login.html')
Пример #9
0
from project import db
from project.models import Project, User, Role, Data, Result
import json

db.drop_all()
db.create_all()

user_role = Role(name='user')
super_user_role = Role(name='superuser')
db.session.add(user_role)
db.session.add(super_user_role)

u1 = User("user1", "*****@*****.**", "username1", "haslo", [
    user_role,
])
db.session.add(u1)

u2 = User("user2", "*****@*****.**", "username2", "haslo", [
    user_role,
])
db.session.add(u2)

u3 = User("user3", "*****@*****.**", "username3", "haslo", [
    user_role,
])
db.session.add(u3)

p1 = Project("Project 1", "Description 1", u1.id, "convergence behaviour")
db.session.add(p1)

#create result table
Пример #10
0
def init_db():
    Role.insert_roles()
    ArticleType.init_data()
    init_dates()
Пример #11
0
desc = ""
role = None
for ind, line in enumerate(roles):
    if ind == 0:
        mafia_roles = [item.strip() for item in line.strip().split(" - ")]
        continue
    if ind == 1:
        citizen_roles = [item.strip() for item in line.strip().split(" - ")]
        continue

    if line.strip() in mafia_roles:
        if desc:
            Role.insert(
                recorder=user,
                is_default=True,
                role_name=role,
                team='مافیا',
                callback_data=role,
                description=desc,
            ).execute()
            desc = ""
        role = line.strip()
    elif line.strip() in citizen_roles:
        if desc:
            Role.insert(
                recorder=user,
                is_default=True,
                role_name=role,
                team='شهروند',
                callback_data=role,
                description=desc,
            ).execute()
Пример #12
0
def del_roles(name):
    name = Role(name=name)
    db.session.delete(name)
    db.session.commit()
    names = [name for name, in db.session.query(Role.name).all()]
    return names
Пример #13
0
def add_roles(name):
    name = Role(name=name, front='Y')
    db.session.add(name)
    db.session.commit()
    names = [name for name, in db.session.query(Role.name).all()]
    return names
Пример #14
0
from project import db
from project.models import User, Role, ObjDef, InpData, DiscrDef, AnalogDef, MessageDef
import json

with open('instance/db_conf.json') as data_file:
    data = json.load(data_file)

    db.drop_all()
    db.create_all()

    role1 = Role('admin')
    role2 = Role('guest')

    db.session.add(role1)
    db.session.add(role2)

    db.session.commit()

    users = list()

    for user in data["users"]:
        us = User(user["email"], user["password"], role1)
        users.append(us)
        db.session.add(us)

    db.session.commit()

    for ob in data["objects"]:
        obj = ObjDef(name=ob["name"],
                     comment=ob["comment"],
                     discr_count=len(ob["discr"]),
Пример #15
0
 def get_current_user():
     if session.get('logged_in'):
         return User.query.filter_by(
             username=session.get('username')).first()
     else:
         return User('anon', roles=[Role.get_by_name('anonymous')])