187 lines
4.2 KiB
Go
187 lines
4.2 KiB
Go
package controllers
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"thermalFax/models"
|
|
"thermalFax/scache"
|
|
"thermalFax/views"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v4"
|
|
)
|
|
|
|
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 == tokenName {
|
|
return c
|
|
}
|
|
}
|
|
|
|
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 createNewSession(w http.ResponseWriter, loginForm models.LoginForm) {
|
|
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().Add("HX-Redirect", "/editor")
|
|
}
|
|
|
|
func updateSession(w http.ResponseWriter, loginForm models.LoginForm,
|
|
sessionCookie *http.Cookie) {
|
|
localUserSession := models.GetSession(sessionCookie.Value)
|
|
if localUserSession == nil {
|
|
// Just create a new session in this case
|
|
createNewSession(w, loginForm)
|
|
return
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
func Authenticate(w http.ResponseWriter, r *http.Request) {
|
|
// DELETE THIS AFTER TESTING AND SO ON
|
|
time.Sleep(1 * time.Second)
|
|
|
|
// first we have to verify if this request brings any login data
|
|
r.ParseForm()
|
|
loginForm := models.LoginForm{
|
|
Username: r.FormValue("login-user"),
|
|
Password: r.FormValue("login-pass"),
|
|
}
|
|
|
|
if !models.ValidateCredentials(&loginForm) {
|
|
w.Header().Add("HX-Trigger", `{"wrongCredentials":"Wrong Credentials"}`)
|
|
return
|
|
}
|
|
|
|
// First check if there is an active session
|
|
sessionCookie := getToken(r, "fax-session")
|
|
userReqSession := false
|
|
if sessionCookie != nil {
|
|
userReqSession = true
|
|
}
|
|
|
|
// If there is an active session we update the current session
|
|
if userReqSession {
|
|
// Update current session
|
|
updateSession(w, loginForm, sessionCookie)
|
|
} else {
|
|
// Create a new session
|
|
createNewSession(w, loginForm)
|
|
}
|
|
}
|
|
|
|
func saveSessionState(r *http.Request) {
|
|
cache := scache.GetInstance()
|
|
cookie := getToken(r, "fax-session")
|
|
if cookie == nil {
|
|
log.Println("The cookie is nil. It should not be")
|
|
}
|
|
|
|
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
|
|
}
|
|
}
|
|
|
|
func reauth(w http.ResponseWriter, r *http.Request) {
|
|
saveSessionState(r)
|
|
w.Header().Set("HX-Redirect", "/login")
|
|
w.Header().Set("HX-Push-Url", "true")
|
|
}
|
|
|
|
func relogin(w http.ResponseWriter, r *http.Request) {
|
|
saveSessionState(r)
|
|
views.LoginPage(w, r)
|
|
}
|