Load credentials from config file instead of requiring user to manually enter them

This commit is contained in:
Luca 2022-07-23 00:33:05 +02:00
parent 2277916d30
commit e549d0ec19
4 changed files with 66 additions and 47 deletions

30
internal/config/config.go Normal file
View File

@ -0,0 +1,30 @@
package config
import (
"encoding/json"
"os"
)
type Config struct {
Matrix MatrixConfig
}
type MatrixConfig struct {
HomeserverURL string
UserIdentifier string
Password string
}
func ParseFromFile(path string) (config *Config, err error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
err = json.Unmarshal(data, config)
if err != nil {
return nil, err
}
return config, nil
}

View File

@ -1,9 +1,29 @@
package matrix package matrix
import ( import (
"git.luj0ga.de/franconian/matrix-pretix/internal/config"
"maunium.net/go/mautrix" "maunium.net/go/mautrix"
) )
type Client struct { func NewClient(config *config.MatrixConfig) (*mautrix.Client, error) {
client *mautrix.Client client, err := mautrix.NewClient(config.HomeserverURL, "", "")
if err != nil {
return nil, err
}
_, err := client.Login(&mautrix.ReqLogin{
Type: mautrix.AuthTypePassword,
Identifier: mautrix.UserIdentifier{
Type: mautrix.IdentifierTypeUser,
User: config.UserIdentifier,
},
Password: config.Password,
StoreCredentials: true,
})
if err != nil {
return nil, err
}
return client, nil
} }

View File

@ -1,8 +0,0 @@
package matrix
import "fmt"
func Login(identifier, password string) error {
fmt.Println(identifier, password)
return nil
}

51
main.go
View File

@ -1,47 +1,24 @@
package main package main
import ( import (
"bufio" "log"
"fmt"
"os"
"git.luj0ga.de/franconian/matrix-pretix/internal/config"
"git.luj0ga.de/franconian/matrix-pretix/internal/matrix" "git.luj0ga.de/franconian/matrix-pretix/internal/matrix"
"git.luj0ga.de/franconian/matrix-pretix/internal/util"
) )
func login() {
prompter := util.NewPrompter(bufio.NewScanner(os.Stdin))
identifier, err := prompter.Prompt("user id")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
password, err := util.PromptForPassword("password")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
err = matrix.Login(identifier, password)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() {
}
func main() { func main() {
switch { if len(os.Args) != 2 {
case len(os.Args) == 2 && os.Args[1] == "login": log.Fatal("missing config file path")
login() }
case len(os.Args) == 1:
run() config, err := config.ParseFromFile(os.Args[1])
default: if err != nil {
fmt.Fprintf(os.Stderr, "usage: %s [ \"\" | \"login\" ]\n", os.Args[0]) log.Fatal(err)
os.Exit(1) }
client, err := matrix.NewClient(&config.Matrix)
if err != nil {
log.Fatal(err)
} }
} }