18 "golang.org/x/oauth2/google"
19 "google.golang.org/api/admin/directory/v1"
20 "google.golang.org/api/googleapi"
23type GoogleProvider struct {
25 RedeemRefreshURL *url.URL
26 // GroupValidator is a function that determines if the passed email is in
27 // the configured Google group.
28 GroupValidator func(string) bool
31func NewGoogleProvider(p *ProviderData) *GoogleProvider {
32 p.ProviderName = "Google"
33 if p.LoginURL.String() == "" {
34 p.LoginURL = &url.URL{Scheme: "https",
35 Host: "accounts.google.com",
36 Path: "/o/oauth2/auth",
37 // to get a refresh token. see https://developers.google.com/identity/protocols/OAuth2WebServer#offline
38 RawQuery: "access_type=offline",
41 if p.RedeemURL.String() == "" {
42 p.RedeemURL = &url.URL{Scheme: "https",
43 Host: "www.googleapis.com",
44 Path: "/oauth2/v3/token"}
46 if p.ValidateURL.String() == "" {
47 p.ValidateURL = &url.URL{Scheme: "https",
48 Host: "www.googleapis.com",
49 Path: "/oauth2/v1/tokeninfo"}
52 p.Scope = "profile email"
55 return &GoogleProvider{
57 // Set a default GroupValidator to just always return valid (true), it will
58 // be overwritten if we configured a Google group restriction.
59 GroupValidator: func(email string) bool {
65func emailFromIdToken(idToken string) (string, error) {
67 // id_token is a base64 encode ID token payload
68 // https://developers.google.com/accounts/docs/OAuth2Login#obtainuserinfo
69 jwt := strings.Split(idToken, ".")
70 b, err := jwtDecodeSegment(jwt[1])
76 Email string `json:"email"`
77 EmailVerified bool `json:"email_verified"`
79 err = json.Unmarshal(b, &email)
83 if email.Email == "" {
84 return "", errors.New("missing email")
86 if !email.EmailVerified {
87 return "", fmt.Errorf("email %s not listed as verified", email.Email)
89 return email.Email, nil
92func jwtDecodeSegment(seg string) ([]byte, error) {
93 if l := len(seg) % 4; l > 0 {
94 seg += strings.Repeat("=", 4-l)
97 return base64.URLEncoding.DecodeString(seg)
100func (p *GoogleProvider) Redeem(redirectURL, code string) (s *SessionState, err error) {
102 err = errors.New("missing code")
106 params := url.Values{}
107 params.Add("redirect_uri", redirectURL)
108 params.Add("client_id", p.ClientID)
109 params.Add("client_secret", p.ClientSecret)
110 params.Add("code", code)
111 params.Add("grant_type", "authorization_code")
112 var req *http.Request
113 req, err = http.NewRequest("POST", p.RedeemURL.String(), bytes.NewBufferString(params.Encode()))
117 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
119 resp, err := http.DefaultClient.Do(req)
124 body, err = ioutil.ReadAll(resp.Body)
130 if resp.StatusCode != 200 {
131 err = fmt.Errorf("got %d from %q %s", resp.StatusCode, p.RedeemURL.String(), body)
135 var jsonResponse struct {
136 AccessToken string `json:"access_token"`
137 RefreshToken string `json:"refresh_token"`
138 ExpiresIn int64 `json:"expires_in"`
139 IdToken string `json:"id_token"`
141 err = json.Unmarshal(body, &jsonResponse)
146 email, err = emailFromIdToken(jsonResponse.IdToken)
151 AccessToken: jsonResponse.AccessToken,
152 ExpiresOn: time.Now().Add(time.Duration(jsonResponse.ExpiresIn) * time.Second).Truncate(time.Second),
153 RefreshToken: jsonResponse.RefreshToken,
159// SetGroupRestriction configures the GoogleProvider to restrict access to the
160// specified group(s). AdminEmail has to be an administrative email on the domain that is
161// checked. CredentialsFile is the path to a json file containing a Google service
162// account credentials.
163func (p *GoogleProvider) SetGroupRestriction(groups []string, adminEmail string, credentialsReader io.Reader) {
164 adminService := getAdminService(adminEmail, credentialsReader)
165 p.GroupValidator = func(email string) bool {
166 return userInGroup(adminService, groups, email)
170func getAdminService(adminEmail string, credentialsReader io.Reader) *admin.Service {
171 data, err := ioutil.ReadAll(credentialsReader)
173 log.Fatal("can't read Google credentials file:", err)
175 conf, err := google.JWTConfigFromJSON(data, admin.AdminDirectoryUserReadonlyScope, admin.AdminDirectoryGroupReadonlyScope)
177 log.Fatal("can't load Google credentials file:", err)
179 conf.Subject = adminEmail
181 client := conf.Client(oauth2.NoContext)
182 adminService, err := admin.New(client)
189func userInGroup(service *admin.Service, groups []string, email string) bool {
190 user, err := fetchUser(service, email)
192 log.Printf("error fetching user: %v", err)
196 custID := user.CustomerId
198 for _, group := range groups {
199 members, err := fetchGroupMembers(service, group)
201 if err, ok := err.(*googleapi.Error); ok && err.Code == 404 {
202 log.Printf("error fetching members for group %s: group does not exist", group)
204 log.Printf("error fetching group members: %v", err)
209 for _, member := range members {
212 if member.Id == custID {
225func fetchUser(service *admin.Service, email string) (*admin.User, error) {
226 user, err := service.Users.Get(email).Do()
230func fetchGroupMembers(service *admin.Service, group string) ([]*admin.Member, error) {
231 members := []*admin.Member{}
234 req := service.Members.List(group)
236 req.PageToken(pageToken)
242 for _, member := range r.Members {
243 members = append(members, member)
245 if r.NextPageToken == "" {
248 pageToken = r.NextPageToken
253// ValidateGroup validates that the provided email exists in the configured Google
255func (p *GoogleProvider) ValidateGroup(email string) bool {
256 return p.GroupValidator(email)
259func (p *GoogleProvider) RefreshSessionIfNeeded(s *SessionState) (bool, error) {
260 if s == nil || s.ExpiresOn.After(time.Now()) || s.RefreshToken == "" {
264 newToken, duration, err := p.redeemRefreshToken(s.RefreshToken)
269 // re-check that the user is in the proper google group(s)
270 if !p.ValidateGroup(s.Email) {
271 return false, fmt.Errorf("%s is no longer in the group(s)", s.Email)
274 origExpiration := s.ExpiresOn
275 s.AccessToken = newToken
276 s.ExpiresOn = time.Now().Add(duration).Truncate(time.Second)
277 log.Printf("refreshed access token %s (expired on %s)", s, origExpiration)
281func (p *GoogleProvider) redeemRefreshToken(refreshToken string) (token string, expires time.Duration, err error) {
282 // https://developers.google.com/identity/protocols/OAuth2WebServer#refresh
283 params := url.Values{}
284 params.Add("client_id", p.ClientID)
285 params.Add("client_secret", p.ClientSecret)
286 params.Add("refresh_token", refreshToken)
287 params.Add("grant_type", "refresh_token")
288 var req *http.Request
289 req, err = http.NewRequest("POST", p.RedeemURL.String(), bytes.NewBufferString(params.Encode()))
293 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
295 resp, err := http.DefaultClient.Do(req)
300 body, err = ioutil.ReadAll(resp.Body)
306 if resp.StatusCode != 200 {
307 err = fmt.Errorf("got %d from %q %s", resp.StatusCode, p.RedeemURL.String(), body)
312 AccessToken string `json:"access_token"`
313 ExpiresIn int64 `json:"expires_in"`
315 err = json.Unmarshal(body, &data)
319 token = data.AccessToken
320 expires = time.Duration(data.ExpiresIn) * time.Second
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list