-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
83 lines (67 loc) · 1.7 KB
/
session.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package authservice
import (
"net/http"
"github.com/eeroleppalehto/go_gallery/models"
"github.com/gorilla/sessions"
"github.com/labstack/echo/v4"
)
var (
key = []byte("super-secret-key")
cookieStore = "session"
store = sessions.NewCookieStore(key)
)
type SessionService struct{}
type UserSession struct {
IsAuthenticated bool
Username string
}
func (s *SessionService) Init() {
store.Options.HttpOnly = true
store.Options.Secure = true
}
func (s *SessionService) Login(c echo.Context, q *models.Queries) error {
sess, err := store.Get(c.Request(), cookieStore)
if err != nil {
c.Response().Status = http.StatusInternalServerError
return err
}
username := c.FormValue("username")
password := c.FormValue("password")
user, err := q.GetUserByUsername(c.Request().Context(), username)
if err != nil {
c.Response().Status = 401
return err
}
isValidPW := ComparePassowrds([]byte(user.Password), password)
if !isValidPW {
c.Response().Status = 401
return err
}
sess.Values["authenticated"] = true
sess.Values["username"] = username
sess.Save(c.Request(), c.Response())
return nil
}
func (s *SessionService) Logout(c echo.Context) error {
sess, err := store.Get(c.Request(), cookieStore)
if err != nil {
return err
}
sess.Values["authenticated"] = false
sess.Options.MaxAge = -1
sess.Save(c.Request(), c.Response())
return nil
}
func (s *SessionService) IsAuthenticated(c echo.Context) UserSession {
sess, _ := store.Get(c.Request(), cookieStore)
if auth, ok := sess.Values["authenticated"].(bool); !ok || !auth {
return UserSession{
false,
"",
}
}
return UserSession{
sess.Values["authenticated"].(bool),
sess.Values["username"].(string),
}
}