Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

from __future__ import absolute_import, division, print_function 

 

import os 

import os.path 

 

import yaml 

 

from appr.config import DEFAULT_CONF_DIR 

from appr.utils import mkdir_p 

 

 

class ApprAuth(object): 

""" Store Auth object """ 

 

def __init__(self, conf_directory=DEFAULT_CONF_DIR): 

self.conf_directory = conf_directory 

home = os.path.expanduser("~") 

old_path = "%s/%s/auth_token" % (home, conf_directory) 

path = "%s/%s/auths.yaml" % (home, conf_directory) 

mkdir_p(os.path.join(home, conf_directory)) 

self.tokenfile = os.path.join(home, path) 

self._tokens = None 

self._retro_compat(old_path) 

 

def _retro_compat(self, old): 

oldtoken = self._old_token(old) 

if oldtoken: 

if self.tokens is None or '*' not in self.tokens['auths']: 

self.add_token('*', oldtoken) 

os.remove(old) 

 

def _old_token(self, path): 

if os.path.exists(path): 

with open(path, 'r') as tokenfile: 

return tokenfile.read() 

else: 

return None 

 

@property 

def tokens(self): 

if self._tokens is None: 

if os.path.exists(self.tokenfile): 

with open(self.tokenfile, 'r') as tokenfile: 

self._tokens = yaml.load(tokenfile.read()) 

else: 

return None 

return self._tokens 

 

def token(self, host=None): 

if not self.tokens: 

return None 

if host is None or host not in self.tokens['auths']: 

host = '*' 

return self.tokens['auths'].get(host, None) 

 

def add_token(self, host, value): 

auths = self.tokens 

if auths is None: 

auths = {'auths': {}} 

auths['auths'][host] = value 

self._write_tokens(auths) 

 

def _write_tokens(self, tokens): 

with open(self.tokenfile, 'w') as tokenfile: 

tokenfile.write( 

yaml.safe_dump(tokens, indent=2, default_style='"', default_flow_style=False)) 

 

def delete_token(self, host): 

auths = self.tokens 

if not auths or host not in auths['auths']: 

return None 

prev = auths['auths'].pop(host) 

self._write_tokens(auths) 

return prev