def authorize_farm( *, db: Session = Depends(get_db), farm_url: str = Body(...), auth_params: FarmAuthorizationParams, ): """ Authorize a new farm. Complete the OAuth Authorization Flow. This endpoint is only used when authorizing a new farm, before creation. See /authorize-farm/{farm_id} for authorizing existing farms. """ logging.debug("Authorizing new farm: " + farm_url) token = get_oauth_token(farm_url, auth_params) # Check the token expiration time. if token is not None and 'expires_at' in token: # Create datetime objects for comparison. now = datetime.now() expiration_time = datetime.fromtimestamp(float(token['expires_at'])) # Calculate seconds until expiration. timedelta = expiration_time - now expires_in = timedelta.total_seconds() # Update the token expires_in value token['expires_in'] = expires_in client_id = settings.AGGREGATOR_OAUTH_CLIENT_ID client_secret = settings.AGGREGATOR_OAUTH_CLIENT_SECRET # Allow OAuth over http if settings.AGGREGATOR_OAUTH_INSECURE_TRANSPORT: os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' try: logging.debug("Testing OAuth token with farmOS client.") logging.debug(token.dict()) client = farmOS( hostname=farm_url, client_id=client_id, client_secret=client_secret, scope=auth_params.scope, token=token.dict(), ) info = client.info() return {'token': token, 'info': info} except Exception as e: logging.debug("Error testing OAuth token with farmOS client: ") logging.debug(e) raise HTTPException( status_code=400, detail="Could not authenticate with farmOS server.")
def authorize_farm( farm: Farm = Depends(get_farm_by_id), *, db: Session = Depends(get_db), auth_params: FarmAuthorizationParams, ): """ Authorize an existing farm. Complete the OAuth Authorization Flow. """ try: token = get_oauth_token(farm.url, auth_params) except Exception as e: error = f"Authorization flow failed: {e}" crud.farm.update_is_authorized(db, farm_id=farm.id, is_authorized=False, auth_error=error) raise HTTPException( status_code=400, detail=error, ) new_token = FarmTokenCreate(farm_id=farm.id, **token.dict()) old_token = crud.farm_token.get_farm_token(db, farm.id) if old_token is None: token = crud.farm_token.create_farm_token(db, token=new_token) else: token = crud.farm_token.update_farm_token(db, token=old_token, token_in=new_token) # Update the scope attribute of the Farm profile to the scope that was just authorized. crud.farm.update_scope(db, farm=farm, scope=auth_params.scope) # Reconnect to the farmOS server and update farm info. try: farm_client = get_farm_client(db=db, farm=farm) info = farm_client.info() crud.farm.update_info(db, farm=farm, info=info) except Exception as e: error = f"Could not connect to farm after successful Authorization Flow: {e}" crud.farm.update_is_authorized(db, farm_id=farm.id, is_authorized=False, auth_error=error) raise HTTPException( status_code=400, detail=error, ) return token
def authorize_farm( farm: Farm = Depends(get_farm_by_id), *, db: Session = Depends(get_db), auth_params: FarmAuthorizationParams, ): """ Authorize an existing farm. Complete the OAuth Authorization Flow. """ token = get_oauth_token(farm.url, auth_params) new_token = FarmTokenCreate(farm_id=farm.id, **token.dict()) old_token = crud.farm_token.get_farm_token(db, farm.id) if old_token is None: token = crud.farm_token.create_farm_token(db, token=new_token) else: token = crud.farm_token.update_farm_token(db, token=old_token, token_in=new_token) return token