Conditions | 11 |
Total Lines | 58 |
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 |
||
25 | def run(self, username, factor, |
||
26 | ipaddr, device, push_type, passcode, pushinfo): |
||
27 | """ |
||
28 | Auth against the Duo Platorm. |
||
29 | |||
30 | Returns: An dict with info returned by Duo. |
||
31 | |||
32 | Raises: |
||
33 | ValueError: 'Duo config not found in config' or 'Invalid factor' |
||
34 | RuntimeError: 'Failed auth.' |
||
35 | """ |
||
36 | |||
37 | auth_kargs = {} |
||
38 | |||
39 | if factor == "auto" or factor == "push": |
||
40 | auth_kargs['type'] = push_type |
||
41 | auth_kargs['device'] = device |
||
42 | |||
43 | if ipaddr is not None: |
||
44 | auth_kargs['ipaddr'] = ipaddr |
||
45 | |||
46 | if pushinfo is not None: |
||
47 | info = {} |
||
48 | for value in pushinfo.split('; '): |
||
49 | (key, value) = value.split('=') |
||
50 | info[key] = value |
||
51 | |||
52 | encoded = urllib.urlencode(info) |
||
53 | auth_kargs['pushinfo'] = encoded |
||
54 | elif factor == "passcode": |
||
55 | auth_kargs['passcode'] = passcode |
||
56 | elif factor == "phone": |
||
57 | auth_kargs['device'] = device |
||
58 | elif factor == "sms": |
||
59 | # As 'sms' just denies and then we do not support it |
||
60 | # requires re-authentication. |
||
61 | |||
62 | print "Denied, we do not support SMS!" |
||
63 | raise ValueError("Denied, we do not support SMS!") |
||
64 | else: |
||
65 | raise ValueError("Invalid factor!") |
||
66 | |||
67 | try: |
||
68 | data = self.duo_auth.auth(factor=factor, |
||
69 | username=username, |
||
70 | **auth_kargs) |
||
71 | except RuntimeError, e: |
||
72 | print "Error: %s" % e |
||
73 | raise RuntimeError("Error: %s" % e) |
||
74 | else: |
||
75 | if data['result'] == "allow": |
||
76 | return data |
||
77 | elif data['result'] == "deny": |
||
78 | print data['status_msg'] |
||
79 | raise RuntimeError("{}".format( |
||
80 | data['status_msg'])) |
||
81 | else: |
||
82 | raise RuntimeError("Invalid status") |
||
83 |