kytos.utils.users.UsersManager.__init__()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 1
dl 0
loc 6
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
"""Module used to handle Users in Napps Server."""
2 1
import logging
3 1
import re
4 1
from getpass import getpass
5
6 1
from kytos.utils.client import UsersClient
7
8 1
LOG = logging.getLogger(__name__)
9
10 1
NAME_PATTERN = ("\t- insert only letters", r'[a-zA-Z][a-zA-Z]{2,}$')
11 1
USERNAME_PATTERN = ("\t- start with letter\n"
12
                    "\t- insert only numbers and letters",
13
                    r'[a-zA-Z][a-zA-Z0-9_]{2,}$')
14 1
PASSWORD_PATTERN = ("\t- insert only the caracters:"
15
                    " [letters, numbers, _, %, &, -, $]"
16
                    "\n\t- must be at least 6 characters",
17
                    r'[a-zA-Z0-9_%\-&$]{6,}$')
18 1
EMAIL_PATTERN = ("\t- follow the format: <login>@<domain>\n"
19
                 "\t\te.g. [email protected]", r'[^@]+@[^@]+\.[^@]+')
20 1
PHONE_PATTERN = ("\t- insert only numbers", r'\d*$')
21
22
23 1
class UsersManager:
24
    """Class used to handle users stored by Napps server."""
25
26 1
    attributes = {
27
        "username": {"field_name": "Username (Required)",
28
                     "pattern": USERNAME_PATTERN},
29
        "first_name": {"field_name": "First Name (Required)",
30
                       "pattern": NAME_PATTERN},
31
        "last_name": {"field_name": "Last Name", "pattern": NAME_PATTERN},
32
        "password": {"field_name": "Password (Required)",
33
                     "pattern": PASSWORD_PATTERN},
34
        "email": {"field_name": "Email (Required)", "pattern": EMAIL_PATTERN},
35
        "phone": {"field_name": "Phone", "pattern": PHONE_PATTERN},
36
        "city": {"field_name": "City", "pattern": NAME_PATTERN},
37
        "state": {"field_name": "State", "pattern": NAME_PATTERN},
38
        "country": {"field_name": "Country", "pattern": NAME_PATTERN}
39
    }
40
41 1
    required = ["username", "first_name", "password", "email"]
42
43 1
    def __init__(self):
44
        """Instance a new UsersManager.
45
46
        This method do not need parameters.
47
        """
48 1
        self._users_client = UsersClient()
49
50 1
    def register(self):
51
        """Register a new user.
52
53
        This method will ask for user attributes and create the user in
54
        Napps server, when All required fields is filled.
55
56
        Returns:
57
            result(string): Response of user registration process.
58
59
        """
60 1
        user = {}
61
62 1
        print('--------------------------------------------------------------')
63 1
        print('Welcome to the user registration process.')
64 1
        print('--------------------------------------------------------------')
65 1
        print("To continue you must fill the following fields.")
66 1
        for attribute, value in self.attributes.items():
67
68 1
            is_required = attribute in self.required
69 1
            field_name = value['field_name']
70 1
            pattern = value['pattern']
71
72 1
            if attribute != 'password':
73 1
                user[attribute] = self.ask_question(field_name, pattern,
74
                                                    is_required)
75
            else:
76 1
                user[attribute] = self.ask_question(field_name, pattern,
77
                                                    password=True)
78
79 1
        return self._users_client.register(user)
80
81 1
    def ask_question(self, field_name, pattern=NAME_PATTERN, is_required=False,
82
                     password=False):
83
        """Ask a question and get the input values.
84
85
        This method will validade the input values.
86
        Args:
87
            field_name(string): Field name used to ask for input value.
88
            pattern(tuple): Pattern to validate the input value.
89
            is_required(bool): Boolean value if the input value is required.
90
            password(bool): Boolean value to get input password with mask.
91
        Returns:
92
            input_value(string): Input value validated.
93
94
        """
95 1
        input_value = ""
96 1
        question = ("Insert the field using the pattern below:"
97
                    "\n{}\n{}: ".format(pattern[0], field_name))
98
99 1
        while not input_value:
100 1
            input_value = getpass(question) if password else input(question)
101
102 1
            if not (input_value or is_required):
103
                break
104
105 1
            if password:
106 1
                confirm_password = getpass('Confirm your password: ')
107 1
                if confirm_password != input_value:
108
                    print("Password does not match")
109
                    input_value = ""
110
111 1
            if not self.valid_attribute(input_value, pattern[1]):
112
                error_message = "The content must fit the pattern: {}\n"
113
                print(error_message.format(pattern[0]))
114
                input_value = ""
115
116 1
        return input_value
117
118 1
    @classmethod
119
    def valid_attribute(cls, attribute, pattern):
120
        """Check the validity of the given 'attribute' using the given pattern.
121
122
        Args:
123
            attribute(string): String with the value of an attribute
124
            pattern(string): Pattern used to validate the attribute value.
125
        Returns:
126
            pattern_found(bool): Return True if the pattern match.
127
128
        """
129
        return attribute and re.match(pattern, attribute)
130