summaryrefslogtreecommitdiff
path: root/example_test.go
blob: 8a347a626d257be319710b5e9a36d98480897e9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package pam_test

import (
	"bufio"
	"errors"
	"fmt"
	"os"

	"github.com/msteinert/pam"
	"golang.org/x/term"
)

// 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("", "", func(s pam.Style, msg string) (string, error) {
		switch s {
		case pam.PromptEchoOff:
			fmt.Print(msg)
			pw, err := term.ReadPassword(int(os.Stdin.Fd()))
			if err != nil {
				return "", err
			}
			fmt.Println()
			return string(pw), nil
		case pam.PromptEchoOn:
			fmt.Print(msg)
			s := bufio.NewScanner(os.Stdin)
			s.Scan()
			return s.Text(), nil
		case pam.ErrorMsg:
			fmt.Fprintf(os.Stderr, "%s\n", msg)
			return "", nil
		case pam.TextInfo:
			fmt.Println(msg)
			return "", nil
		default:
			return "", errors.New("unrecognized message style")
		}
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "start: %s\n", err.Error())
		os.Exit(1)
	}
	err = t.Authenticate(0)
	if err != nil {
		fmt.Fprintf(os.Stderr, "authenticate: %s\n", err.Error())
		os.Exit(1)
	}
	fmt.Println("authentication succeeded!")
}