Login form handling
This commit is contained in:
parent
8b5ac8c19f
commit
e235e3d8a8
1 changed files with 35 additions and 11 deletions
46
auth/auth.go
46
auth/auth.go
|
|
@ -1,27 +1,51 @@
|
||||||
package auth
|
package auth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
_ "embed"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//go:embed login.html
|
||||||
|
var loginPage string
|
||||||
|
|
||||||
|
//go:embed wrongPassword.html
|
||||||
|
var wrongPassword string
|
||||||
|
|
||||||
type Authenticator struct {
|
type Authenticator struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (a *Authenticator) login(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method != http.MethodPost {
|
||||||
|
w.Header().Set("content-type", "text/html")
|
||||||
|
fmt.Fprint(w, loginPage)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err := r.ParseForm()
|
||||||
|
if err != nil {
|
||||||
|
w.Header().Set("content-type", "text/html")
|
||||||
|
fmt.Fprint(w, loginPage)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
login := r.PostFormValue("login")
|
||||||
|
password := r.PostFormValue("password")
|
||||||
|
if login != "admin" || password != "secret" {
|
||||||
|
w.Header().Set("content-type", "text/html")
|
||||||
|
fmt.Fprint(w, wrongPassword)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c := http.Cookie{
|
||||||
|
Name: "token",
|
||||||
|
Value: "good",
|
||||||
|
}
|
||||||
|
http.SetCookie(w, &c)
|
||||||
|
http.Redirect(w, r, "/", http.StatusFound)
|
||||||
|
}
|
||||||
|
|
||||||
func (a *Authenticator) Authenticate(in http.HandlerFunc) http.HandlerFunc {
|
func (a *Authenticator) Authenticate(in http.HandlerFunc) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.URL.String() == "/loginok" {
|
|
||||||
c := http.Cookie{
|
|
||||||
Name: "token",
|
|
||||||
Value: "good",
|
|
||||||
}
|
|
||||||
http.SetCookie(w, &c)
|
|
||||||
http.Redirect(w, r, "/", http.StatusFound)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if r.URL.String() == "/login" {
|
if r.URL.String() == "/login" {
|
||||||
w.Header().Set("content-type", "text/html")
|
a.login(w, r)
|
||||||
fmt.Fprint(w, "<a href='/loginok'>Login</a>")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if _, err := r.Cookie("token"); err != nil {
|
if _, err := r.Cookie("token"); err != nil {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue