Passed
Pull Request — master (#292)
by
unknown
01:24
created

kytos.utils.decorators   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 91
Duplicated Lines 0 %

Test Coverage

Coverage 83.64%

Importance

Changes 0
Metric Value
eloc 58
dl 0
loc 91
ccs 46
cts 55
cp 0.8364
rs 10
c 0
b 0
f 0
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A kytos_auth.__init__() 0 9 1
A kytos_auth.__get__() 0 6 1
A kytos_auth.__call__() 0 25 5
A kytos_auth.authenticate() 0 29 4
1
"""Decorators for Kytos-utils."""
2 1
import logging
3 1
import os
4 1
import sys
5 1
from getpass import getpass
6
7 1
import requests
8
9 1
from kytos.utils.config import KytosConfig
10
11 1
LOG = logging.getLogger(__name__)
12
13
14
# This class is used as decorator, so this class name is lowercase and the
15
# invalid-name warning from pylint is disabled below.
16 1
class kytos_auth:  # pylint: disable=invalid-name
17
    """Class to be used as decorator to require authentication."""
18
19 1
    def __init__(self, func):
20
        """Init method.
21
22
        Save the function on the func attribute and bootstrap a new config.
23
        """
24 1
        self.func = func
25 1
        self.config = KytosConfig().config
26 1
        self.cls = None
27 1
        self.obj = None
28
29 1
    def __call__(self, *args, **kwargs):
30
        """Code run when func is called."""
31 1
        if not (self.config.has_option('napps', 'api') and
32
                self.config.has_option('napps', 'repo')):
33 1
            uri = input("Enter the kytos napps server address: ")
34 1
            self.config.set('napps', 'api', os.path.join(uri, 'api', ''))
35 1
            self.config.set('napps', 'repo', os.path.join(uri, 'repo', ''))
36
37 1
        if not self.config.has_option('auth', 'user'):
38 1
            user = input("Enter the username: ")
39 1
            self.config.set('auth', 'user', user)
40
        else:
41
            user = self.config.get('auth', 'user')
42
43 1
        if not self.config.has_option('auth', 'token'):
44 1
            token = self.authenticate()
45
        else:
46
            token = self.config.get('auth', 'token')
47
48
        # Ignore private attribute warning. We don't wanna make it public only
49
        # because of a decorator.
50 1
        config = self.obj._config  # pylint: disable=protected-access
51 1
        config.set('auth', 'user', user)
52 1
        config.set('auth', 'token', token)
53 1
        self.func.__call__(self.obj, *args, **kwargs)
54
55 1
    def __get__(self, instance, owner):
56
        """Deal with owner class."""
57 1
        self.cls = owner
58 1
        self.obj = instance
59
60 1
        return self.__call__
61
62 1
    def authenticate(self):
63
        """Check the user authentication."""
64 1
        endpoint = os.path.join(self.config.get('napps', 'api'), 'auth', '')
65 1
        username = self.config.get('auth', 'user')
66 1
        password = getpass("Enter the password for {}: ".format(username))
67 1
        response = requests.get(endpoint, auth=(username, password))
68 1
        if response.status_code == 401:
69 1
            invTokenStr = "{\"error\":\"Token not sent or expired: " \
70
                          "Signature has expired\"}\n"
71
            # pylint: disable=superfluous-parens
72 1
            if (invTokenStr == response.content.decode()):
73
                print("Seems the token was not set or is expired!"
74
                      "Please run \"kytos napps upload\" again.")
75
                LOG.error(response.content)
76
                LOG.error('ERROR: %s: %s', response.status_code,
77
                          response.reason)
78
                print("Press Ctrl+C or CTRL+Z to stop the process.")
79
                user = input("Enter the username: ")
80
                self.config.set('auth', 'user', user)
81
                self.authenticate()
82
                # sys.exit(1)
83 1
        if response.status_code != 201:
84 1
            LOG.error(response.content)
85 1
            LOG.error('ERROR: %s: %s', response.status_code, response.reason)
86 1
            sys.exit(1)
87
        else:
88 1
            data = response.json()
89 1
            KytosConfig().save_token(username, data.get('hash'))
90
            return data.get('hash')
91