-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth_session.go
executable file
·114 lines (93 loc) · 2.56 KB
/
auth_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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package user
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/go-bolo/bolo"
user_helpers "github.com/go-bolo/user/helpers"
user_models "github.com/go-bolo/user/models"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"github.com/sirupsen/logrus"
)
// Init - Start the redis session connection
func Init(app bolo.App) {
initRedisSession()
}
func isPublicRoute(url string) bool {
return strings.HasPrefix(url, "/health") || strings.HasPrefix(url, "/public")
}
func HandleRequestSessionAuthentication(c echo.Context) error {
var err error
ctx := c.(*bolo.RequestContext)
if !ctx.IsAuthenticated {
err = sessionAuthenticationHandler(c)
if err != nil {
return err
}
}
return nil
}
type SessionData struct {
UserID string `json:"userId"`
}
func (sd *SessionData) ToJSON() string {
jsonData, _ := json.Marshal(sd)
return string(jsonData)
}
func sessionAuthenticationHandler(c echo.Context) error {
ctx := c.(*bolo.RequestContext)
authPlugin := ctx.App.GetPlugin("auth").(*AuthPlugin)
sess, err := session.Get("session", c)
if err != nil {
if !strings.Contains(err.Error(), "session store not found") {
return fmt.Errorf("error on get session: %w", err)
}
}
if ctx.ENV == "production" {
sess.Options.Secure = true
}
if sess.Values["uid"] == nil {
seesC, _ := c.Cookie("session")
if seesC != nil && seesC.Value != "" {
// the session cookie still exists then delete it:
seesC.Expires = time.Now().AddDate(0, -1, 0)
c.SetCookie(seesC)
}
return nil // not authenticated with sessions
}
userId := sess.Values["uid"].(string)
savedUser := user_models.UserModel{}
err = user_models.UserFindOne(userId, &savedUser)
if err != nil {
logrus.WithFields(logrus.Fields{
"err": err,
"value": sess.Values,
"userID": userId,
}).Error("sessionAuthenticationHandler error on find user")
}
if savedUser.ID != 0 {
logrus.WithFields(logrus.Fields{
"userId": savedUser.ID,
}).Debug("sessionAuthenticationHandler user authenticated")
if ctx.AuthenticatedUser == nil {
ctx.SetAuthenticatedUserAndFillRoles(&savedUser)
}
ctx.Session.UserID = ctx.AuthenticatedUser.GetID()
ctx.IsAuthenticated = true
}
if authPlugin.SessionResave && c.Request().Method == http.MethodGet {
sess.Options = user_helpers.GetSessionOptions(ctx.App)
err = sess.Save(c.Request(), c.Response())
if err != nil {
logrus.WithFields(logrus.Fields{
"err": err,
"value": sess.Values,
"userID": userId,
}).Error("sessionAuthenticationHandler error on save session")
}
}
return nil
}