Files
msteinert-go-pam/example_test.go

59 lines
1.2 KiB
Go
Raw Permalink Normal View History

2015-12-04 10:05:44 -06:00
package pam_test
2015-03-27 18:59:29 -05:00
import (
"bufio"
"errors"
"fmt"
"os"
2015-04-10 23:36:35 -05:00
2021-12-03 11:48:12 -06:00
"golang.org/x/term"
2015-03-27 18:59:29 -05:00
)
2021-12-03 11:48:12 -06:00
// This example uses the default PAM service to authenticate any users. This
// should cause PAM to ask its conversation handler for a username and password
// in sequence.
func Example() {
t, err := pam.StartFunc("passwd", "", func(s pam.Style, msg string) (string, error) {
2015-03-27 18:59:29 -05:00
switch s {
case pam.PromptEchoOff:
2021-12-03 11:48:12 -06:00
fmt.Print(msg)
pw, err := term.ReadPassword(int(os.Stdin.Fd()))
2015-03-27 18:59:29 -05:00
if err != nil {
return "", err
}
2021-12-03 11:48:12 -06:00
fmt.Println()
return string(pw), nil
case pam.PromptEchoOn:
fmt.Print(msg)
s := bufio.NewScanner(os.Stdin)
s.Scan()
return s.Text(), nil
2015-03-27 18:59:29 -05:00
case pam.ErrorMsg:
2021-12-03 11:48:12 -06:00
fmt.Fprintf(os.Stderr, "%s\n", msg)
2015-03-27 18:59:29 -05:00
return "", nil
case pam.TextInfo:
fmt.Println(msg)
return "", nil
2021-12-03 11:48:12 -06:00
default:
return "", errors.New("unrecognized message style")
2015-03-27 18:59:29 -05:00
}
})
if err != nil {
fmt.Fprintf(os.Stderr, "start: %v\n", err)
2021-12-03 11:48:12 -06:00
os.Exit(1)
2015-03-27 18:59:29 -05:00
}
defer func() {
err := t.End()
if err != nil {
fmt.Fprintf(os.Stderr, "end: %v\n", err)
os.Exit(1)
}
}()
2015-03-27 18:59:29 -05:00
err = t.Authenticate(0)
if err != nil {
fmt.Fprintf(os.Stderr, "authenticate: %v\n", err)
2021-12-03 11:48:12 -06:00
os.Exit(1)
2015-03-27 18:59:29 -05:00
}
2021-12-03 11:48:12 -06:00
fmt.Println("authentication succeeded!")
2015-03-27 18:59:29 -05:00
}