swill/credentials.go
2022-11-20 22:40:43 +01:00

91 lines
2.2 KiB
Go

package main
import (
"fmt"
"io/ioutil"
"os"
"os/user"
"path"
mastodon "git.gutmet.org/go-mastodon.git"
goutil "git.gutmet.org/goutil.git/misc"
)
const (
AppDir = ".swill" //inside home dir
fileServer = "Server"
fileClientKey = "ClientKey"
fileClientSecret = "ClientSecret"
fileAccessToken = "AccessToken"
)
type credentials struct {
server string
clientKey string
clientSecret string
accessToken string
}
func (c *credentials) writeCredentials(appDir string) {
write := func(file string, s string) {
optLogFatal("writeToAppDir", ioutil.WriteFile(path.Join(appDir, file), []byte(s), 0640))
}
write(fileServer, c.server)
write(fileClientKey, c.clientKey)
write(fileClientSecret, c.clientSecret)
write(fileAccessToken, c.accessToken)
}
func readCredentials(appDir string) *credentials {
read := func(f string) string {
s, err := goutil.ReadFile(path.Join(appDir, f))
optLogFatal("readFromAppDir", err)
return s
}
s := read(fileServer)
ck := read(fileClientKey)
cs := read(fileClientSecret)
at := read(fileAccessToken)
return &credentials{s, ck, cs, at}
}
func createAppDir(appDir string) {
ask := func(s string) string {
a, err := goutil.AskFor(s)
optLogFatal("createAppDir", err)
return a
}
fmt.Fprintln(os.Stderr, "Did not find "+appDir+", creating.")
fmt.Fprintln(os.Stderr, "Go to Preferences > Development > New application to register a new app and generate access tokens with read & write permissions")
err := os.MkdirAll(appDir, 0755)
optLogFatal("createAppDir", err)
s := ask("Server URL")
ck := ask("Client key")
cs := ask("Client secret")
at := ask("Access token")
c := credentials{s, ck, cs, at}
c.writeCredentials(appDir)
}
func appDir() string {
log := func(err error) { optLogFatal("appDir", err) }
currentUser, err := user.Current()
log(err)
homeDir := currentUser.HomeDir
appDir := path.Join(homeDir, AppDir)
if !goutil.PathExists(appDir) {
createAppDir(appDir)
}
return appDir
}
func initializeMastodon() {
c := readCredentials(appDir())
mastodon.Initialize(&mastodon.Config{
Server: c.server,
ClientID: c.clientKey,
ClientSecret: c.clientSecret,
AccessToken: c.accessToken,
})
}