// The user will be redirected back to this handler, that takes the
// "code" query parameter and Exchanges it for an access token.
498506
func handler(w http.ResponseWriter, r *http.Request) {
	t := &oauth2.Transport{Config: config}
	t.Exchange(r.FormValue("code"))
	// The Transport now has a valid Token. Create an *http.Client
	// with which we can make authenticated API requests.
	c := t.Client()

	// Now you can pass the authenticated Client to gopencils, and
	// it will be used to make all the requests
	api := gopencils.Api("http://your-api-url.com/api/", c)

	// Create a pointer to our response struct, which will hold the response
	re := &respStruct{}
	// Maybe some payload to send along with the request?
	payload := map[string]interface{}{"Key1": "Value1"}

	// Perform a GET request
	// URL Requested: http://your-api-url.com/api/users
	api.Res("users", re).Get()

	// Perform a GET request with Querystring
	querystring := map[string]string{"page": "100"}
	// URL Requested: http://your-api-url.com/api/users/123/items?page=100
	api.Res("users").Id(123).Res("items", re).Get(querystring)

	// Or perform a POST Request
	// URL Requested: http://your-api-url.com/api/items/123 with payload as json Data
	api.Res("items", re).Id(123).Post(payload)
}
580236
func (us *UsersService) GetAuthenticated() (*User, *http.Response, error) {
	u, err := urlWithOptions("/users/", nil)
	if err != nil {
		return nil, nil, err
	}

	req, err := us.client.NewRequest("GET", u, nil, nil)
	if err != nil {
		return nil, nil, err
	}

	var userResp getUserResponse
	resp, err := us.client.Do(req, &userResp)
	if err != nil {
		return nil, resp, err
	}

	return &userResp.User, resp, err
}
1259099
func (m *AuthMethod) loginHandler(ctx *router.Context) {
	c, rw, r := ctx.Context, ctx.Writer, ctx.Request

	dest, err := normalizeURL(r.URL.Query().Get("r"))
	if err != nil {
		replyError(c, rw, err, "Bad redirect URI (%q) - %s", dest, err)
		return
	}

	cfg, err := fetchCachedSettings(c)
	if err != nil {
		replyError(c, rw, err, "Can't load OpenID settings - %s", err)
		return
	}

	// `state` will be propagated by OpenID backend and will eventually show up
	// in callback URI handler. See callbackHandler.
	state := map[string]string{
		"dest_url": dest,
		"host_url": r.Host,
	}
	authURI, err := authenticationURI(c, cfg, state)
	if err != nil {
		replyError(c, rw, err, "Can't generate authentication URI - %s", err)
		return
	}
	http.Redirect(rw, r, authURI, http.StatusFound)
}
358137
func (oauth *Oauth) RefreshAccessToken(refreshToken string) (result ResAccessToken, err error) {
	urlStr := fmt.Sprintf(refreshAccessTokenURL, oauth.AppID, refreshToken)
	var response []byte
	response, err = util.HTTPGet(urlStr)
	if err != nil {
		return
	}
	err = json.Unmarshal(response, &result)
	if err != nil {
		return
	}
	if result.ErrCode != 0 {
		err = fmt.Errorf("GetUserAccessToken error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
		return
	}
	return
}
1095513
func (om *Oauth2oauth_2_0Middleware) Handler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		accessToken := om.GetAccessToken(r)
		if accessToken == "" {
			w.WriteHeader(401)
			return
		}

		// TODO: WRITE codes to check user's scopes on this company
		scopes := []string{}
		log.Debug("Available scopes: ", scopes)

		// check scopes
		if !om.CheckScopes(scopes) {
			w.WriteHeader(403)
			return
		}

		next.ServeHTTP(w, r)
	})
}
338138
func (s *OAuthService) Access(clientID string, clientSecret string, code string) *OAuthAccessCall {
	var call OAuthAccessCall
	call.service = s
	call.clientID = clientID
	call.clientSecret = clientSecret
	call.code = code
	return &call
}
487352
func (c *Config) AuthCodeURL(state string, opts ...oauth2.AuthCodeOption) string {
	config := c.getConfig()
	return config.AuthCodeURL(state, opts...)
}
558627
func AccessCodeFlow(authorizationURL, tokenURL string) {
	if current, ok := dslengine.CurrentDefinition().(*design.SecuritySchemeDefinition); ok {
		if current.Kind == design.OAuth2SecurityKind {
			current.Flow = "accessCode"
			current.AuthorizationURL = authorizationURL
			current.TokenURL = tokenURL
			return
		}
	}
	dslengine.IncompatibleDSL()
}
458108
func (c *Context) Redirect(code int, url string) (err error) {
	c.Response().Header().Set(HeaderLocation, url)
	c.Response().WriteHeader(code)
	return nil
}
1229669
func (OAuth2) RedirectURL(imp Importer, ctx *SetupContext) string {
	// We strip our callback URL of its query component, because the Redirect URI
	// we send during authorization has to match exactly the registered redirect
	// URI(s). This query component should be stored in the "state" paremeter instead.
	// See http://tools.ietf.org/html/rfc6749#section-3.1.2.2
	fullCallback := ctx.CallbackURL()
	queryPart := imp.CallbackURLParameters(ctx.AccountNode.PermanodeRef())
	if len(queryPart) == 0 {
		log.Printf("WARNING: callback URL %q has no query component", fullCallback)
	}
	u, _ := url.Parse(fullCallback)
	v := u.Query()
	// remove query params in CallbackURLParameters
	for k := range queryPart {
		v.Del(k)
	}
	u.RawQuery = v.Encode()
	return u.String()
}
1163232
func (oauth *Oauth) Redirect(writer http.ResponseWriter, req *http.Request, redirectURI, scope, state string) error {
	location, err := oauth.GetRedirectURL(redirectURI, scope, state)
	if err != nil {
		return err
	}
	http.Redirect(writer, req, location, 302)
	return nil
}
578335
func (this *serviceImpl) get_token_from_header_query_param(req *http.Request) (*Token, error) {
	if this.settings.VerifyKeyFromHttpRequest == nil {
		return nil, ErrNoVerifyKey
	}
	t, err := jwt.ParseFromRequest(req, func(*jwt.Token) (interface{}, error) {
		return this.settings.VerifyKeyFromHttpRequest(req), nil
	})
	if err != nil {
		return nil, err
	}
	return this.check_token(t)
}
718851
func (service *Service) AccessTokenHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Access-Control-Allow-Origin", "*")

	err := r.ParseForm()
	if err != nil {
		log.Debug("ERROR parsing form: ", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	var clientID, clientSecret string
	code := r.FormValue("code")
	grantType := r.FormValue("grant_type")
	clientSecret = r.FormValue("client_secret")
	clientID = r.FormValue("client_id")

	//If clientSecret if missing from form data check if its available as basicauth
	//See https://tools.ietf.org/html/rfc6749#section-2.3.1
	if clientSecret == "" {
		var ok bool
		clientID, clientSecret, ok = r.BasicAuth()
		if !ok {
			log.Debug("clientSecret not found in form data nor basicauth")
			http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
			return
		}
	}

	//Also accept some alternatives
	if grantType == "authorization_code" {
		grantType = ""
	}

	if clientSecret == "" || clientID == "" || (grantType == "" && code == "") {
		log.Debug("Required parameter missing in the request")
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	var at *AccessToken
	var idToken string
	httpStatusCode := http.StatusOK

	mgr := NewManager(r)
	if grantType != "" {
		if grantType == ClientCredentialsGrantCodeType {
			at, httpStatusCode = clientCredentialsTokenHandler(clientID, clientSecret, mgr, r)
		} else {
			log.Debug("Invalid grant_type")
			httpStatusCode = http.StatusBadRequest
		}
	} else {
		redirectURI := r.FormValue("redirect_uri")
		state := r.FormValue("state")
		at, httpStatusCode = convertCodeToAccessTokenHandler(code, clientID, clientSecret, redirectURI, state, mgr)

		if httpStatusCode == http.StatusOK {
			idToken, httpStatusCode = getIDTokenFromCode(code, service.jwtSigningKey, r, at, mgr)
			at.Scope = removeScope(at.Scope, scopeOpenID)
		}
	}

	if httpStatusCode != http.StatusOK {
		http.Error(w, http.StatusText(httpStatusCode), httpStatusCode)
		return
	}

	// It is also possible to immediately get a JWT by specifying 'id_token' as the response type
	// In this case, the scope parameter needs to be given to prevent consumers to accidentally handing out too powerful tokens to third party services
	// It is also possible to specify additional audiences
	responseType := r.FormValue("response_type")

	if responseType == "id_token" {
		requestedScopeParameter := r.FormValue("scope")
		extraAudiences := r.FormValue("aud")

		validity := parseValidity(r)

		var tokenString string
		tokenString, err = service.convertAccessTokenToJWT(r, at, requestedScopeParameter, extraAudiences, validity)
		if err == errUnauthorized {
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return
		}
		if err != nil {
			log.Error(err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}

		// if client could accept JSON we give the token as JSON string
		// if not, in plain text with the application/jwt mime-type
		if strings.Index(r.Header.Get("Accept"), "application/json") >= 0 {
			w.Header().Set("Content-type", "application/json")
			json.NewEncoder(w).Encode(map[string]string{"access_token": tokenString})
		} else {
			w.Header().Set("Content-type", "application/jwt")
			w.Write([]byte(tokenString))
		}
		return
	}
	mgr.saveAccessToken(at)

	orgMgr := organization.NewManager(r)
	scope, err := verifyScopes(at.Scope, at.Username, at.ClientID, orgMgr)
	if err != nil {
		log.Error("Failed to verify token scopes: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	// Add grants
	grantList, err := getGrants(at.Username, clientID, r)
	if err != nil {
		log.Error("Failed to get grants: ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	scope = strings.Join([]string{scope, strings.Join(grantList, ",")}, ",")

	response := struct {
		AccessToken string      `json:"access_token"`
		IDToken     string      `json:"id_token,omitempty"`
		TokenType   string      `json:"token_type"`
		Scope       string      `json:"scope"`
		ExpiresIn   int64       `json:"expires_in"`
		Info        interface{} `json:"info"`
	}{
		AccessToken: at.AccessToken,
		IDToken:     idToken,
		TokenType:   at.Type,
		Scope:       scope,
		ExpiresIn:   int64(at.ExpirationTime().Sub(time.Now()).Seconds() - 600),

		Info: struct {
			Username string `json:"username"`
		}{
			Username: at.Username,
		},
	}

	w.Header().Set("Content-type", "application/json")
	json.NewEncoder(w).Encode(&response)
}
1006793
func (oauth *Oauth) GetUserAccessToken(code string) (result ResAccessToken, err error) {
	urlStr := fmt.Sprintf(accessTokenURL, oauth.AppID, oauth.AppSecret, code)
	var response []byte
	response, err = util.HTTPGet(urlStr)
	if err != nil {
		return
	}
	err = json.Unmarshal(response, &result)
	if err != nil {
		return
	}
	if result.ErrCode != 0 {
		err = fmt.Errorf("GetUserAccessToken error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
		return
	}
	return
}
1139719
func csrfTokenFromQuery(param string) csrfTokenExtractor {
	return func(c echo.Context) (string, error) {
		token := c.Query(param)
		if token == "" {
			return "", errors.New("empty csrf token in query param")
		}
		return token, nil
	}
}
1100935
func (c *UserConfig) GetAuthorizeURL(service *Service) (string, error) {
	if c.RequestTokenKey == "" || c.RequestTokenSecret == "" {
		return "", fmt.Errorf("No configured request token")
	}
	token := url.QueryEscape(c.RequestTokenKey)
	return service.AuthorizeURL + "?oauth_token=" + token, nil
}
772936
func (self *OAuth2Mixin) GetAccessToken(r *http.Request) (*oauth2.Token, error) {

	code := r.URL.Query().Get("code")
	if len(code) == 0 {
		return nil, errors.New("No Access Code in the Request URL")
	}

	accessToken, err := self.Client.GrantToken(code)
	if err != nil {
		return nil, err
	}

	return accessToken, err
}