Conditions | 11 |
Total Lines | 56 |
Lines | 0 |
Ratio | 0 % |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like Auth.run() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | #!/usr/bin/env python |
||
24 | def run(self, username, factor, |
||
25 | ipaddr, device, push_type, passcode, pushinfo): |
||
26 | """ |
||
27 | Auth against the Duo Platorm. |
||
28 | |||
29 | Returns: An dict with info returned by Duo. |
||
30 | |||
31 | Raises: |
||
32 | ValueError: 'Duo config not found in config' or 'Invalid factor' |
||
33 | RuntimeError: 'Failed auth.' |
||
34 | """ |
||
35 | |||
36 | auth_kargs = {} |
||
37 | |||
38 | if factor == "auto" or factor == "push": |
||
39 | auth_kargs['type'] = push_type |
||
40 | auth_kargs['device'] = device |
||
41 | |||
42 | if ipaddr is not None: |
||
43 | auth_kargs['ipaddr'] = ipaddr |
||
44 | |||
45 | if pushinfo is not None: |
||
46 | info = {} |
||
47 | for value in pushinfo.split('; '): |
||
48 | (key, value) = value.split('=') |
||
49 | info[key] = value |
||
50 | |||
51 | encoded = urllib.urlencode(info) |
||
52 | auth_kargs['pushinfo'] = encoded |
||
53 | elif factor == "passcode": |
||
54 | auth_kargs['passcode'] = passcode |
||
55 | elif factor == "phone": |
||
56 | auth_kargs['device'] = device |
||
57 | elif factor == "sms": |
||
58 | # As 'sms' just denies and then we do not support it |
||
59 | # requires re-authentication. |
||
60 | |||
61 | raise ValueError("Denied, we do not support SMS!") |
||
62 | else: |
||
63 | raise ValueError("Invalid factor!") |
||
64 | |||
65 | try: |
||
66 | data = self.duo_auth.auth(factor=factor, |
||
67 | username=username, |
||
68 | **auth_kargs) |
||
69 | except RuntimeError, e: |
||
70 | raise RuntimeError("Error: %s" % e) |
||
71 | else: |
||
72 | if data['result'] == "allow": |
||
73 | return data |
||
74 | elif data['result'] == "deny": |
||
75 | self.send_user_error(data['status_msg']) |
||
76 | raise RuntimeError("{}".format( |
||
77 | data['status_msg'])) |
||
78 | else: |
||
79 | raise RuntimeError("Invalid status") |
||
80 |