Creating handler to log in
This commit is contained in:
parent
d32fd432d2
commit
a6dca00199
@ -31,6 +31,7 @@ func routes(app *config.AppConfig) http.Handler {
|
||||
mux.Get("/choose-room/{id}", handlers.Repo.ChooseRoom)
|
||||
mux.Get("/book-room", handlers.Repo.BookRoom)
|
||||
mux.Get("/user/login", handlers.Repo.ShowLogin)
|
||||
mux.Post("/user/login", handlers.Repo.PostShowLogin)
|
||||
|
||||
fileServer := http.FileServer(http.Dir("./static/"))
|
||||
mux.Handle("/static/*", http.StripPrefix("/static", fileServer))
|
||||
|
@ -10,6 +10,7 @@ import (
|
||||
"go-udemy-web-1/internal/render"
|
||||
"go-udemy-web-1/internal/repository"
|
||||
"go-udemy-web-1/internal/repository/dbrepo"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@ -457,3 +458,37 @@ func (m *Repository) ShowLogin(w http.ResponseWriter, r *http.Request) {
|
||||
Form: forms.New(nil),
|
||||
})
|
||||
}
|
||||
|
||||
// PostShowLogin handles logging the user in
|
||||
func (m *Repository) PostShowLogin(w http.ResponseWriter, r *http.Request) {
|
||||
_ = m.App.Session.RenewToken(r.Context())
|
||||
|
||||
err := r.ParseForm()
|
||||
if err != nil {
|
||||
m.App.Session.Put(r.Context(), "error", "Can't parse form")
|
||||
http.Redirect(w, r, "/user/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
email := r.Form.Get("email")
|
||||
password := r.Form.Get("password")
|
||||
form := forms.New(r.PostForm)
|
||||
form.Required("email", "password")
|
||||
if !form.Valid() {
|
||||
// TODO
|
||||
http.Redirect(w, r, "/user/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
id, _, err := m.DB.Authenticate(email, password)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
m.App.Session.Put(r.Context(), "error", "Invalid login credentials")
|
||||
http.Redirect(w, r, "/user/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
m.App.Session.Put(r.Context(), "user_id", id)
|
||||
m.App.Session.Put(r.Context(), "flash", "Logged in successfully")
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
@ -4,7 +4,8 @@
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
<h1>Login</h1>
|
||||
<form>
|
||||
<form method="post" action="/user/login">
|
||||
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
|
||||
<div class="form-group mt-5">
|
||||
<label for="email">Email:</label>
|
||||
{{with .Form.Errors.Get "email"}}
|
||||
@ -21,10 +22,10 @@
|
||||
<input type="text" name="password" id="password" class="form-control {{with .Form.Errors.Get "password"}} is-invalid {{end}}"
|
||||
value="" required autocomplete="off">
|
||||
</div>
|
||||
</form>
|
||||
<hr>
|
||||
|
||||
<input type="submit" class="btn btn-primary" value="Submit">
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
Loading…
Reference in New Issue
Block a user