You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-sendxmpp/handlemechanisminfo.go

73 lines
1.7 KiB
Go

// Copyright Martin Dosch.
// Use of this source code is governed by the BSD-2-clause
// license that can be found in the LICENSE file.
package main
import (
"errors"
"fmt"
"os"
"os/user"
"strings"
)
func findPinFilePath(username string) (string, error) {
osDataDir := os.Getenv("$XDG_DATA_HOME")
if osDataDir == "" {
// Get the current user.
curUser, err := user.Current()
if err != nil {
return strError, fmt.Errorf("findConfig: failed to get current user: %w", err)
}
// Get home directory.
home := curUser.HomeDir
if home == "" {
return strError, errors.New("no home directory found")
}
osDataDir = home + "/.local/share/"
}
authPinFilePath := osDataDir + "/go-sendxmpp/" + username + "/"
return authPinFilePath, nil
}
// Opens the auth mechanism pin file and returns the value.
func parsePinFile(user string) (string, error) {
// Find auth pin file
authPinFile, err := findPinFilePath(user)
if err != nil {
return "", err
}
// Read file.
m, err := os.ReadFile(authPinFile + "authmechanism")
if err != nil {
return "", err
}
// Strip trailing newline.
mechanism := strings.TrimSuffix(string(m), "\n")
return mechanism, nil
}
// Writes the used mechanism to the auth pin file.
func writePinFile(mechanism string, user string) error {
// Find auth pin file
authPinFilePath, err := findPinFilePath(user)
if err != nil {
return err
}
if _, err = os.Stat(authPinFilePath); os.IsNotExist(err) {
err = os.MkdirAll(authPinFilePath, defaultDirRights)
if err != nil {
return fmt.Errorf("writePinFile: could not create folder for auth pin file: %w", err)
}
}
err = os.WriteFile(authPinFilePath+"authmechanism", []byte(mechanism+"\n"), 0o400)
if err != nil {
return err
}
return nil
}