/
init.go
83 lines (73 loc) · 2.33 KB
/
init.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 auth
import (
"os"
"time"
"github.com/gmarcha/ent-goswagger-app/internal/ent"
"github.com/gmarcha/ent-goswagger-app/internal/goswagger/restapi/operations"
"github.com/gmarcha/ent-goswagger-app/internal/modules/user"
"github.com/go-redis/redis/v8"
"github.com/golang-jwt/jwt/v4"
"golang.org/x/oauth2"
)
type userClaims struct {
Roles []string
jwt.RegisteredClaims
}
// Init sets authentication route handlers.
func Init(api *operations.TutorAPI, db *ent.Client, rdb *redis.Client) {
accessTokenDuration := time.Minute * 1
refreshTokenDuration := time.Hour * 72
accessTokenState := os.Getenv("ACCESS_TOKEN_STATE")
refreshTokenState := os.Getenv("REFRESH_TOKEN_STATE")
oauthState := os.Getenv("AUTH_STATE")
oauthConfig := createConfig()
userInfoUrl := os.Getenv("API_USERINFO_URL")
userService := &user.Service{User: db.User}
api.OAuth2Auth = authenticate(rdb, accessTokenState).auth
api.AuthenticationLoginHandler = &login{
oauthState: oauthState,
oauthConfig: oauthConfig,
}
api.AuthenticationCallbackHandler = &callback{
userInfoUrl: userInfoUrl,
accessTokenDuration: accessTokenDuration,
refreshTokenDuration: refreshTokenDuration,
accessTokenState: accessTokenState,
refreshTokenState: refreshTokenState,
oauthState: oauthState,
oauthConfig: oauthConfig,
user: userService,
rdb: rdb,
}
api.AuthenticationTokenInfoHandler = &tokenInfo{
accessTokenState: accessTokenState,
rdb: rdb,
}
api.AuthenticationTokenRefreshHandler = &tokenRefresh{
userInfoUrl: userInfoUrl,
accessTokenDuration: accessTokenDuration,
refreshTokenDuration: refreshTokenDuration,
accessTokenState: accessTokenState,
refreshTokenState: refreshTokenState,
oauthConfig: oauthConfig,
user: userService,
rdb: rdb,
}
}
func createConfig() *oauth2.Config {
clientID := os.Getenv("API_CLIENT_ID")
clientSecret := os.Getenv("API_CLIENT_SECRET")
authUrl := os.Getenv("API_AUTH_URL")
tokenUrl := os.Getenv("API_TOKEN_URL")
callbackUrl := os.Getenv("API_CALLBACK_URL")
return &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
Scopes: []string{"public"},
Endpoint: oauth2.Endpoint{
AuthURL: authUrl,
TokenURL: tokenUrl,
},
RedirectURL: callbackUrl,
}
}