Пример #1
0
class Config(object):
    # FLASK
    DEBUG = False
    TESTING = False
    # JWT
    JWT_TOKEN_LOCATION = ['headers']
    JWT_ACCESS_TOKEN_EXPIRES = 20
    JWT_REFRESH_TOKEN_EXPIRES = 1800
    SECRET_KEY = 's3nh4-d01d4'

    # POSTGRES
    DB_HOST = decouple_config('DB_HOST', 'postgres')
    DB_PORT = decouple_config('DB_HOST', 5432)
    DB_NAME = decouple_config('DB_NAME', 'postgres')
    DB_USER = decouple_config('DB_USER', 'postgres')
    DB_PASSWORD = decouple_config('DB_PASSWORD', 'postgres')
    SQLALCHEMY_DATABASE_URI = f'postgres://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}?client_encoding=utf8'
Пример #2
0
def request_password_reset(email: EmailStr,
                           dba: Session = Depends(deps.get_db)):
    sent_email = (
        "We've emailed you instructions for setting your password. "
        "If an account exists with the email you entered, you should "
        "receive them shortly.")
    user = cruds.get_user_by_email(db=dba, email=email)
    if not user:
        return {'detail': sent_email}

    PASSWORD_RESET_EXPIRES = decouple_config('PASSWORD_RESET_EXPIRES',
                                             cast=int,
                                             default=1440)
    expires = datetime.now() + timedelta(minutes=PASSWORD_RESET_EXPIRES)
    request = models.PasswordReset(email=email, expires=expires)
    dba.add(request)
    try:
        dba.commit()
    except IntegrityError:
        dba.rollback()
        dba.query(models.PasswordReset). \
            filter(models.PasswordReset.email == email). \
            delete()
        dba.add(request)
        dba.commit()
    message = (
        'Hi,\n\n'
        'you are receiving this email because we received a password\n'
        'reset request for your account. Use this token for your password\n'
        f'reset: {request.uuid}.\n\n'
        'If you did not request a password reset, no further action is required.'
    )
    send_dummy_mail(subject="Reset Your Password",
                    message=message,
                    to=request.email)
    return {"detail": sent_email}
Пример #3
0
from fastapi.routing import APIRouter
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import (
    get_redoc_html,
    get_swagger_ui_html,
    get_swagger_ui_oauth2_redirect_html,
)

from config import db
from access_control import router as access_control_router
from users import router as users_router

# Use self-hosted files
USE_LOCAL_DOCS_FILES = decouple_config('USE_LOCAL_DOCS_FILES',
                                       cast=bool,
                                       default=False)
DOCS_URL = decouple_config('DOCS_URL')
REDOC_URL = decouple_config('REDOC_URL')
OPENAPI_URL = decouple_config('OPENAPI_URL')
DOCS_AUTH_URL = decouple_config('DOCS_AUTH_URL')
APP_TITLE = decouple_config('APP_TITLE', default='FastAPI')
if USE_LOCAL_DOCS_FILES:
    DOCS_URL = None
    REDOC_URL = None

# Locaal docs urls
local_docs_router = APIRouter(include_in_schema=False)


@local_docs_router.get("/docs")
Пример #4
0
from datetime import datetime, timedelta

from decouple import config as decouple_config
from jose import JWTError, jwt
from passlib.context import CryptContext

# Password hash context
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# JWT config
SECRET_KEY = decouple_config('SECRET_KEY')
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = decouple_config('AUTH_TOKEN_EXPIRES', cast=int)


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.hash(password)


def create_access_token(data: dict):
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt
Пример #5
0
from decouple import config as decouple_config

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Database server config
DB_HOST = decouple_config('DB_HOST')
DB_PORT = decouple_config('DB_PORT', cast=int)
DB_USER = decouple_config('DB_USER')
DB_NAME = decouple_config('DB_NAME')
DB_ENGINE = decouple_config('DB_ENGINE', default='postgres')
DB_PASSWORD = decouple_config('DB_PASSWORD')

DB_URL = f'{DB_ENGINE}://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}'

# SQLAlchemy config

engine = create_engine(DB_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()
from jose import jwt
from fastapi import Depends, HTTPException
from sqlalchemy.orm import Session
from decouple import config as decouple_config
from fastapi.security import OAuth2PasswordBearer

from config import db
from users import cruds as users_cruds, schemas as users_schema

SECRET_KEY = decouple_config('SECRET_KEY')
TOKEN_URL = decouple_config('DOCS_AUTH_URL', default='token')
ALGORITHM = "HS256"
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=TOKEN_URL)


def get_db():
    dbase = db.SessionLocal()
    try:
        yield dbase
    finally:
        dbase.close()


def get_current_user(token: str = Depends(oauth2_scheme),
                     db: Session = Depends(get_db)):
    payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    user = users_schema.UserSchema.from_orm(
        users_cruds.get_user_by_email(db=db, email=payload['data']['email']))
    return user

Пример #7
0
def configure_app(app):
    config_name = decouple_config('FLASK_ENV', 'test')
    app.config.from_object(config[config_name])
Пример #8
0
        },
    },
]

WSGI_APPLICATION = "config.wsgi.application"

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

# TODO: Add to documentation that database keys should not be than 128 characters.

# MATHESAR_DATABASES should be of the form '({db_name}|{db_url}), ({db_name}|{db_url})'
# See pipe_delim above for why we use pipes as delimiters
DATABASES = {
    db_key: db_url(url_string)
    for db_key, url_string in decouple_config('MATHESAR_DATABASES',
                                              cast=Csv(pipe_delim))
}
DATABASES[decouple_config('DJANGO_DATABASE_KEY')] = decouple_config(
    'DJANGO_DATABASE_URL', cast=db_url)

for db_key, db_dict in DATABASES.items():
    # Engine can be '.postgresql' or '.postgresql_psycopg2'
    if not db_dict['ENGINE'].startswith('django.db.backends.postgresql'):
        raise ValueError(f"{db_key} is not a PostgreSQL database. "
                         f"{db_dict['ENGINE']} found for {db_key}'s engine.")

# pytest-django will create a new database named 'test_{DATABASES[table_db]['NAME']}'
# and use it for our API tests if we don't specify DATABASES[table_db]['TEST']['NAME']
if decouple_config('TEST', default=False, cast=bool):
    for db_key, _ in decouple_config('MATHESAR_DATABASES',
                                     cast=Csv(pipe_delim)):