リビジョン | f75190489822954db1931521f73b692ac0aec52c (tree) |
---|---|
日時 | 2020-05-23 05:52:19 |
作者 | Francisco Reyes <francisco@nats...> |
コミッター | Francisco Reyes |
Improvements to sessions example
@@ -45,22 +45,33 @@ | ||
45 | 45 | } |
46 | 46 | |
47 | 47 | func LoginHandler(c echo.Context) error { |
48 | + var html string | |
48 | 49 | sess, _ := session.Get("session", c) |
49 | 50 | sess.Options = &sessions.Options{ |
50 | 51 | Path: "/", |
51 | - MaxAge: 20, | |
52 | + MaxAge: 30, | |
52 | 53 | HttpOnly: true, |
53 | 54 | } |
54 | 55 | post_user := c.FormValue("user") |
55 | 56 | post_pwd := c.FormValue("passwd") |
57 | + // Is user authorized? | |
56 | 58 | if (post_user == "user" || post_user == "admin") && post_pwd == "pass" { |
57 | 59 | sess.Values["auth"] = "true" |
60 | + html = "authorized for 30 seconds at <a href=\"/user\">/user</a>" | |
58 | 61 | } else { |
59 | 62 | sess.Values["auth"] = "false" |
63 | + html = "Failed auth" | |
64 | + } | |
65 | + // Is user admin? | |
66 | + if post_user == "admin" && post_pwd == "pass" { | |
67 | + sess.Values["admin"] = "true" | |
68 | + html += "<p> user is admin and can access <a href=\"/admin\">/user</a>" | |
69 | + } else { | |
70 | + sess.Values["admin"] = "false" | |
60 | 71 | } |
61 | 72 | |
62 | 73 | sess.Save(c.Request(), c.Response()) |
63 | - return c.HTML(http.StatusOK, "authorized for 20 seconds at <a href=\"/user\">/user</a>") | |
74 | + return c.HTML(http.StatusOK, html) | |
64 | 75 | } |
65 | 76 | |
66 | 77 | func LogoutHandler(c echo.Context) error { |
@@ -69,8 +80,7 @@ | ||
69 | 80 | |
70 | 81 | func UserHandler(c echo.Context) error { |
71 | 82 | var html string |
72 | - | |
73 | - sess, error := session.Get("session", c) | |
83 | + sess, _ := session.Get("session", c) | |
74 | 84 | |
75 | 85 | if sess.Values["auth"] == "true" { |
76 | 86 | html = "authorized" |
@@ -81,7 +91,15 @@ | ||
81 | 91 | } |
82 | 92 | |
83 | 93 | func AdminHandler(c echo.Context) error { |
84 | - return c.NoContent(http.StatusOK) | |
94 | + var html string | |
95 | + sess, _ := session.Get("session", c) | |
96 | + | |
97 | + if sess.Values["auth"] == "true" && sess.Values["admin"] == "true" { | |
98 | + html = "authorized admin" | |
99 | + } else { | |
100 | + html = "not authorized as admin" | |
101 | + } | |
102 | + return c.HTML(http.StatusOK, html) | |
85 | 103 | } |
86 | 104 | |
87 | 105 | // -- initialize echo and start it |