# -*- coding: utf-8; -*-
################################################################################
#
#  WuttaFarm --Web app to integrate with and extend farmOS
#  Copyright © 2026 Lance Edgar
#
#  This file is part of WuttaFarm.
#
#  WuttaFarm is free software: you can redistribute it and/or modify it under
#  the terms of the GNU General Public License as published by the Free Software
#  Foundation, either version 3 of the License, or (at your option) any later
#  version.
#
#  WuttaFarm is distributed in the hope that it will be useful, but WITHOUT ANY
#  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
#  A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along with
#  WuttaFarm.  If not, see <http://www.gnu.org/licenses/>.
#
################################################################################
"""
Misc. utilities for web app
"""


def save_farmos_oauth2_token(request, token):
    """
    Common logic for saving the given OAuth2 token within the user
    session.  This function is called from 2 places:

    * :meth:`wuttafarm.web.views.auth.farmos_oauth_callback()`
    * :meth:`wuttafarm.web.views.farmos.master.FarmOSMasterView.get_farmos_client()`
    """
    # nb. we pretend the token expires 1 minute early, to avoid edge
    # cases around token refresh
    token["expires_at"] -= 60

    # save token to user session
    request.session["farmos.oauth2.token"] = token
