blasphem/pkg/auth/store.go

78 lines
1.6 KiB
Go
Raw Normal View History

2022-11-12 15:56:17 -05:00
package auth
import (
"encoding/json"
2022-11-12 17:42:51 -05:00
"fmt"
2022-11-12 15:56:17 -05:00
2022-11-13 11:55:10 -05:00
"dynatron.me/x/blasphem/pkg/auth/provider"
2022-11-12 15:56:17 -05:00
"dynatron.me/x/blasphem/pkg/storage"
)
const (
AuthStoreKey = "auth"
)
type AuthStore interface {
2022-11-12 17:50:01 -05:00
User(UserID) *User
2022-11-13 19:06:53 -05:00
Credential(provider.ProviderUser) *Credential
2022-11-12 15:56:17 -05:00
}
type authStore struct {
2022-11-13 11:55:10 -05:00
Users []User `json:"users"`
Groups []Group `json:"groups"`
Credentials []Credential `json:"credentials"`
Refresh []RefreshToken `json:"refresh_tokens"`
2022-11-12 15:56:17 -05:00
2022-11-20 08:49:24 -05:00
userMap map[UserID]*User
2022-11-13 19:06:53 -05:00
providerUsers map[provider.ProviderUser]*Credential
}
func (as *authStore) Credential(p provider.ProviderUser) *Credential {
c, have := as.providerUsers[p]
if !have {
return nil
}
return c
2022-11-12 15:56:17 -05:00
}
func (a *Authenticator) newAuthStore(s storage.Store) (as *authStore, err error) {
as = &authStore{}
err = s.Get(AuthStoreKey, as)
as.userMap = make(map[UserID]*User)
2022-11-13 19:06:53 -05:00
as.providerUsers = make(map[provider.ProviderUser]*Credential)
2022-11-12 15:56:17 -05:00
for _, u := range as.Users {
as.userMap[u.ID] = &u
}
for _, c := range as.Credentials {
prov := a.Provider(c.AuthProviderType)
if prov == nil {
return nil, fmt.Errorf("no such provider %s", c.AuthProviderType)
}
2022-11-13 09:05:09 -05:00
if c.DataRaw != nil {
2022-11-13 11:55:10 -05:00
pd := prov.NewCredData()
2022-11-13 09:05:09 -05:00
err := json.Unmarshal(*c.DataRaw, pd)
if err != nil {
return nil, err
}
2022-11-13 11:55:10 -05:00
2022-11-13 19:06:53 -05:00
c.user = prov.Lookup(pd.(provider.ProviderUser))
if c.user == nil {
return nil, fmt.Errorf("cannot find user in provider %s", prov.ProviderName())
}
as.providerUsers[c.user] = &c
2022-11-12 15:56:17 -05:00
}
}
return
}
2022-11-12 17:50:01 -05:00
func (s *authStore) User(uid UserID) *User {
return s.userMap[uid]
}