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
import (
"git.luj0ga.de/franconian/matrix-pretix/internal/config"
"maunium.net/go/mautrix"
)
type Client struct {
client *mautrix.Client
func NewClient(config *config.MatrixConfig) (*mautrix.Client, error) {
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
import (
"bufio"
"fmt"
"os"
"log"
"git.luj0ga.de/franconian/matrix-pretix/internal/config"
"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() {
switch {
case len(os.Args) == 2 && os.Args[1] == "login":
login()
case len(os.Args) == 1:
run()
default:
fmt.Fprintf(os.Stderr, "usage: %s [ \"\" | \"login\" ]\n", os.Args[0])
os.Exit(1)
if len(os.Args) != 2 {
log.Fatal("missing config file path")
}
config, err := config.ParseFromFile(os.Args[1])
if err != nil {
log.Fatal(err)
}
client, err := matrix.NewClient(&config.Matrix)
if err != nil {
log.Fatal(err)
}
}