can store token after login

This commit is contained in:
Ruidy 2024-05-10 23:01:50 +02:00
parent aa5ac4dace
commit e673acb5c2
No known key found for this signature in database
GPG key ID: E00F51288CB857CC
6 changed files with 22 additions and 37 deletions

View file

@ -3,12 +3,10 @@ package server
import (
"net/http"
"os"
"strconv"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
"github.com/labstack/gommon/log"
)
const (
@ -20,7 +18,6 @@ var validityTime = time.Now().Add(time.Hour * 24)
type Claims struct {
jwt.RegisteredClaims
Id int `json:"id"`
}
func MakeAuthMiddleware(secretKey string) echo.MiddlewareFunc {
@ -45,47 +42,26 @@ func MakeAuthMiddleware(secretKey string) echo.MiddlewareFunc {
return c.Redirect(http.StatusSeeOther, routeLogin)
}
var id int
switch v := token.Claims.(jwt.MapClaims)["id"].(type) {
case int:
id = v
case string:
id, err = strconv.Atoi(token.Claims.(jwt.MapClaims)["id"].(string))
if err != nil {
return c.Redirect(http.StatusSeeOther, routeLogin)
}
case float64:
id = int(v)
default:
log.Errorf("id %v is of type %T", v, v)
return c.Redirect(http.StatusSeeOther, routeLogin)
}
email, err := token.Claims.GetSubject()
_, err = token.Claims.GetSubject()
if err != nil {
return c.Redirect(http.StatusSeeOther, routeLogin)
}
log.Printf("id: %d, email: %q", id, email)
//c.Set("user", services.User{Id: id, Email: email, PaymentValid: paymentValid})
return next(c)
}
}
}
// refactor to use a `AuthService`
func writeCookie(c echo.Context, userId int, email string) error {
// TODO: refactor to use a `AuthService`
func writeCookie(c echo.Context, email string) error {
claims := &Claims{
jwt.RegisteredClaims{
Subject: email,
ExpiresAt: jwt.NewNumericDate(validityTime),
},
userId,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signedToken, err := token.SignedString(os.Getenv("SECRET_KEY"))
signedToken, err := token.SignedString([]byte(os.Getenv("SECRET_KEY")))
if err != nil {
return err
}

View file

@ -1,8 +1,10 @@
package server
import (
"errors"
"fmt"
"net/http"
"os"
"github.com/labstack/echo/v4"
@ -15,18 +17,25 @@ func handleLoginPage() echo.HandlerFunc {
}
}
// TODO: move to auth service
func signIn(email, pwd string) error {
if email != os.Getenv("ADMIN") || pwd != os.Getenv("ADMIN_PASSWORD") {
return errors.New("unauthorized")
}
return nil
}
func handleLogin() echo.HandlerFunc {
return func(c echo.Context) error {
email := c.FormValue("email")
_ = c.FormValue("password")
pwd := c.FormValue("password")
//user, err := s.us.SignIn(email, pwd)
user := struct{ Id int }{Id: 1}
var err error = nil
err := signIn(email, pwd)
if err != nil {
return c.Redirect(http.StatusSeeOther, fmt.Sprintf("%s?err=invalid+credentials", "/login"))
}
if err = writeCookie(c, user.Id, email); err != nil {
if err = writeCookie(c, email); err != nil {
return c.Redirect(http.StatusSeeOther, fmt.Sprintf("%s?err=invalid+credentials", "/login"))
}
return c.Redirect(http.StatusFound, "/bookings")

View file

@ -2,7 +2,7 @@ package layout
templ BaseLayout() {
<!DOCTYPE html>
<html lang="en" data-theme="light">
<html lang="en">
<head>
<title>RentEase | Your Property Management System</title>
<meta charset="UTF-8"/>

View file

@ -23,7 +23,7 @@ func BaseLayout() templ.Component {
templ_7745c5c3_Var1 = templ.NopComponent
}
ctx = templ.ClearChildren(ctx)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<!doctype html><html lang=\"en\" data-theme=\"light\"><head><title>RentEase | Your Property Management System</title><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><meta name=\"description\" content=\"AI assistant to help you improve your management\"><link rel=\"icon\" href=\"/static/icons/favicon-main.png\"><link rel=\"stylesheet\" href=\"/static/css/pico.min.css\"><script src=\"/static/js/htmx.js\" defer></script></head><body hx-boost=\"true\"><nav class=\"container-fluid\"><ul><li><a href=\"/\"><b>🏨 RentEase </b></a></li></ul><ul><li><a href=\"/bookings\">Bookings</a></li><li><a href=\"/reports\">Reports</a></li><li><a href=\"/bookings/new\" role=\"button\">New Booking</a></li></ul></nav><main class=\"container\">")
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<!doctype html><html lang=\"en\"><head><title>RentEase | Your Property Management System</title><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><meta name=\"description\" content=\"AI assistant to help you improve your management\"><link rel=\"icon\" href=\"/static/icons/favicon-main.png\"><link rel=\"stylesheet\" href=\"/static/css/pico.min.css\"><script src=\"/static/js/htmx.js\" defer></script></head><body hx-boost=\"true\"><nav class=\"container-fluid\"><ul><li><a href=\"/\"><b>🏨 RentEase </b></a></li></ul><ul><li><a href=\"/bookings\">Bookings</a></li><li><a href=\"/reports\">Reports</a></li><li><a href=\"/bookings/new\" role=\"button\">New Booking</a></li></ul></nav><main class=\"container\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}

View file

@ -9,7 +9,7 @@ templ Login() {
<main class="container">
<section>
<h1>Login</h1>
<form>
<form method="POST">
<input
type="email"
name="email"

View file

@ -33,7 +33,7 @@ func Login() templ.Component {
templ_7745c5c3_Buffer = templ.GetBuffer()
defer templ.ReleaseBuffer(templ_7745c5c3_Buffer)
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<main class=\"container\"><section><h1>Login</h1><form><input type=\"email\" name=\"email\" placeholder=\"john@email.com\" aria-label=\"email\" autocomplete=\"email\" required> <input type=\"password\" name=\"password\" placeholder=\"p4Ssw0rD\" aria-label=\"password\" autocomplete=\"password\" required> <button type=\"submit\">Log in</button></form></section></main>")
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<main class=\"container\"><section><h1>Login</h1><form method=\"POST\"><input type=\"email\" name=\"email\" placeholder=\"john@email.com\" aria-label=\"email\" autocomplete=\"email\" required> <input type=\"password\" name=\"password\" placeholder=\"p4Ssw0rD\" aria-label=\"password\" autocomplete=\"password\" required> <button type=\"submit\">Log in</button></form></section></main>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}