-
Notifications
You must be signed in to change notification settings - Fork 0
/
login.go
63 lines (48 loc) · 1.71 KB
/
login.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package handler
import (
"log"
"net/http"
"github.com/labstack/echo/v4"
"github.com/sparkymat/honey/auth"
"github.com/sparkymat/honey/internal/view"
"golang.org/x/crypto/bcrypt"
)
func Login(cfg ConfigService, _ DatabaseService) echo.HandlerFunc {
return func(c echo.Context) error {
return renderLoginPage(cfg, c, "", "")
}
}
func DoLogin(cfg ConfigService, db DatabaseService) echo.HandlerFunc {
return func(c echo.Context) error {
username := c.FormValue("username")
password := c.FormValue("password")
user, err := db.FetchUserByUsername(c.Request().Context(), username)
if err != nil {
log.Printf("failed to load user. err: %v", err)
return renderLoginPage(cfg, c, username, "Authentication failed")
}
if bcrypt.CompareHashAndPassword([]byte(user.EncryptedPassword), []byte(password)) != nil {
log.Printf("password does not match")
return renderLoginPage(cfg, c, username, "Authentication failed")
}
err = auth.SaveUsernameToSession(cfg, c, user.Username.String)
if err != nil {
log.Printf("failed to save email to session. err: %v", err)
return renderLoginPage(cfg, c, username, "Authentication failed")
}
//nolint:wrapcheck
return c.Redirect(http.StatusSeeOther, "/")
}
}
func renderLoginPage(cfg ConfigService, c echo.Context, email string, errorMessage string) error {
csrfToken := getCSRFToken(c)
if csrfToken == "" {
log.Print("error: csrf token not found")
//nolint:wrapcheck
return c.String(http.StatusInternalServerError, "server error")
}
pageHTML := view.Login(cfg.DisableRegistration(), csrfToken, email, errorMessage)
htmlString := view.Layout("honey | login", csrfToken, pageHTML)
//nolint:wrapcheck
return c.HTMLBlob(http.StatusOK, []byte(htmlString))
}