Passed
Push — master ( 4d0c07...327bd3 )
by Carlos Eduardo
01:35
created

UsersManager   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 101
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 101
rs 10
wmc 13

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __init__() 0 3 1
B register() 0 29 3
A valid_attribute() 0 11 1
D ask_question() 0 35 8
1
"""Module used to handle Users in Napps Server."""
2
import logging
3
import re
4
from getpass import getpass
5
6
from kytos.utils.client import UsersClient
7
8
log = logging.getLogger(__name__)
9
10
NAME_PATTERN = ("\t- insert only letters", r'[a-zA-Z][a-zA-Z]{2,}$')
11
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
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
EMAIL_PATTERN = ("\t- follow the format: <login>@<domain>\n"
19
                 "\t\te.g. [email protected]", r'[^@]+@[^@]+\.[^@]+')
20
PHONE_PATTERN = ("\t- insert only numbers", r'\d*$')
21
22
23
class UsersManager:
24
    """Class used to handle users stored by Napps server."""
25
26
    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
    required = ["username", "first_name", "password", "email"]
42
43
    def __init__(self):
44
        """Constructor of UsersManager do not need parameters."""
45
        self._users_client = UsersClient()
46
47
    def register(self):
48
        """Method used to register a new user.
49
50
        This method will ask for user attributes and create the user in
51
        Napps server, when All required fields is filled.
52
53
        Returns:
54
            result(string): Response of user registration process.
55
        """
56
        user = {}
57
58
        print('--------------------------------------------------------------')
59
        print('Welcome to the user registration process.')
60
        print('--------------------------------------------------------------')
61
        print("To continue you must fill the following fields.")
62
        for attribute, value in self.attributes.items():
63
64
            is_required = attribute in self.required
65
            field_name = value['field_name']
66
            pattern = value['pattern']
67
68
            if attribute != 'password':
69
                user[attribute] = self.ask_question(field_name, pattern,
70
                                                    is_required)
71
            else:
72
                user[attribute] = self.ask_question(field_name, pattern,
73
                                                    password=True)
74
75
        return self._users_client.register(user)
76
77
    def ask_question(self, field_name, pattern=NAME_PATTERN, is_required=False,
78
                     password=False):
79
        """Method used to ask a question and get the input values.
80
81
        This method will validade the input values.
82
        Args:
83
            field_name(string): Field name used to ask for input value.
84
            pattern(tuple): Pattern to validate the input value.
85
            is_required(bool): Boolean value if the input value is required.
86
            password(bool): Boolean value to get input password with mask.
87
        Returns:
88
            input_value(string): Input value validated.
89
        """
90
        input_value = ""
91
        question = ("Insert the field using the pattern below:"
92
                    "\n{}\n{}: ".format(pattern[0], field_name))
93
94
        while not input_value:
95
            input_value = getpass(question) if password else input(question)
96
97
            if not (input_value or is_required):
98
                break
99
100
            if password:
101
                confirm_password = getpass('Confirm your password: ')
102
                if confirm_password != input_value:
103
                    print("Password does not match")
104
                    input_value = ""
105
106
            if not self.valid_attribute(input_value, pattern[1]):
107
                error_message = "The content must fit the pattern: {}\n"
108
                print(error_message.format(pattern[0]))
109
                input_value = ""
110
111
        return input_value
112
113
    @classmethod
114
    def valid_attribute(cls, attribute, pattern):
115
        """Check the validity of the given 'attribute' using the given pattern.
116
117
        Args:
118
            attribute(string): String with the value of an attribute
119
            pattern(string): Pattern used to validate the attribute value.
120
        Returns:
121
            pattern_found(bool): Return True if the pattern match.
122
        """
123
        return attribute and re.match(pattern, attribute)
124