Login Flow
In this commit I added: More pages like history, personal data and editor with dummy content A HTMX login flow The login flow is mostly backend, I think there's nothing on the frontend made to support it. Pretty neat if I say so myself
This commit is contained in:
@@ -2,31 +2,79 @@ package controllers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"thermalFax/models"
|
||||
"thermalFax/scache"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
)
|
||||
|
||||
func isAuthenticated(r *http.Request) (bool, string) {
|
||||
var (
|
||||
SESSION_INTERVAL = 2 * time.Minute
|
||||
)
|
||||
|
||||
func getToken(r *http.Request, tokenName string) *http.Cookie {
|
||||
cookies := r.Cookies()
|
||||
for _, c := range cookies {
|
||||
if c.Name == "token" {
|
||||
// Check if the token exists and if its date is valid
|
||||
expirationTime := time.Now()
|
||||
return expirationTime.Unix() >= c.Expires.Unix(), c.Value
|
||||
if c.Name == tokenName {
|
||||
return c
|
||||
}
|
||||
}
|
||||
|
||||
return false, ""
|
||||
return nil
|
||||
}
|
||||
|
||||
func isAuthenticated(r *http.Request) (bool, string) {
|
||||
token := getToken(r, "token")
|
||||
if token == nil {
|
||||
return false, ""
|
||||
}
|
||||
|
||||
expirationTime := time.Now()
|
||||
return expirationTime.Unix() >= token.Expires.Unix(), token.Value
|
||||
}
|
||||
|
||||
func createAuthCookie(loginForm models.LoginForm) (*http.Cookie, error) {
|
||||
expirationTime := time.Now().Add(SESSION_INTERVAL)
|
||||
claims := models.Claims{
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: loginForm.Username,
|
||||
ExpiresAt: jwt.NewNumericDate(expirationTime),
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenString, err := token.SignedString([]byte("secret"))
|
||||
if err != nil {
|
||||
errStr := fmt.Sprintf("Failed to create the token: %s", err)
|
||||
return nil, errors.New(errStr)
|
||||
}
|
||||
|
||||
cookie := http.Cookie{
|
||||
Name: "token",
|
||||
Value: tokenString,
|
||||
Expires: expirationTime,
|
||||
}
|
||||
|
||||
return &cookie, nil
|
||||
}
|
||||
|
||||
func createSessionCookie(token string) *http.Cookie {
|
||||
sessionCookie := http.Cookie{
|
||||
Name: "fax-session",
|
||||
Value: token,
|
||||
}
|
||||
|
||||
return &sessionCookie
|
||||
}
|
||||
|
||||
func Authenticate(w http.ResponseWriter, r *http.Request) {
|
||||
// first we have to verify if this request brings any login data
|
||||
// Otherwise we login, which we will do everytime lmao
|
||||
|
||||
data, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
@@ -48,36 +96,92 @@ func Authenticate(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Generate the thing
|
||||
expirationTime := time.Now().Add(2 * time.Minute)
|
||||
claims := models.Claims{
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
Subject: loginForm.Username,
|
||||
ExpiresAt: jwt.NewNumericDate(expirationTime),
|
||||
},
|
||||
// First check if there is an active session
|
||||
sessionCookie := getToken(r, "fax-session")
|
||||
userReqSession := false
|
||||
if sessionCookie != nil {
|
||||
userReqSession = true
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenString, err := token.SignedString([]byte("secret"))
|
||||
if err != nil {
|
||||
log.Printf("Failed to create the token.")
|
||||
return
|
||||
// If there is an active session we update the current session
|
||||
if userReqSession {
|
||||
// Update current session
|
||||
localUserSession := models.GetSession(sessionCookie.Value)
|
||||
if localUserSession == nil {
|
||||
log.Panicln("| But what happened should not have happened. Blame the user")
|
||||
}
|
||||
|
||||
expirationTime := time.Now().Add(SESSION_INTERVAL)
|
||||
cookie := http.Cookie{
|
||||
Name: "token",
|
||||
Value: sessionCookie.Value,
|
||||
Expires: expirationTime,
|
||||
}
|
||||
http.SetCookie(w, &cookie)
|
||||
|
||||
// w.Header().Set("HX-Redirect", localUserSession.Wants)
|
||||
w.Header().Set("Content-Type", "text/json")
|
||||
w.Write([]byte(`
|
||||
{
|
||||
"state":"success",
|
||||
"page":"` + localUserSession.Wants + `"
|
||||
}
|
||||
`))
|
||||
} else {
|
||||
// Create a new session
|
||||
authCookie, err := createAuthCookie(loginForm)
|
||||
if err != nil {
|
||||
log.Printf("Error: %s", err)
|
||||
return
|
||||
}
|
||||
http.SetCookie(w, authCookie)
|
||||
|
||||
sessionCookie := createSessionCookie(authCookie.Value)
|
||||
http.SetCookie(w, sessionCookie)
|
||||
|
||||
// Store the auth token in the database
|
||||
err = models.StoreAuthToken(authCookie.Value, loginForm.Username, authCookie.Expires.Unix())
|
||||
if err != nil {
|
||||
log.Println("Failed to store auth token: ", err)
|
||||
return
|
||||
}
|
||||
|
||||
// Store the session token in the cache
|
||||
err = models.StoreSessionToken(authCookie.Value)
|
||||
if err != nil {
|
||||
log.Println("Failed to store session token: ", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf(`| {"user": %s, "time": %d}`, loginForm.Username, time.Now().Unix())
|
||||
|
||||
w.Header().Set("Content-Type", "text/json")
|
||||
w.Write([]byte(`
|
||||
{
|
||||
"state":"success",
|
||||
"page":"` + "/editor" + `"
|
||||
}
|
||||
`))
|
||||
}
|
||||
}
|
||||
|
||||
cookie := http.Cookie{
|
||||
Name: "token",
|
||||
Value: tokenString,
|
||||
Expires: expirationTime,
|
||||
func reauth(w http.ResponseWriter, r *http.Request) {
|
||||
cache := scache.GetInstance()
|
||||
cookie := getToken(r, "fax-session")
|
||||
if cookie == nil {
|
||||
log.Println("The cookie is nil. It should not be")
|
||||
}
|
||||
http.SetCookie(w, &cookie)
|
||||
|
||||
err = models.StoreSessionToken(tokenString, loginForm.Username, expirationTime.Unix())
|
||||
if err != nil {
|
||||
log.Fatal("Failed to store session token: ", err)
|
||||
if cookie != nil {
|
||||
tok := cookie.Value
|
||||
|
||||
if _, ok := cache.Data[tok]; !ok {
|
||||
session := &scache.Session{}
|
||||
cache.Data[tok] = session
|
||||
}
|
||||
|
||||
cache.Data[tok].Wants = r.RequestURI
|
||||
}
|
||||
|
||||
log.Printf(`| {"user": %s, "time": %d}`, loginForm.Username, time.Now().Unix())
|
||||
|
||||
w.Header().Set("Content-Type", "text/json")
|
||||
w.Write([]byte("{\"state\":\"success\"}"))
|
||||
w.Header().Set("HX-Redirect", "/login")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user