Example #1
0
def initialize_users():
    if settings.ADMIN_EMAIL is None or settings.ADMIN_PASSWORD is None:
        logger.info("Skipping creating admin as missing email and/or password")
    try:
        user = User.get(email=settings.ADMIN_EMAIL)
    except InstanceNotFound:
        user = User.create(email=settings.ADMIN_EMAIL,
                           password=settings.ADMIN_PASSWORD,
                           username="******")
    roles = Role.list()
    logger.info(f"Roles = {roles!r}")
    admin_role = Role.get(name="admin")
    if admin_role not in user.roles:
        user.roles += [admin_role]
        user.save()
Example #2
0
def set_tokens(response: Response,
               user: User,
               extra_scopes: List[str] = None) -> dict:
    if extra_scopes is None:
        extra_scopes = []
    access_token = user.create_token(
        extra_scopes=extra_scopes, expires_delta=settings.ACCESS_TOKEN_EXPIRES)
    refresh_token = user.create_token(
        expires_delta=settings.REFRESH_TOKEN_EXPIRES, refresh=True)
    response.set_cookie(
        "refresh_token",
        value=refresh_token,
        max_age=int(settings.REFRESH_TOKEN_EXPIRES.total_seconds()),
        httponly=True,
        path="/api/v1/auth/refresh",
    )
    return {"success": True, "access_token": access_token}
Example #3
0
def guest_login(response: Response):
    guest_id = token_hex(6)
    username = f"Guest-{guest_id}"
    user: User = User.create(username=username,
                             email=f"guest{guest_id}@guest",
                             verified=False)
    guest_role = Role.get(name="guest")
    user.update(roles=[guest_role])
    return set_tokens(response, user, extra_scopes=["fresh"])
Example #4
0
def login(response: Response,
          form_data: OAuth2PasswordRequestForm = Depends()):
    try:
        user = User.get(email=form_data.username)
    except InstanceNotFound:
        logging.info("Login with incorrect email: %s", form_data.username)
        return {"success": False, "message": "Incorrect email or password"}
    if user.guest or not user.check_password(password=form_data.password):
        logging.info("Login with incorrect password: %s", form_data.username)
        return {"success": False, "message": "Incorrect email or password"}
    if not user.verified:
        return {"success": False, "message": "User not activated"}
    return set_tokens(response, user, extra_scopes=["fresh"])
Example #5
0
def register(response: Response, registration: RegisterSchema):
    try:
        user = User.create(username=registration.username,
                           email=registration.email,
                           password=registration.password)
    except UniqueContstraintViolation as e:
        logging.error(f"Registration failed with email {registration.email}")
        logging.error(e)
        return {
            "success": False,
            "message": "Email or username already in use"
        }
    if user.verified:
        return set_tokens(response, user, extra_scopes=["fresh"])
    return {"success": True, "message": "User created, awaiting approval"}
Example #6
0
def refresh(response: Response, refresh_token: Optional[str] = Cookie(None)):
    if refresh_token is None:
        logger.debug("No refresh token")
        return {"success": False}
    try:
        claims = jwt.decode(refresh_token,
                            settings.SECRET_KEY,
                            algorithms=[settings.TOKEN_ALGORITHM])
        if claims["type"] != "refresh":
            logger.warning("Attempted refresh with not refresh token")
            return {"success": False}
        try:
            user = User.get(claims["sub"])
            return set_tokens(response, user)
        except InstanceNotFound:
            logger.warning(
                f"User from refresh token not found: {claims['sub']}")
            return {"success": False}
    except JWTError as e:
        logger.warning(f"JWT Error in refresh token: {e!r}")
        return {"success": False}
Example #7
0
def me(user_id: UserId = Security(get_user_id)):
    return User.get(user_id)