# -*- coding: utf-8 -*-
# _session.py
# Copyright (C) 2016 LEAP Encryption Acess Project
#
# This program 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.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
"""
Service for handling the local sessions.
"""

import binascii
import os

from twisted.application import service
from twisted.logger import Logger

from leap.bitmask.hooks import HookableService


class SessionService(HookableService):

    """
    This service holds random local-session tokens, that will be used to
    protect the access to the API resources.

    These tokens are different from the (remote) SRP session tokens: the
    local-session tokens are also ephemeral, but generated by the local Bitmask
    daemon.

    Right now, they are generated when a soledad instance is successfully
    created. This might be subject to further discussion, but this is the
    earliest moment in which we can decide if a user should be authenticated
    locally: it means that the entered password is able to decrypt the local
    store. In this way, we can protect the API resources even in the case that
    we don't have connectivity.
    """

    name = 'sessions'
    log = Logger()

    def __init__(self, basedir, tokens):
        service.Service.__init__(self)
        self._basedir = basedir
        self._tokens = tokens

    def startService(self):
        self.log.info('Starting Session Service')
        super(SessionService, self).startService()

    def stopService(self):
        pass

    def hook_on_new_soledad_instance(self, **kw):
        user = kw['user']
        session_token = binascii.hexlify(os.urandom(10))
        self._tokens[user] = session_token
