1
0
mirror of https://github.com/osmarks/mycorrhiza.git synced 2024-10-30 11:46:16 +00:00
mycorrhiza/user/files.go

94 lines
1.9 KiB
Go
Raw Normal View History

2020-11-14 14:46:04 +00:00
package user
import (
"encoding/json"
"io/ioutil"
"log"
"os"
"strings"
2020-11-14 14:46:04 +00:00
"github.com/adrg/xdg"
"github.com/bouncepaw/mycorrhiza/util"
)
// ReadUsersFromFilesystem reads all user information from filesystem and stores it internally. Call it during initialization.
func ReadUsersFromFilesystem() {
rememberUsers(usersFromFixedCredentials())
readTokensToUsers()
}
func usersFromFixedCredentials() []*User {
var users []*User
2020-11-14 14:46:04 +00:00
contents, err := ioutil.ReadFile(util.FixedCredentialsPath)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(contents, &users)
2020-11-14 14:46:04 +00:00
if err != nil {
log.Fatal(err)
}
for _, u := range users {
u.Source = SourceFixed
}
log.Println("Found", len(users), "fixed users")
return users
}
func rememberUsers(uu []*User) {
// uu is used to not shadow the `users` in `users.go`.
for _, user := range uu {
users.Store(user.Name, user)
2020-11-14 14:46:04 +00:00
}
}
2020-11-14 14:46:04 +00:00
func readTokensToUsers() {
contents, err := ioutil.ReadFile(tokenStoragePath())
2020-11-14 14:46:04 +00:00
if os.IsNotExist(err) {
return
}
if err != nil {
log.Fatal(err)
}
2020-11-14 14:46:04 +00:00
var tmp map[string]string
err = json.Unmarshal(contents, &tmp)
if err != nil {
log.Fatal(err)
}
2020-11-14 14:46:04 +00:00
for token, username := range tmp {
commenceSession(username, token)
2020-11-14 14:46:04 +00:00
}
log.Println("Found", len(tmp), "active sessions")
}
// Return path to tokens.json. Creates folders if needed.
2020-11-14 14:46:04 +00:00
func tokenStoragePath() string {
dir, err := xdg.DataFile("mycorrhiza/tokens.json")
if err != nil {
2021-03-05 20:40:41 +00:00
log.Fatal(err)
}
if strings.HasPrefix(dir, util.WikiDir) {
log.Fatal("Error: Wiki storage directory includes private config files")
2020-11-14 14:46:04 +00:00
}
return dir
}
func dumpTokens() {
tmp := make(map[string]string)
tokens.Range(func(k, v interface{}) bool {
token := k.(string)
username := v.(string)
tmp[token] = username
return true
})
blob, err := json.Marshal(tmp)
if err != nil {
log.Println(err)
} else {
ioutil.WriteFile(tokenStoragePath(), blob, 0644)
}
}