5
5
"github.com/gorilla/mux"
6
6
"github.com/gorilla/sessions"
7
7
"github.com/go-redis/redis"
8
+ "golang.org/x/crypto/bcrypt"
8
9
"html/template"
9
10
)
10
11
@@ -22,14 +23,21 @@ func main() {
22
23
r .HandleFunc ("/" , indexPostHandler ).Methods ("POST" )
23
24
r .HandleFunc ("/login" , loginGetHandler ).Methods ("GET" )
24
25
r .HandleFunc ("/login" , loginPostHandler ).Methods ("POST" )
25
- r .HandleFunc ("/test" , testGetHandler ).Methods ("GET" )
26
+ r .HandleFunc ("/register" , registerGetHandler ).Methods ("GET" )
27
+ r .HandleFunc ("/register" , registerPostHandler ).Methods ("POST" )
26
28
fs := http .FileServer (http .Dir ("./static/" ))
27
29
r .PathPrefix ("/static/" ).Handler (http .StripPrefix ("/static/" , fs ))
28
30
http .Handle ("/" , r )
29
31
http .ListenAndServe (":8080" , nil )
30
32
}
31
33
32
34
func indexGetHandler (w http.ResponseWriter , r * http.Request ) {
35
+ session , _ := store .Get (r , "session" )
36
+ _ , ok := session .Values ["username" ]
37
+ if ! ok {
38
+ http .Redirect (w , r , "/login" , 302 )
39
+ return
40
+ }
33
41
comments , err := client .LRange ("comments" , 0 , 10 ).Result ()
34
42
if err != nil {
35
43
return
@@ -51,20 +59,34 @@ func loginGetHandler(w http.ResponseWriter, r *http.Request) {
51
59
func loginPostHandler (w http.ResponseWriter , r * http.Request ) {
52
60
r .ParseForm ()
53
61
username := r .PostForm .Get ("username" )
62
+ password := r .PostForm .Get ("password" )
63
+ hash , err := client .Get ("user:" + username ).Bytes ()
64
+ if err != nil {
65
+ return
66
+ }
67
+ err = bcrypt .CompareHashAndPassword (hash , []byte (password ))
68
+ if err != nil {
69
+ return
70
+ }
54
71
session , _ := store .Get (r , "session" )
55
72
session .Values ["username" ] = username
56
73
session .Save (r , w )
74
+ http .Redirect (w , r , "/" , 302 )
57
75
}
58
76
59
- func testGetHandler (w http.ResponseWriter , r * http.Request ) {
60
- session , _ := store .Get (r , "session" )
61
- untyped , ok := session .Values ["username" ]
62
- if ! ok {
63
- return
64
- }
65
- username , ok := untyped .(string )
66
- if ! ok {
77
+ func registerGetHandler (w http.ResponseWriter , r * http.Request ) {
78
+ templates .ExecuteTemplate (w , "register.html" , nil )
79
+ }
80
+
81
+ func registerPostHandler (w http.ResponseWriter , r * http.Request ) {
82
+ r .ParseForm ()
83
+ username := r .PostForm .Get ("username" )
84
+ password := r .PostForm .Get ("password" )
85
+ cost := bcrypt .DefaultCost
86
+ hash , err := bcrypt .GenerateFromPassword ([]byte (password ), cost )
87
+ if err != nil {
67
88
return
68
89
}
69
- w .Write ([]byte (username ))
70
- }
90
+ client .Set ("user:" + username , hash , 0 )
91
+ http .Redirect (w , r , "/login" , 302 )
92
+ }
0 commit comments