mctl/cmd/login.go
jake 0ff7d25802 init commit
- first code pass
- readme updates
- config file work
- encrypting passwords
2025-04-16 16:18:40 -04:00

79 lines
1.7 KiB
Go

/*
Copyright © 2025 Jake jake.young.dev@gmail.com
*/
package cmd
import (
"bufio"
"crypto/aes"
"crypto/cipher"
"fmt"
"os"
"github.com/jake-young-dev/mcr"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// loginCmd represents the login command
var loginCmd = &cobra.Command{
Use: "login",
Short: "Login to server and send commands",
Long: `Login to server using saved config and enter command loop
sending commands to server and printing the response.`,
Run: func(cmd *cobra.Command, args []string) {
//grab saved credentials
server := viper.Get("server")
password := viper.Get("password")
port := viper.Get("port")
fmt.Printf("Logging into %s on port %d\n", server, port)
//setup decrypter
nonce := viper.Get("nonce")
block, err := aes.NewCipher([]byte(viper.Get("device").(string)))
cobra.CheckErr(err)
aesg, err := cipher.NewGCM(block)
cobra.CheckErr(err)
//decrypt password
pwd := []byte(password.(string))
nn := []byte(nonce.(string))
pt, err := aesg.Open(nil, nn, pwd, nil)
cobra.CheckErr(err)
//connect to game server
cli := mcr.NewClient(server.(string), mcr.WithPort(port.(int)))
err = cli.Connect(string(pt))
cobra.CheckErr(err)
defer cli.Close()
//start command loop
fmt.Println("Connected! Type 'mctl' to close")
scanner := bufio.NewScanner(os.Stdin)
var runningCmd string
for runningCmd != "mctl" {
fmt.Printf("RCON@%s /> ", server)
if scanner.Scan() {
runningCmd = scanner.Text()
if runningCmd == "" {
continue
}
if runningCmd == "mctl" {
break
}
res, err := cli.Command(runningCmd)
cobra.CheckErr(err)
fmt.Printf("\n%s\n", res)
}
}
},
}
func init() {
rootCmd.AddCommand(loginCmd)
}