funcloginHandler(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, "Method Not Supported", http.StatusMethodNotAllowed) return } // ParseForm parses the raw query from the URL and updates r.Form err := r.ParseForm() if err != nil { http.Error(w, "Please pass the data as URL form encoded", http.StatusBadRequest) return }
// Get username and password from the parsed form username := r.Form.Get("username") password := r.Form.Get("password")
// Check if user exists storedPassword, exists := users[username] if exists { // It returns a new session if the sessions doesn't exist session, _ := store.Get(r, "session.id") if storedPassword == password { session.Values["authenticated"] = true // Saves all sessions used during the current request session.Save(r, w) } else { http.Error(w, "Invalid Credentials", http.StatusUnauthorized) } w.Write([]byte("Login successfully!")) }
funclogoutHandler(w http.ResponseWriter, r *http.Request) { // Get registers and returns a session for the given name and session store. session, _ := store.Get(r, "session.id") // Set the authenticated value on the session to false session.Values["authenticated"] = false session.Save(r, w) w.Write([]byte("Logout Successful")) }