-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
52 lines (43 loc) · 1.1 KB
/
auth.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
package auth
import (
"encoding/gob"
"fmt"
"net/http"
"net/url"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
)
const (
AuthSessionCookieName = "auth-session"
AuthSessionProfileKey = "profile"
AuthSessionAccessTokenKey = "access_token"
)
type User struct {
ID string
FirstName string
LastName string
ProfilePicture string
}
func NewUserFromProfile(profile map[string]interface{}) *User {
return &User{
ID: profile["sub"].(string),
FirstName: profile["given_name"].(string),
LastName: profile["family_name"].(string),
ProfilePicture: profile["picture"].(string),
}
}
func init() {
gob.Register(User{})
}
func IsAuthenticated(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
sess, err := session.Get(AuthSessionCookieName, c)
if err != nil {
return fmt.Errorf("failed to get auth session: %w", err)
}
if sess.Values[AuthSessionProfileKey] == nil {
return c.Redirect(http.StatusSeeOther, "/login?redirectTo="+url.QueryEscape(c.Request().URL.Path))
}
return next(c)
}
}