Passed
Pull Request — main (#166)
by Yume
02:03
created

app/v2/handlers/auth.go   A

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 34
dl 0
loc 54
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A handlers.NewAuthController 0 2 1
A handlers.*AuthController.PostLogin 0 27 2
1
package handlers
2
3
import (
4
	"context"
5
	"log/slog"
6
	"net/http"
7
	"time"
8
9
	"github.com/labstack/echo/v4"
10
	"github.com/memnix/memnix-rest/app/v2/views/components"
11
	"github.com/memnix/memnix-rest/services/auth"
12
)
13
14
type AuthController struct {
15
	useCase auth.IUseCase
16
}
17
18
const (
19
	// SessionTokenCookieKey is the key for the session token cookie.
20
	SessionTokenCookieKey = "session_token"
21
	ExpiresDuration       = 24 * time.Hour
22
)
23
24
func NewAuthController(auth auth.IUseCase) AuthController {
25
	return AuthController{useCase: auth}
26
}
27
28
func (a *AuthController) PostLogin(c echo.Context) error {
29
	// Get the username and password from the request
30
	email := c.FormValue("email")
31
	password := c.FormValue("password")
32
33
	slog.Info("Auth: ", slog.String("email", email), slog.String("password", password))
34
35
	// Call the use case to authenticate the user
36
	jwtToken, err := a.useCase.Login(context.Background(), password, email)
37
	if err != nil {
38
		loginError := components.LoginError("Invalid email or password")
39
		slog.Info("Auth: ", slog.String("error", err.Error()))
40
		return Render(c, http.StatusForbidden, loginError)
41
	}
42
43
	cookie := &http.Cookie{
44
		Name:     SessionTokenCookieKey,
45
		Value:    jwtToken,
46
		Path:     "/",
47
		Expires:  time.Now().Add(ExpiresDuration),
48
		HttpOnly: true,
49
		Secure:   true,
50
		SameSite: http.SameSiteLaxMode,
51
	}
52
	c.SetCookie(cookie)
53
54
	return c.Redirect(http.StatusFound, "/")
55
}
56