summaryrefslogtreecommitdiff
path: root/phlox/login.go
diff options
context:
space:
mode:
Diffstat (limited to 'phlox/login.go')
-rw-r--r--phlox/login.go56
1 files changed, 56 insertions, 0 deletions
diff --git a/phlox/login.go b/phlox/login.go
new file mode 100644
index 0000000..27decf4
--- /dev/null
+++ b/phlox/login.go
@@ -0,0 +1,56 @@
+package main
+
+import (
+ "fmt"
+ "net/http"
+ db "sanine.net/git/phlox/db"
+)
+
+
+func LoginUser(username, password string) (bool, db.Session, error) {
+ auth, user, err := p.AuthenticateUser(username, password)
+ if err != nil {
+ return false, db.Session{}, err
+ }
+ if auth == false {
+ return false, db.Session{}, nil
+ }
+ // auth was successful!
+ session, err := p.CreateSession(user)
+ if err != nil {
+ return false, db.Session{}, err
+ }
+ return true, session, nil
+}
+
+
+func LoginPostHandler(w http.ResponseWriter, r *http.Request) {
+ r.ParseForm()
+ username := r.Form.Get("username")
+ password := r.Form.Get("password")
+ redirect := r.Form.Get("redirect")
+
+ auth, session, err := LoginUser(username, password)
+ if err != nil {
+ // respond with error page
+ w.WriteHeader(http.StatusInternalServerError)
+ fmt.Fprintf(w, "an error was encountered when processing the request")
+ log.Error(err)
+ }
+
+ if !auth {
+ // not allowed!
+ w.WriteHeader(http.StatusUnauthorized)
+ fmt.Fprintf(w, "bad username or password")
+ log.Errorf("failed login for %v", username)
+ }
+
+ http.SetCookie(w, &http.Cookie{
+ Name: "phlox-session-id",
+ Value: session.Id,
+ SameSite: http.SameSiteLaxMode,
+ }
+
+ http.Header.Add("Location", redirect)
+ http.WriteHeader(http.StatusTemporaryRedirect)
+}