-
Notifications
You must be signed in to change notification settings - Fork 2
/
login_callback.go
63 lines (50 loc) · 1.7 KB
/
login_callback.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
package page
import (
"context"
"net/http"
"github.com/ministryofjustice/opg-modernising-lpa/internal/actor"
"github.com/ministryofjustice/opg-modernising-lpa/internal/onelogin"
"github.com/ministryofjustice/opg-modernising-lpa/internal/sesh"
)
type LoginCallbackOneLoginClient interface {
Exchange(ctx context.Context, code, nonce string) (idToken, accessToken string, err error)
UserInfo(ctx context.Context, accessToken string) (onelogin.UserInfo, error)
}
type LoginCallbackSessionStore interface {
OneLogin(r *http.Request) (*sesh.OneLoginSession, error)
SetLogin(r *http.Request, w http.ResponseWriter, session *sesh.LoginSession) error
}
func LoginCallback(oneLoginClient LoginCallbackOneLoginClient, sessionStore LoginCallbackSessionStore, redirect Path, dashboardStore DashboardStore, actorType actor.Type) Handler {
return func(appData AppData, w http.ResponseWriter, r *http.Request) error {
oneLoginSession, err := sessionStore.OneLogin(r)
if err != nil {
return err
}
idToken, accessToken, err := oneLoginClient.Exchange(r.Context(), r.FormValue("code"), oneLoginSession.Nonce)
if err != nil {
return err
}
userInfo, err := oneLoginClient.UserInfo(r.Context(), accessToken)
if err != nil {
return err
}
session := &sesh.LoginSession{
IDToken: idToken,
Sub: userInfo.Sub,
Email: userInfo.Email,
}
if err := sessionStore.SetLogin(r, w, session); err != nil {
return err
}
if actorType != actor.TypeDonor {
exists, err := dashboardStore.SubExistsForActorType(r.Context(), session.SessionID(), actorType)
if err != nil {
return err
}
if exists {
redirect = Paths.Dashboard
}
}
return appData.Redirect(w, r, redirect.Format())
}
}