File: device_cookie.py

package info (click to toggle)
tryton-client 7.0.31-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,472 kB
  • sloc: python: 27,196; sh: 37; makefile: 18
file content (76 lines) | stat: -rw-r--r-- 1,879 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# This file is part of Tryton.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import json
import logging
import os
from threading import Lock

from tryton.config import CONFIG, get_config_dir

logger = logging.getLogger(__name__)
COOKIES_PATH = os.path.join(get_config_dir(), 'device_cookies')


_lock = Lock()


def renew():
    from tryton.common import common

    def set_cookie(new_cookie):
        try:
            new_cookie = new_cookie()
        except Exception:
            logger.error("Cannot renew device cookie", exc_info=True)
        else:
            _set(new_cookie)

    current_cookie = get()
    common.RPCExecute(
        'model', 'res.user.device', 'renew', current_cookie,
        process_exception=False, callback=set_cookie)


def get():
    cookies = _load()
    return cookies.get(_key())


def _key():
    from tryton import common

    host = CONFIG['login.host']
    hostname = common.get_hostname(host)
    port = common.get_port(host)
    database = CONFIG['login.db']
    username = CONFIG['login.login']

    return '%(username)s@%(hostname)s:%(port)s/%(database)s' % {
        'username': username,
        'hostname': hostname,
        'port': port,
        'database': database,
        }


def _set(cookie):
    cookies = _load()
    cookies[_key()] = cookie
    try:
        with _lock:
            with open(COOKIES_PATH, 'w') as cookies_file:
                json.dump(cookies, cookies_file)
    except Exception:
        logger.error('Unable to save cookies file')


def _load():
    if not os.path.isfile(COOKIES_PATH):
        return {}
    try:
        with open(COOKIES_PATH) as cookies:
            cookies = json.load(cookies)
    except Exception:
        logger.error("Unable to load device cookies file", exc_info=True)
        cookies = {}
    return cookies