-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlan_ips.go
More file actions
118 lines (101 loc) · 2.47 KB
/
lan_ips.go
File metadata and controls
118 lines (101 loc) · 2.47 KB
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
//go:build !wasm
package user
import (
"time"
"github.com/tinywasm/orm"
"github.com/tinywasm/unixid"
)
func (m *Module) RegisterLAN(userID, rut string) error {
normalized, err := validateRUT(rut)
if err != nil {
return ErrInvalidRUT
}
id, err := getIdentityByProvider(m.db, "lan", normalized)
if err == nil {
if id.UserID != userID {
return ErrRUTTaken
}
return nil
} else if err != ErrNotFound {
return err
}
return createIdentity(m.db, userID, "lan", normalized, "")
}
func (m *Module) UnregisterLAN(userID string) error {
_, err := getIdentityByUserAndProvider(m.db, userID, "lan")
if err == ErrNotFound {
return ErrNotFound
}
if err != nil {
return err
}
qb := m.db.Query(&LANIP{}).Where(LANIP_.UserID).Eq(userID)
ips, _ := ReadAllLANIP(qb)
for _, ip := range ips {
m.db.Delete(ip, orm.Eq(LANIP_.ID, ip.ID))
}
qbId := m.db.Query(&Identity{}).Where(Identity_.UserID).Eq(userID).Where(Identity_.Provider).Eq("lan")
ids, _ := ReadAllIdentity(qbId)
for _, id := range ids {
m.db.Delete(id, orm.Eq(Identity_.ID, id.ID))
}
return nil
}
func (m *Module) AssignLANIP(userID, ip, label string) error {
qb := m.db.Query(&LANIP{}).Where(LANIP_.IP).Eq(ip)
results, err := ReadAllLANIP(qb)
if err != nil {
return err
}
if len(results) > 0 {
return ErrIPTaken
}
u, err := unixid.NewUnixID()
if err != nil {
return err
}
id := u.GetNewID()
now := time.Now().Unix()
i := &LANIP{
ID: id,
UserID: userID,
IP: ip,
Label: label,
CreatedAt: now,
}
return m.db.Create(i)
}
func (m *Module) RevokeLANIP(userID, ip string) error {
qb := m.db.Query(&LANIP{}).Where(LANIP_.UserID).Eq(userID).Where(LANIP_.IP).Eq(ip)
results, err := ReadAllLANIP(qb)
if err != nil {
return err
}
if len(results) == 0 {
return ErrNotFound
}
return m.db.Delete(results[0], orm.Eq(LANIP_.ID, results[0].ID))
}
func (m *Module) GetLANIPs(userID string) ([]LANIP, error) {
qb := m.db.Query(&LANIP{}).Where(LANIP_.UserID).Eq(userID).OrderBy(LANIP_.CreatedAt).Asc()
results, err := ReadAllLANIP(qb)
if err != nil {
return nil, err
}
ips := make([]LANIP, 0, len(results))
for _, r := range results {
ips = append(ips, *r)
}
return ips, nil
}
func checkLANIP(db *orm.DB, userID, ip string) error {
qb := db.Query(&LANIP{}).Where(LANIP_.UserID).Eq(userID).Where(LANIP_.IP).Eq(ip)
results, err := ReadAllLANIP(qb)
if err != nil {
return ErrInvalidCredentials
}
if len(results) == 0 {
return ErrInvalidCredentials
}
return nil
}