OAuth

/app/lib/user/accounts.go (2.2 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
package user

import (
"cmp"
"slices"
"strings"

"github.com/samber/lo"

"{{{ .Package }}}/app/util"
)

type Accounts []*Account

func (a Accounts) String() string {
return strings.Join(lo.Map(a, func(x *Account, _ int) string {
return x.String()
}), ",")
}

func (a Accounts) TitleString() string {
return strings.Join(lo.Map(a, func(x *Account, _ int) string {
return x.TitleString()
}), ",")
}

func (a Accounts) Images() []string {
ret := make(util.KeyVals[string], 0, len(a))
lo.ForEach(a, func(x *Account, _ int) {
if x.Picture != "" {
ret = append(ret, &util.KeyVal[string]{Key: x.Provider, Val: x.Picture})
}
})
return ret.Values()
}

func (a Accounts) Image() string {
if is := a.Images(); len(is) > 0 {
return is[0]
}
return ""
}

func (a Accounts) Sort() {
slices.SortFunc(a, func(l *Account, r *Account) int {
if l.Provider == r.Provider {
return cmp.Compare(strings.ToLower(l.Email), strings.ToLower(r.Email))
}
return cmp.Compare(l.Provider, r.Provider)
})
}

func (a Accounts) GetByProvider(p string) Accounts {
return lo.Filter(a, func(x *Account, _ int) bool {
return x.Provider == p
})
}

func (a Accounts) GetByProviderDomain(p string, d string) *Account {
return lo.FindOrElse(a, nil, func(x *Account) bool {
return x.Provider == p && x.Domain() == d
})
}

func (a Accounts) Matches(match string) bool {
if match == "" || match == "*" {
return true
}
if strings.Contains(match, ",") {
return lo.ContainsBy(util.StringSplitAndTrim(match, ","), func(x string) bool {
return a.Matches(x)
})
}
prv, acct := util.StringSplit(match, ':', true)
for _, x := range a {
if x.Provider == prv {
if acct == "" {
return true
}
return strings.HasSuffix(x.Email, acct)
}
}
return false
}

func (a Accounts) Purge(keys ...string) Accounts {
ret := make(Accounts, 0, len(a))
for _, ss := range a {
hit := false
for _, key := range keys {
if ss.Provider == key {
hit = true
}
}
if !hit {
ret = append(ret, ss)
}
}
return ret
}

func AccountsFromString(s string) Accounts {
return lo.Map(util.StringSplitAndTrim(s, ","), func(x string, _ int) *Account {
return accountFromString(x)
})
}