diff options
Diffstat (limited to 'phlox/login.go')
-rw-r--r-- | phlox/login.go | 71 |
1 files changed, 67 insertions, 4 deletions
diff --git a/phlox/login.go b/phlox/login.go index 27decf4..9dd82f1 100644 --- a/phlox/login.go +++ b/phlox/login.go @@ -2,12 +2,16 @@ package main import ( "fmt" + "strings" "net/http" + "text/template" + log "github.com/sirupsen/logrus" db "sanine.net/git/phlox/db" ) func LoginUser(username, password string) (bool, db.Session, error) { + p := &P auth, user, err := p.AuthenticateUser(username, password) if err != nil { return false, db.Session{}, err @@ -27,7 +31,8 @@ func LoginUser(username, password string) (bool, db.Session, error) { func LoginPostHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() username := r.Form.Get("username") - password := r.Form.Get("password") + password := strings.TrimSpace(r.Form.Get("password")) + log.Infof("username: %v\tpassword: '%v'", username, password) redirect := r.Form.Get("redirect") auth, session, err := LoginUser(username, password) @@ -36,21 +41,79 @@ func LoginPostHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "an error was encountered when processing the request") log.Error(err) + return } - if !auth { + if auth == false { // not allowed! w.WriteHeader(http.StatusUnauthorized) fmt.Fprintf(w, "bad username or password") log.Errorf("failed login for %v", username) + return } http.SetCookie(w, &http.Cookie{ Name: "phlox-session-id", Value: session.Id, SameSite: http.SameSiteLaxMode, + }) + + w.Header().Add("Location", redirect) + w.WriteHeader(http.StatusTemporaryRedirect) +} + + +var page *template.Template + +type Page struct { + Title string + Body string +} + + +func InitLogin() { + var err error + page, err = template.New("").Parse(` +<!doctype html> +<html> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <title>Login</title> + </head> + <body> + {{ .Body }} + </body> +</html> +`) + + if err != nil { + log.Fatal(err) } - http.Header.Add("Location", redirect) - http.WriteHeader(http.StatusTemporaryRedirect) + http.HandleFunc("/login", func (w http.ResponseWriter, r *http.Request) { + if r.Method == "POST" { + LoginPostHandler(w, r) + } else { + LoginGetHandler(w, r) + } + }) +} + + +func LoginGetHandler(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + page.Execute(w, Page{ + Title: "Login", + Body: ` + <form method="post"> + <label for="user">Username</label> + <input type="text" id="user" name="username"> + <br> + <label for="pass">Password</label> + <input type="text" id="pass" name="password"> + <br> + <input type="submit" value="Submit"> + `, + }) } |