async def get_item_user(pk: int):
    item = dict(await
                database.fetch_one(items.select().where(items.c.id == pk)))
    user = dict(await database.fetch_one(
        users.select().where(users.c.id == item["owner_id"])))
    item.update({"owner": user})
    return item
Beispiel #2
0
    async def permits(self, identity, permission, context=None):
        if identity is None:
            return False

        async with self.dbengine.acquire() as conn:
            where = sa.and_(users.c.login == identity,
                            sa.not_(users.c.disabled))
            query = users.select().where(where)
            ret = await conn.execute(query)
            user = await ret.fetchone()
            if user is not None:
                user_id = user[0]
                is_superuser = user[3]
                if is_superuser:
                    return True

                where = permissions.c.user_id == user_id
                query = permissions.select().where(where)
                ret = await conn.execute(query)
                result = await ret.fetchall()

                if ret is not None:
                    for record in result:
                        if record.perm_name == permission:
                            return True

            return False
Beispiel #3
0
async def login(
        name: str = Body(...),
        password: str = Body(...),
):
    async with database.transaction():
        query = users.select().where(users.c.name == name)
        user = await database.fetch_one(query)

        if not user:
            raise HTTPException(
                status_code=404,
                detail=f"User with name: '{name}' not found",
            )

        if not check_hash(hash_code=user['hash_code'], code=password):
            raise HTTPException(
                status_code=403,
                detail=f"Incorrect username or password",
            )

        token = jwt.encode(
            {
                'id':
                user['id'],
                'exp':
                datetime.utcnow() + timedelta(seconds=int(config.JWT_EXPIRE))
            },
            config.JWT_SALT,
            algorithm='HS512')

        return LoginSchema(user=UserSchema(
            id=user['id'],
            name=user['name'],
        ),
                           token=token)
Beispiel #4
0
async def get_all_users(request):
    async with request.app['db'].acquire() as conn:
        raw_query = await conn.fetch(users.select().order_by(users.c.surname))
        query = [dict(record) for record in raw_query]
        if query:
            return web.json_response(query)
        else:
            return aiohttp.web.HTTPNoContent()
async def get_user(user_id: int):
    user = dict(await
                database.fetch_one(users.select().where(users.c.id == user_id)
                                   ))
    list_item = await database.fetch_all(
        items.select().where(items.c.owner_id == user["id"]))
    user.update({"items": [dict(result) for result in list_item]})
    return user
Beispiel #6
0
    def get_by_id(cls, user_id):

        doc = users.select().where(users.c.user_id == user_id).execute()
        doc = doc.first()
        if not doc:
            return None
        user = cls()
        user.doc = doc
        return user
Beispiel #7
0
async def get_user(request):
    try:
        user_id = int(request.match_info.get('user_id'))
        async with request.app['db'].acquire() as conn:
            # print(conn.__dir__())
            raw_query = await conn.fetchrow(
                users.select().where(users.c.id == user_id))
            return web.json_response(dict(raw_query))
    except Exception:
        return aiohttp.web.HTTPNotFound()
Beispiel #8
0
async def check_credentials(dbengine, username, password):
    async with dbengine.acquire() as conn:
        where = sa.and_(users.c.login == username, sa.not_(users.c.disabled))
        query = users.select().where(where)
        ret = await conn.execute(query)
        user = await ret.fetchone()
        if user is not None:
            hash = user[2]
            return sha256_crypt.verify(password, hash)
    return False
Beispiel #9
0
async def get_user(request):
    async with request.app['db'].acquire() as conn:
        username = request.match_info['name']

        cursor = await conn.execute(
            users.select().where(users.c.username == username.lower()))
        result = await cursor.fetchone()

        if result:
            return web.json_response(data={"username": result.username})
        else:
            return web.json_response(data={"error": "not found"}, status=404)
