-
Notifications
You must be signed in to change notification settings - Fork 111
/
auth.go
203 lines (164 loc) · 5.35 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package server
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"net/http"
"net/url"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
"golang.org/x/oauth2"
)
const authSessionName = "auth"
// Authenticator is used to authenticate our users.
// Refereance link - https://auth0.com/docs/quickstart/webapp/golang/01-login for sample auth setup
type Authenticator struct {
*oidc.Provider
oauth2.Config
}
func newAuthenticator(c context.Context, conf Config) (*Authenticator, error) {
provider, err := oidc.NewProvider(
c,
"https://"+conf.AuthDomain+"/",
)
if err != nil {
return nil, err
}
config := oauth2.Config{
ClientID: conf.AuthClientID,
ClientSecret: conf.AuthClientSecret,
RedirectURL: conf.AuthCallbackURL,
Endpoint: provider.Endpoint(),
Scopes: []string{oidc.ScopeOpenID, "profile"},
}
return &Authenticator{
Provider: provider,
Config: config,
}, nil
}
// VerifyIDToken verifies that an *oauth2.Token is a valid *oidc.IDToken.
func (a *Authenticator) VerifyIDToken(ctx context.Context, token *oauth2.Token) (*oidc.IDToken, error) {
rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
return nil, errors.New("no id_token field in oauth2 token")
}
oidcConfig := &oidc.Config{
ClientID: a.ClientID,
}
return a.Verifier(oidcConfig).Verify(ctx, rawIDToken)
}
func (s *Server) authLogin(c echo.Context) error {
state, err := generateRandomState()
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
sess, err := session.Get(authSessionName, c)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
sess.Values["state"] = state
if err := sess.Save(c.Request(), c.Response()); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
return c.Redirect(http.StatusTemporaryRedirect, s.auth.AuthCodeURL(state))
}
func (s *Server) callback(c echo.Context) error {
sess, err := session.Get(authSessionName, c)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
if c.QueryParam("state") != sess.Values["state"] {
return c.String(http.StatusBadRequest, "Invalid state parameter.")
}
// Exchange an authorization code for a token.
token, err := s.auth.Exchange(c.Request().Context(), c.QueryParam("code"))
if err != nil {
return c.String(http.StatusUnauthorized, "Failed to convert an authorization code into a token.")
}
idToken, err := s.auth.VerifyIDToken(c.Request().Context(), token)
if err != nil {
return c.String(http.StatusInternalServerError, "Failed to verify ID Token.")
}
var profile map[string]interface{}
if err := idToken.Claims(&profile); err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
profileBytes, err := json.Marshal(profile)
if err != nil {
return c.String(http.StatusInternalServerError, "Failed to Serialize profile.")
}
sess.Values["access_token"] = token.AccessToken
sess.Values["profile"] = profileBytes
if err := sess.Save(c.Request(), c.Response()); err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
// Redirect to logged in page.
return c.Redirect(http.StatusTemporaryRedirect, "/auth/user")
}
func (s *Server) logout(c echo.Context) error {
logoutUrl, err := url.Parse("https://" + s.conf.AuthDomain + "/v2/logout")
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
scheme := "http"
if c.Request().TLS != nil {
scheme = "https"
}
returnTo, err := url.Parse(scheme + "://" + c.Request().Host + "/auth/logout/callback")
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
parameters := url.Values{}
parameters.Add("returnTo", returnTo.String())
parameters.Add("client_id", s.conf.AuthClientID)
logoutUrl.RawQuery = parameters.Encode()
return c.Redirect(http.StatusTemporaryRedirect, logoutUrl.String())
}
func (s *Server) logoutCallback(c echo.Context) error {
sess, err := session.Get(authSessionName, c)
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err.Error())
}
sess.Values["access_token"] = nil
sess.Values["profile"] = nil
if err := sess.Save(c.Request(), c.Response()); err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
return c.String(http.StatusOK, "user logged out")
}
func (s *Server) user(c echo.Context) error {
sess, err := session.Get(authSessionName, c)
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
var profiles map[string]interface{}
profile := sess.Values["profile"].([]byte)
json.Unmarshal(profile, &profiles)
return c.JSON(http.StatusOK, profiles)
}
func generateRandomState() (string, error) {
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
return "", err
}
state := base64.StdEncoding.EncodeToString(b)
return state, nil
}
// IsAuthenticated is a middleware that checks if
// the user has already been authenticated previously.
func IsAuthenticated(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
sess, err := session.Get(authSessionName, c)
if err != nil {
return c.String(http.StatusUnauthorized, err.Error())
}
if sess.Values["profile"] == nil {
return c.String(http.StatusUnauthorized, "Not Authenticated")
}
return next(c)
}
}