-
Notifications
You must be signed in to change notification settings - Fork 14
/
friends.go
130 lines (110 loc) · 2.11 KB
/
friends.go
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
)
var friendsFile = "friends"
const (
AdminPerm = "admin"
PinPerm = "pin"
)
var DefaultFriendsList = FriendsList{
friends: map[string]string{
"whyrusleeping": "admin",
"jbenet": "admin",
"lgierth": "admin",
},
}
type FriendsList struct {
friends map[string]string
}
func (fl *FriendsList) CanPin(name string) bool {
switch fl.friends[name] {
case AdminPerm:
return true
case PinPerm:
return true
default:
return false
}
}
func (fl *FriendsList) CanAddFriends(name string) bool {
switch fl.friends[name] {
case AdminPerm:
return true
default:
return false
}
}
func (fl *FriendsList) AddFriend(name, perm string) error {
if !validPerm(perm) {
return fmt.Errorf("invalid perm: %s", perm)
}
fl.friends[name] = perm
return fl.Write()
}
func (fl *FriendsList) RmFriend(name string) error {
delete(fl.friends, name)
return fl.Write()
}
func (fl *FriendsList) Write() error {
f, err := os.Create(friendsFile)
if err != nil {
return err
}
defer f.Close()
for n, p := range fl.friends {
_, err := fmt.Fprintf(f, "%s %s\n", n, p)
if err != nil {
return err
}
}
return nil
}
func (fl *FriendsList) Load() error {
buf, err := ioutil.ReadFile(friendsFile)
if err != nil {
return err
}
// clear friends map
f, err := fl.Parse(buf)
if err != nil {
return err
}
fl.friends = f
return nil
}
func (fl *FriendsList) Parse(buf []byte) (f map[string]string, err error) {
f = make(map[string]string)
for _, l := range bytes.Split(buf, []byte("\n")) {
if len(l) < 3 {
continue
}
parts := bytes.Split(l, []byte(" "))
if len(parts) != 2 {
return f, fmt.Errorf("format error. too many parts. %s", parts)
}
user := string(parts[0])
if len(user) < 1 {
return f, fmt.Errorf("invalid user: %s", user)
}
perm := string(parts[1])
if !validPerm(perm) {
return f, fmt.Errorf("invalid perm: %s", perm)
}
f[user] = perm
}
// ok everything seems good
return f, nil
}
func validPerm(perm string) bool {
switch perm {
case AdminPerm:
case PinPerm:
default:
return false
}
return true
}