Debian Codegraph @

example/readline-pass-strength/readline-pass-strength.go

raw
1 // This is a small example using readline to read a password
2 // and check it's strength while typing using the zxcvbn library.
3 // Depending on the strength the prompt is colored nicely to indicate strength.
4 //
5 // This file is licensed under the WTFPL:
6 //
7 // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
8 // Version 2, December 2004
9 //
10 // Copyright (C) 2004 Sam Hocevar <[email protected]>
11 //
12 // Everyone is permitted to copy and distribute verbatim or modified
13 // copies of this license document, and changing it is allowed as long
14 // as the name is changed.
15 //
16 // DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
17 // TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
18 //
19 // 0. You just DO WHAT THE FUCK YOU WANT TO.
20 package main
21
22 import (
23 "fmt"
24
25 "github.com/chzyer/readline"
26 )
27
28 const (
29 Cyan = 36
30 Green = 32
31 Magenta = 35
32 Red = 31
33 Yellow = 33
34 BackgroundRed = 41
35 )
36
37 // Reset sequence
38 var ColorResetEscape = "\033[0m"
39
40 // ColorResetEscape translates a ANSI color number to a color escape.
41 func ColorEscape(color int) string {
42 return fmt.Sprintf("\033[0;%dm", color)
43 }
44
45 // Colorize the msg using ANSI color escapes
46 func Colorize(msg string, color int) string {
47 return ColorEscape(color) + msg + ColorResetEscape
48 }
49
50 func createStrengthPrompt(password []rune) string {
51 symbol, color := "", Red
52
53 switch {
54 case len(password) <= 1:
55 symbol = "✗"
56 color = Red
57 case len(password) <= 3:
58 symbol = "⚡"
59 color = Magenta
60 case len(password) <= 5:
61 symbol = "⚠"
62 color = Yellow
63 default:
64 symbol = "✔"
65 color = Green
66 }
67
68 prompt := Colorize(symbol, color)
69 prompt += Colorize(" ENT", Cyan)
70
71 prompt += Colorize(" New Password: ", color)
72 return prompt
73 }
74
75 func main() {
76 rl, err := readline.New("")
77 if err != nil {
78 return
79 }
80 defer rl.Close()
81
82 setPasswordCfg := rl.GenPasswordConfig()
83 setPasswordCfg.SetListener(func(line []rune, pos int, key rune) (newLine []rune, newPos int, ok bool) {
84 rl.SetPrompt(createStrengthPrompt(line))
85 rl.Refresh()
86 return nil, 0, false
87 })
88
89 pswd, err := rl.ReadPasswordWithConfig(setPasswordCfg)
90 if err != nil {
91 return
92 }
93
94 fmt.Println("Your password was:", string(pswd))
95 }