#73 add sign out
All checks were successful
Build Docker Image / Explore-Gitea-Actions (push) Successful in 48s
All checks were successful
Build Docker Image / Explore-Gitea-Actions (push) Successful in 48s
This commit is contained in:
20
handler.go
20
handler.go
@@ -11,21 +11,21 @@ import (
|
|||||||
func getHandler(db *sql.DB) http.Handler {
|
func getHandler(db *sql.DB) http.Handler {
|
||||||
var router = http.NewServeMux()
|
var router = http.NewServeMux()
|
||||||
|
|
||||||
router.HandleFunc("/", service.HandleIndexAnd404)
|
router.HandleFunc("/", service.HandleIndexAnd404(db))
|
||||||
|
|
||||||
// Serve static files (CSS, JS and images)
|
// Serve static files (CSS, JS and images)
|
||||||
router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
|
router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
|
||||||
|
|
||||||
router.HandleFunc("/app", service.WorkoutPage)
|
router.HandleFunc("/app", service.HandleWorkoutPage(db))
|
||||||
router.HandleFunc("POST /api/workout", service.NewWorkout(db))
|
router.HandleFunc("POST /api/workout", service.HandleNewWorkout(db))
|
||||||
router.HandleFunc("GET /api/workout", service.GetWorkouts(db))
|
router.HandleFunc("GET /api/workout", service.HandleGetWorkouts(db))
|
||||||
router.HandleFunc("DELETE /api/workout", service.DeleteWorkout(db))
|
router.HandleFunc("DELETE /api/workout", service.HandleDeleteWorkout(db))
|
||||||
|
|
||||||
router.HandleFunc("/auth/signin", service.SignInPage)
|
router.HandleFunc("/auth/signin", service.HandleSignInPage(db))
|
||||||
router.HandleFunc("/auth/signup", service.SignUpPage)
|
router.HandleFunc("/auth/signup", service.HandleSignUpPage(db))
|
||||||
router.HandleFunc("/api/auth/signup", service.SignUp(db))
|
router.HandleFunc("/api/auth/signup", service.HandleSignUp(db))
|
||||||
router.HandleFunc("/api/auth/signin", service.SignIn(db))
|
router.HandleFunc("/api/auth/signin", service.HandleSignIn(db))
|
||||||
router.HandleFunc("/api/auth/userinfo", service.UserInfoComp(db))
|
router.HandleFunc("/api/auth/signout", service.HandleSignOutComp(db))
|
||||||
|
|
||||||
return middleware.Logging(middleware.EnableCors(router))
|
return middleware.Logging(middleware.EnableCors(router))
|
||||||
}
|
}
|
||||||
|
|||||||
113
service/auth.go
113
service/auth.go
@@ -14,27 +14,42 @@ import (
|
|||||||
"me-fit/template"
|
"me-fit/template"
|
||||||
"me-fit/template/auth"
|
"me-fit/template/auth"
|
||||||
|
|
||||||
|
"github.com/a-h/templ"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"golang.org/x/crypto/argon2"
|
"golang.org/x/crypto/argon2"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SignInPage(w http.ResponseWriter, r *http.Request) {
|
type User struct {
|
||||||
signIn := auth.SignInOrUp(true)
|
user_uuid uuid.UUID
|
||||||
template.Layout(signIn).Render(r.Context(), w)
|
email string
|
||||||
}
|
}
|
||||||
|
|
||||||
func SignUpPage(w http.ResponseWriter, r *http.Request) {
|
func HandleSignInPage(db *sql.DB) http.HandlerFunc {
|
||||||
signIn := auth.SignInOrUp(false)
|
|
||||||
template.Layout(signIn).Render(r.Context(), w)
|
|
||||||
}
|
|
||||||
|
|
||||||
func UserInfoComp(db *sql.DB) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
//TODO
|
user_comp := UserInfoComp(verifySessionAndReturnUser(db, r))
|
||||||
|
signIn := auth.SignInOrUp(true)
|
||||||
|
template.Layout(signIn, user_comp).Render(r.Context(), w)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func SignUp(db *sql.DB) http.HandlerFunc {
|
func HandleSignUpPage(db *sql.DB) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
user_comp := UserInfoComp(verifySessionAndReturnUser(db, r))
|
||||||
|
signIn := auth.SignInOrUp(false)
|
||||||
|
template.Layout(signIn, user_comp).Render(r.Context(), w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func UserInfoComp(user *User) templ.Component {
|
||||||
|
|
||||||
|
if user != nil {
|
||||||
|
return auth.UserComp(user.email)
|
||||||
|
} else {
|
||||||
|
return auth.UserComp("")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleSignUp(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
var email = r.FormValue("email")
|
var email = r.FormValue("email")
|
||||||
var password = r.FormValue("password")
|
var password = r.FormValue("password")
|
||||||
@@ -78,16 +93,16 @@ func SignUp(db *sql.DB) http.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
result := tryCreateSessionAndSetCookie(r, w, db, user_uuid)
|
result := tryCreateSessionAndSetCookie(w, db, user_uuid)
|
||||||
if !result {
|
if !result {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
w.WriteHeader(http.StatusOK)
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func SignIn(db *sql.DB) http.HandlerFunc {
|
func HandleSignIn(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
var email = r.FormValue("email")
|
var email = r.FormValue("email")
|
||||||
var password = r.FormValue("password")
|
var password = r.FormValue("password")
|
||||||
@@ -112,14 +127,14 @@ func SignIn(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if result {
|
if result {
|
||||||
result := tryCreateSessionAndSetCookie(r, w, db, user_uuid)
|
result := tryCreateSessionAndSetCookie(w, db, user_uuid)
|
||||||
if !result {
|
if !result {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
duration := time.Since(start)
|
duration := time.Since(start)
|
||||||
time_to_wait := 300 - duration.Milliseconds()
|
time_to_wait := 100 - duration.Milliseconds()
|
||||||
// It is important to sleep for a while to prevent timing attacks
|
// It is important to sleep for a while to prevent timing attacks
|
||||||
// If the email is correct, the server will calculate the hash, which will take some time
|
// If the email is correct, the server will calculate the hash, which will take some time
|
||||||
// This way an attacker could guess emails when comparing the response time
|
// This way an attacker could guess emails when comparing the response time
|
||||||
@@ -127,13 +142,39 @@ func SignIn(db *sql.DB) http.HandlerFunc {
|
|||||||
time.Sleep(time.Duration(time_to_wait) * time.Millisecond)
|
time.Sleep(time.Duration(time_to_wait) * time.Millisecond)
|
||||||
|
|
||||||
if result {
|
if result {
|
||||||
w.WriteHeader(http.StatusOK)
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||||
} else {
|
} else {
|
||||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func HandleSignOutComp(db *sql.DB) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id := getSessionID(r)
|
||||||
|
|
||||||
|
_, err := db.Exec("DELETE FROM session WHERE session_id = ?", id)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Could not delete session: %v", err)
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c := http.Cookie{
|
||||||
|
Name: "id",
|
||||||
|
Value: "",
|
||||||
|
MaxAge: -1,
|
||||||
|
Secure: true,
|
||||||
|
HttpOnly: true,
|
||||||
|
SameSite: http.SameSiteStrictMode,
|
||||||
|
Path: "/",
|
||||||
|
}
|
||||||
|
|
||||||
|
http.SetCookie(w, &c)
|
||||||
|
auth.UserComp("").Render(r.Context(), w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// var (
|
// var (
|
||||||
// metricsAuthSignUp = promauto.NewCounterVec(
|
// metricsAuthSignUp = promauto.NewCounterVec(
|
||||||
// prometheus.CounterOpts{
|
// prometheus.CounterOpts{
|
||||||
@@ -159,7 +200,7 @@ func SignIn(db *sql.DB) http.HandlerFunc {
|
|||||||
// // )
|
// // )
|
||||||
// )
|
// )
|
||||||
|
|
||||||
func tryCreateSessionAndSetCookie(r *http.Request, w http.ResponseWriter, db *sql.DB, user_uuid uuid.UUID) bool {
|
func tryCreateSessionAndSetCookie(w http.ResponseWriter, db *sql.DB, user_uuid uuid.UUID) bool {
|
||||||
var session_id_bytes []byte = make([]byte, 32)
|
var session_id_bytes []byte = make([]byte, 32)
|
||||||
_, err := rand.Reader.Read(session_id_bytes)
|
_, err := rand.Reader.Read(session_id_bytes)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -190,6 +231,42 @@ func tryCreateSessionAndSetCookie(r *http.Request, w http.ResponseWriter, db *sq
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getSessionID(r *http.Request) string {
|
||||||
|
for _, c := range r.Cookies() {
|
||||||
|
if c.Name == "id" {
|
||||||
|
return c.Value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifySessionAndReturnUser(db *sql.DB, r *http.Request) *User {
|
||||||
|
session_id := getSessionID(r)
|
||||||
|
if session_id == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var user User
|
||||||
|
var created_at time.Time
|
||||||
|
|
||||||
|
err := db.QueryRow(`
|
||||||
|
SELECT u.user_uuid, u.email, s.created_at
|
||||||
|
FROM session s
|
||||||
|
INNER JOIN user u ON s.user_uuid = u.user_uuid
|
||||||
|
WHERE session_id = ?`, session_id).Scan(&user.user_uuid, &user.email, &created_at)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Could not verify session: %v", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Test
|
||||||
|
// if created_at.Add(time.Duration(8 * time.Hour)).Before(time.Now()) {
|
||||||
|
// return nil
|
||||||
|
// }
|
||||||
|
|
||||||
|
return &user
|
||||||
|
}
|
||||||
|
|
||||||
func getHashPassword(password string, salt []byte) []byte {
|
func getHashPassword(password string, salt []byte) []byte {
|
||||||
return argon2.IDKey([]byte(password), salt, 1, 64*1024, 1, 16)
|
return argon2.IDKey([]byte(password), salt, 1, 64*1024, 1, 16)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,25 @@
|
|||||||
package service
|
package service
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"database/sql"
|
||||||
"me-fit/template"
|
"me-fit/template"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/a-h/templ"
|
"github.com/a-h/templ"
|
||||||
)
|
)
|
||||||
|
|
||||||
func HandleIndexAnd404(w http.ResponseWriter, r *http.Request) {
|
func HandleIndexAnd404(db *sql.DB) http.HandlerFunc {
|
||||||
var comp templ.Component = nil
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.URL.Path != "/" {
|
var comp templ.Component = nil
|
||||||
comp = template.Layout(template.NotFound())
|
user_comp := UserInfoComp(verifySessionAndReturnUser(db, r))
|
||||||
w.WriteHeader(http.StatusNotFound)
|
|
||||||
} else {
|
|
||||||
comp = template.Layout(template.Index())
|
|
||||||
}
|
|
||||||
|
|
||||||
comp.Render(r.Context(), w)
|
if r.URL.Path != "/" {
|
||||||
|
comp = template.Layout(template.NotFound(), user_comp)
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
} else {
|
||||||
|
comp = template.Layout(template.Index(), user_comp)
|
||||||
|
}
|
||||||
|
|
||||||
|
comp.Render(r.Context(), w)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,13 +23,16 @@ var (
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
func WorkoutPage(w http.ResponseWriter, r *http.Request) {
|
func HandleWorkoutPage(db *sql.DB) http.HandlerFunc {
|
||||||
comp := template.App()
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
layout := template.Layout(comp)
|
inner := template.App()
|
||||||
layout.Render(r.Context(), w)
|
user_comp := UserInfoComp(verifySessionAndReturnUser(db, r))
|
||||||
|
layout := template.Layout(inner, user_comp)
|
||||||
|
layout.Render(r.Context(), w)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewWorkout(db *sql.DB) http.HandlerFunc {
|
func HandleNewWorkout(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
metrics.WithLabelValues("new").Inc()
|
metrics.WithLabelValues("new").Inc()
|
||||||
|
|
||||||
@@ -73,7 +76,7 @@ func NewWorkout(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetWorkouts(db *sql.DB) http.HandlerFunc {
|
func HandleGetWorkouts(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
metrics.WithLabelValues("get").Inc()
|
metrics.WithLabelValues("get").Inc()
|
||||||
|
|
||||||
@@ -115,7 +118,7 @@ func GetWorkouts(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func DeleteWorkout(db *sql.DB) http.HandlerFunc {
|
func HandleDeleteWorkout(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
metrics.WithLabelValues("delete").Inc()
|
metrics.WithLabelValues("delete").Inc()
|
||||||
|
|
||||||
|
|||||||
@@ -5,9 +5,9 @@ templ SignInOrUp(isSignIn bool) {
|
|||||||
class="max-w-xl px-2 mx-auto flex flex-col gap-4 h-full justify-center"
|
class="max-w-xl px-2 mx-auto flex flex-col gap-4 h-full justify-center"
|
||||||
method="POST"
|
method="POST"
|
||||||
if isSignIn {
|
if isSignIn {
|
||||||
hx-post="/api/auth/signin"
|
action="/api/auth/signin"
|
||||||
} else {
|
} else {
|
||||||
hx-post="/api/auth/signup"
|
action="/api/auth/signup"
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<h2 class="text-6xl mb-10">
|
<h2 class="text-6xl mb-10">
|
||||||
|
|||||||
14
template/auth/user.templ
Normal file
14
template/auth/user.templ
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
templ UserComp(user string) {
|
||||||
|
<div id="user-info" class="flex gap-5">
|
||||||
|
if user != "" {
|
||||||
|
<a hx-get="/api/auth/signout" hx-target="#user-info" class="btn btn-sm">Sign Out</a>
|
||||||
|
<!-- <a href="/api/auth/signout" class="btn btn-sm">Sign Out</a> -->
|
||||||
|
{ user }
|
||||||
|
} else {
|
||||||
|
<a href="/auth/signup" class="btn btn-sm">Sign Up</a>
|
||||||
|
<a href="/auth/signin" class="btn btn-sm">Sign In</a>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
package template
|
package template
|
||||||
|
|
||||||
templ Layout(comp templ.Component) {
|
templ Layout(slot templ.Component, user templ.Component) {
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
@@ -19,12 +19,11 @@ templ Layout(comp templ.Component) {
|
|||||||
<img src="/static/favicon.svg" alt="ME-FIT logo"/>
|
<img src="/static/favicon.svg" alt="ME-FIT logo"/>
|
||||||
<span>ME-FIT</span>
|
<span>ME-FIT</span>
|
||||||
</a>
|
</a>
|
||||||
<a href="/auth/signup" class="btn btn-sm">Sign Up</a>
|
@user
|
||||||
<a href="/auth/signin" class="btn btn-sm">Sign In</a>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="flex-1">
|
<div class="flex-1">
|
||||||
if comp != nil {
|
if slot != nil {
|
||||||
@comp
|
@slot
|
||||||
}
|
}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user