summaryrefslogtreecommitdiff
path: root/example_test.go
blob: 3ab0882edfd41d86abde1ed0db71bfcd7ef1962d (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
53
54
55
56
57
58
59
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("passwd", "", 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: %v\n", err)
		os.Exit(1)
	}
	defer func() {
		err := t.End()
		if err != nil {
			fmt.Fprintf(os.Stderr, "end: %v\n", err)
			os.Exit(1)
		}
	}()
	err = t.Authenticate(0)
	if err != nil {
		fmt.Fprintf(os.Stderr, "authenticate: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("authentication succeeded!")
}