Skip to content

Commit

Permalink
login and redister
Browse files Browse the repository at this point in the history
  • Loading branch information
mstgnz committed Jun 17, 2024
1 parent b4f4a74 commit b54c6db
Show file tree
Hide file tree
Showing 5 changed files with 96 additions and 34 deletions.
21 changes: 17 additions & 4 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,15 +216,28 @@ func main() {

func webAuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// get auth user in context
cUser, _ := r.Context().Value(config.CKey("user")).(*models.User)

if cUser == nil || cUser.ID == 0 {
cookie, err := r.Cookie("auth")
if err != nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}

next.ServeHTTP(w, r)
user := &models.User{}
user_id, err := strconv.Atoi(cookie.Value)
if err != nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}

err = user.GetWithId(user_id)
if err != nil {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}

ctx := context.WithValue(r.Context(), config.CKey("user"), user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}

Expand Down
69 changes: 54 additions & 15 deletions handler/web/user.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package web

import (
"context"
"encoding/json"
"net/http"
"strconv"
"time"

"github.com/mstgnz/cronjob/config"
"github.com/mstgnz/cronjob/models"
Expand All @@ -18,24 +20,47 @@ func (h *UserHandler) LoginHandler(w http.ResponseWriter, r *http.Request) error
case http.MethodGet:
return config.Render(w, "login", map[string]any{})
case http.MethodPost:

//email := r.FormValue("email")
//password := r.FormValue("password")

//statusCode, response := h.LoginService(w, r)
//return config.WriteJSON(w, statusCode, response)

user := &models.User{}
ctx := context.WithValue(r.Context(), config.CKey("user"), user)
r = r.WithContext(ctx)
http.Redirect(w, r, "/", http.StatusSeeOther)
code, response := h.LoginService(w, r)
if response.Status && code == http.StatusOK {
user, ok := response.Data["user"].(*models.User)
if ok && user.ID > 0 {
http.SetCookie(w, &http.Cookie{
Name: "auth",
Value: strconv.Itoa(user.ID),
Expires: time.Now().Add(12 * time.Hour),
})
}
}
json.NewEncoder(w).Encode(response)
return nil
default:
json.NewEncoder(w).Encode(map[string]any{"status": false, "message": "not supported request", "data": nil})
return nil
}
return nil
}

func (h *UserHandler) RegisterHandler(w http.ResponseWriter, r *http.Request) error {
data := map[string]any{}
return config.Render(w, "register", data)
switch r.Method {
case http.MethodGet:
return config.Render(w, "register", map[string]any{})
case http.MethodPost:
code, response := h.RegisterService(w, r)
if response.Status && code == http.StatusCreated {
user, ok := response.Data["user"].(*models.User)
if ok && user.ID > 0 {
http.SetCookie(w, &http.Cookie{
Name: "auth",
Value: strconv.Itoa(user.ID),
Expires: time.Now().Add(12 * time.Hour),
})
}
}
json.NewEncoder(w).Encode(response)
return nil
default:
json.NewEncoder(w).Encode(map[string]any{"status": false, "message": "not supported request", "data": nil})
return nil
}
}

func (h *UserHandler) HomeHandler(w http.ResponseWriter, _ *http.Request) error {
Expand All @@ -49,3 +74,17 @@ func (h *UserHandler) ListHandler(w http.ResponseWriter, _ *http.Request) error
func (h *UserHandler) ProfileHandler(w http.ResponseWriter, r *http.Request) error {
return config.Render(w, "profile", map[string]any{})
}

func (h *UserHandler) Logout(w http.ResponseWriter, r *http.Request) error {
cookie, err := r.Cookie("auth")
if err != nil {
http.Redirect(w, r, "/", http.StatusSeeOther)
return nil
}

cookie.MaxAge = -1
http.SetCookie(w, cookie)

http.Redirect(w, r, "/", http.StatusSeeOther)
return nil
}
2 changes: 1 addition & 1 deletion models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ type UserRegister struct {
Fullname string `json:"fullname" validate:"required"`
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=6"`
Phone string `json:"phone"`
Phone string `json:"phone" validate:"required,e164"`
}

type UserPasswordUpdate struct {
Expand Down
12 changes: 11 additions & 1 deletion views/pages/login.gohtml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
{{define "content"}}
<div class="bg-white p-8 rounded-lg shadow-md w-96">
<h2 class="text-xl mb-4">Sign In</h2>
<form method="post" action="/login" novalidate autocomplete="off">
<form hx-post="/login" hx-target="#toast" hx-ext="json-enc" hx-on="htmx:afterRequest: handleLoginResponse(event)" novalidate autocomplete="off">
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="email">
Email
Expand All @@ -22,6 +22,16 @@
</button>
<span class="ml-4">please <a href="register">register</a> if you don't have an account.</span>
</div>
<span id="toast"></span>
</form>
</div>
<script>
function handleLoginResponse(event) {
const response = JSON.parse(event.detail.xhr.response);
document.querySelector('#toast').innerHTML = response.message;
if (response.status) {
window.location.href = "/";
}
}
</script>
{{end}}
26 changes: 13 additions & 13 deletions views/pages/register.gohtml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
{{define "content"}}
<div class="bg-white p-8 rounded-lg shadow-md w-96">
<h2 class="text-xl mb-4">Sign Up</h2>
{{/* <form hx-post="/register" hx-ext="json-enc" novalidate autocomplete="off"> */}}
<form method="post" action="/register" novalidate autocomplete="off">
<form hx-post="/register" hx-target="#toast" hx-ext="json-enc" novalidate autocomplete="off">
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="email">
Fullname
Expand All @@ -17,6 +16,12 @@
</label>
<input type="email" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="email" name="email" required>
</div>
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="phone">
Phone
</label>
<input type="text" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="phone" name="phone" required>
</div>
<div class="mb-6">
<label class="block text-gray-700 text-sm font-bold mb-2" for="password">
Password
Expand All @@ -29,24 +34,19 @@
</button>
<span class="ml-4">please <a href="login">login</a> if you have an account.</span>
</div>
<div class="flex items-center justify-between">
<span class="ml-4">{{.status}}</span>
<span class="ml-4">{{.message}}</span>
</div>
<span id="toast"></span>
</form>
</div>
{{end}}

{{define "js"}}
<script>
{{/* document.body.addEventListener('htmx:afterRequest', function(evt) {
document.body.addEventListener('htmx:afterRequest', function(evt) {
const response = JSON.parse(evt.detail.xhr.response)
if(response.status){
localStorage.setItem("access_token",response.data)
window.location.url = "/"
return
document.querySelector('#toast').innerHTML = response.message;
if (response.status) {
window.location.href = "/";
}
alert(response.message)
}); */}}
});
</script>
{{end}}

0 comments on commit b54c6db

Please sign in to comment.