-
Notifications
You must be signed in to change notification settings - Fork 0
/
vault.py
57 lines (45 loc) · 1.68 KB
/
vault.py
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
"""
In-memory representation of credential vault.
"""
from typing import Any, Dict, List
import datetime
import json
def current_dt() -> str:
"""Current UTC date and time as 'yyyy-mm-dd hh:mm:ss'."""
return datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
def parse_dt(dt: str) -> datetime.datetime:
"""Parse 'yyyy-mm-dd hh:mm:ss' to datetime."""
return datetime.datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
class Vault:
"""
Credential vault.
"""
def __init__(self) -> None:
"""Create empty vault."""
self.entries: Dict[str, Dict[str, Any]] = {}
def list(self) -> List[str]:
"""List vault contents."""
return sorted(self.entries.keys())
def set(self, credname: str, **data: str) -> None:
"""Set vault entry."""
# keeps old created if overwriting existing entry
now = current_dt()
data['created'] = self.entries.get(credname, {}).get('created', now)
data['modified'] = now
self.entries[credname] = data
def get(self, credname: str) -> Dict[str, Any]:
"""Get vault entry."""
return self.entries[credname]
def search(self, credsubstr: str) -> List[str]:
"""Case-insensitive substring search of vault."""
css_low = credsubstr.lower()
return sorted([k for k in self.entries if css_low in k.lower()])
def remove(self, credname: str) -> None:
"""Remove vault entry."""
del self.entries[credname]
def dumps(self) -> str:
"""Serialize vault using JSON."""
return json.dumps(self.entries)
def loads(self, s: str) -> None:
"""Deserialize vault from JSON."""
self.entries = json.loads(s)