Beispiel #10
0
async def validate_password(request):
    async with request.app['db'].acquire() as conn:
        username = request.match_info['name']
        data = await request.json()
        password = data["password"]

        cursor = await conn.execute(
            users.select().where(users.c.username == username.lower()))
        result = await cursor.fetchone()

        if result:
            password_hash = result.password
            if pbkdf2_sha256.verify(password, password_hash):
                return web.json_response(data={}, status=204)

        return web.json_response(data={}, status=403)
Beispiel #11
0
def api_token():
    data = json.loads(request.get_data())
    error = validate_for_user(data)
    if error:
        resp = jsonify(error)
        resp.status_code = 400
        return resp
    stmt = users.select()\
        .where(users.c.username == data.get('username'))\
        .where(users.c.password == data.get('password'))
    conn = engine.connect()
    result = conn.execute(stmt)
    conn.close()
    if result.rowcount:
        # authenticated now, generate or fetch token
        user_obj = dict(result.fetchone())
        now = datetime.datetime.now()
        fifteen_minutes_back = now - datetime.timedelta(minutes=15)
        token_ext = token.select()\
            .where(token.c.user_id == user_obj.get('id'))\
            .where(token.c.last_accessed_at > fifteen_minutes_back)
        conn = engine.connect()
        fetch_token_result = conn.execute(token_ext)
        conn.close()
        if fetch_token_result.rowcount:
            # token exists, just return
            return jsonify({
                'token': dict(fetch_token_result.fetchone()).get('token')
            })
        else:
            # create, persist and return the token
            token_string = uuid.uuid4()
            token_stmt = token.insert().values(user_id=user_obj.get('id'), token=unicode(token_string))
            conn = engine.connect()
            conn.execute(token_stmt)
            conn.close()
            return jsonify({
                'token': token_string
            })
    else:
        # unauthenticated
        return unauthenticated()
Beispiel #12
0
async def select_user(request):
    try:
        data = await request.json()
        async with request.app['db'].acquire() as conn:
            all_columns = users.columns.keys()
            for key in data.keys():
                if key not in all_columns or not data[key]:
                    return aiohttp.web.HTTPBadRequest(
                        text=f'not valid param {key.upper()}')
            raw_query = await conn.fetch(users.select().where(
                (and_(users.c.name == data['name'],
                      users.c.surname == data['surname'],
                      users.c.patronymic == data['patronymic'],
                      users.c.gender == data['gender']))))
            if raw_query:
                query = [dict(record) for record in raw_query]
                return web.json_response(query)
            else:
                return aiohttp.web.HTTPNoContent()
    except Exception:
        return aiohttp.web.HTTPNotFound()
Beispiel #13
0
async def post_car(request):
    try:
        data = await request.json()
        async with request.app['db'].acquire() as conn:
            user = data['user_id']
            raw_user = await conn.fetchrow(users.select(users.c.id == user))
            if not raw_user:
                return aiohttp.web.HTTPBadRequest(text=f'no such user')
            all_columns = cars.columns.keys()
            res = {}
            for c in all_columns:
                if c != 'id':
                    try:
                        res[c] = data[c]
                    except Exception:
                        return aiohttp.web.HTTPBadRequest(
                            text=f'param {c.upper()} is required')
            r = await conn.execute(cars.insert().values(res))
            return aiohttp.web.HTTPCreated()
    except Exception:
        return aiohttp.web.HTTPBadRequest()
Beispiel #14
0
def list_users():
    usuarios = users.select().execute()
    data = {
        'users': usuarios
    }
    return render_template('auth/users.html', **data)
Beispiel #15
0
async def get_users(skip: int = 0, limit: int = 100):
    results = await database.fetch_all(users.select().offset(skip).limit(limit)
                                       )
    return [dict(result) for result in results]
Beispiel #16
0
async def get_all_users():
    all_users_query = users.select()
    all_users_query_fetch = await database.fetch_one(query=all_users_query)
    result = [dict(result)['id'] for result in all_users_query_fetch]
Beispiel #17
0
async def get_user_by_email(email: str):
    return await database.fetch_one(
        users.select().where(users.c.email == email))