HandleLogin returns the tokens for github oauth authentication.
(ctx context.Context, state string, auth string)
| 114 | |
| 115 | // HandleLogin returns the tokens for github oauth authentication. |
| 116 | func (a *AdminAuth) HandleLogin(ctx context.Context, state string, auth string) (userInfo *AdminUserInfo, err error) { |
| 117 | if a.OAuthEnabled() { |
| 118 | var oauthCfg *oauth2.Config |
| 119 | |
| 120 | // get client id from state |
| 121 | if idx := strings.IndexRune(state, ':'); idx != -1 { |
| 122 | oauthCfg, _ = a.oauthCfg[state[idx+1:]] |
| 123 | } |
| 124 | |
| 125 | if oauthCfg == nil { |
| 126 | oauthCfg = a.oauthCfg["default"] |
| 127 | } |
| 128 | |
| 129 | var token *oauth2.Token |
| 130 | token, err = oauthCfg.Exchange(ctx, auth) |
| 131 | if err != nil { |
| 132 | err = errors.Wrapf(err, "oauth token exchange failed") |
| 133 | return |
| 134 | } |
| 135 | |
| 136 | h := oauthCfg.Client(ctx, token) |
| 137 | var resp *http.Response |
| 138 | |
| 139 | if resp, err = h.Get(GithubGetUserURL); err != nil { |
| 140 | err = errors.Wrapf(err, "request github developer user info failed") |
| 141 | return |
| 142 | } |
| 143 | |
| 144 | defer func() { |
| 145 | if resp.Body != nil { |
| 146 | _ = resp.Body.Close() |
| 147 | } |
| 148 | }() |
| 149 | |
| 150 | if resp.StatusCode < 200 || resp.StatusCode > 299 { |
| 151 | err = ErrOAuthGetUserFailed |
| 152 | return |
| 153 | } |
| 154 | |
| 155 | var respBytes []byte |
| 156 | respBytes, err = ioutil.ReadAll(io.LimitReader(resp.Body, MaxGithubResponseSize)) |
| 157 | if err != nil { |
| 158 | err = errors.Wrapf(err, "read github response failed") |
| 159 | return |
| 160 | } |
| 161 | |
| 162 | // decode necessary fields to struct |
| 163 | if err = json.Unmarshal(respBytes, &userInfo); err != nil || userInfo == nil { |
| 164 | err = errors.Wrapf(err, "decode github user info failed") |
| 165 | return |
| 166 | } |
| 167 | |
| 168 | // decode all fields to extra |
| 169 | if err = json.Unmarshal(respBytes, &userInfo.Extra); err != nil { |
| 170 | err = errors.Wrapf(err, "decode extra user info failed") |
| 171 | return |
| 172 | } |
| 173 |
no test coverage detected