First pass at basic functionality.
This PR introduces the beginnings of Sprint Padawan. Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
+89
@@ -0,0 +1,89 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"sprintpadawan/lib"
|
||||
)
|
||||
|
||||
func handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
if isLoggedIn(r) {
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
renderTemplate(w, "login.html", nil)
|
||||
return
|
||||
}
|
||||
|
||||
username := r.FormValue("username")
|
||||
password := r.FormValue("password")
|
||||
|
||||
user, err := lib.GetUserByUsername(username)
|
||||
if err != nil || !lib.CheckPasswordHash(password, user.PasswordHash) {
|
||||
renderTemplate(w, "login.html", map[string]string{"Error": "Invalid credentials"})
|
||||
return
|
||||
}
|
||||
|
||||
sessionID, err := lib.CreateSession(user.ID)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to create session", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "session_token",
|
||||
Value: sessionID,
|
||||
Expires: time.Now().Add(24 * time.Hour),
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Path: "/",
|
||||
})
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
if isLoggedIn(r) {
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
renderTemplate(w, "register.html", nil)
|
||||
return
|
||||
}
|
||||
|
||||
username := r.FormValue("username")
|
||||
password := r.FormValue("password")
|
||||
confirm := r.FormValue("confirm_password")
|
||||
|
||||
if password != confirm {
|
||||
renderTemplate(w, "register.html", map[string]string{"Error": "Passwords do not match"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := lib.CreateUser(username, password); err != nil {
|
||||
renderTemplate(w, "register.html", map[string]string{"Error": "Username taken"})
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie("session_token")
|
||||
if err == nil {
|
||||
if err := lib.DeleteSession(cookie.Value); err != nil {
|
||||
log.Printf("delete session error: %v", err)
|
||||
}
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "session_token",
|
||||
Value: "",
|
||||
Expires: time.Now().Add(-1 * time.Hour),
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Path: "/",
|
||||
})
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
}
|
||||
Reference in New Issue
Block a user