diff --git a/main.go b/main.go index 7151cb3..ab9e674 100644 --- a/main.go +++ b/main.go @@ -1,28 +1,70 @@ package main import ( + "context" + "crypto/md5" "fmt" "net/http" "net/http/cgi" - _ "os" + "faculty_media_report/dbi" "faculty_media_report/pages" ) -func handler(w http.ResponseWriter, r *http.Request) { +func writeHTML(w http.ResponseWriter, html string) { w.Header().Set("Content-Type", "text/html; charset=utf-8") - fmt.Fprint(w, pages.MainFormPage) + fmt.Fprint(w, html) } -func main() { - cgi.Serve(http.HandlerFunc(handler)) - /* - if os.Getenv("GATEWAY_INTERFACE") != "" { - cgi.Serve(http.HandlerFunc(handler)) - } else { - http.HandleFunc("/", handler) - fmt.Fprintln(os.Stderr, "Running in standalone mode on :9001") - http.ListenAndServe(":9001", nil) +func handleLoginGet(w http.ResponseWriter, r *http.Request) { + writeHTML(w, pages.LoginPage("")) +} + +func handleLoginPost(w http.ResponseWriter, r *http.Request) { + username := r.FormValue("username") + password := r.FormValue("password") + + fail := func() { + writeHTML(w, pages.LoginPage("Username or Password is incorrect.")) + } + + if username == "" || password == "" { + fail() + return + } + + db, err := dbi.GetDbConn() + if err != nil { + fail() + return + } + defer db.Close() + + conn, err := db.Conn(context.Background()) + if err != nil { + fail() + return + } + defer conn.Close() + + user, err := dbi.GetUser(conn, username) + if err != nil { + fail() + return + } + + hash := md5.Sum([]byte(password)) + if fmt.Sprintf("%x", hash) != user.Password { + fail() + return } - */ + + writeHTML(w, pages.MainFormPage) +} + +func main() { + mux := http.NewServeMux() + mux.HandleFunc("GET /activity/login", handleLoginGet) + mux.HandleFunc("POST /activity/login", handleLoginPost) + cgi.Serve(mux) }