// AuthorizeRedirect constructs the request URL that should be used
// to redirect the User to verify User identify and consent.
540142
func (c *Consumer) AuthorizeRedirect(t *RequestToken) (string, error) {
	redirect, err := url.Parse(c.AuthorizationURL)
	if err != nil {
		return "", err
	}

	params := make(url.Values)
	params.Add("oauth_token", t.token)
	redirect.RawQuery = params.Encode()

	u := redirect.String()
	if strings.HasPrefix(u, "https://bitbucket.org/%21api/") {
		u = strings.Replace(u, "/%21api/", "/!api/", -1)
	}

	return u, nil
}
900250
func Authorize() echo.HandlerFunc {
	return func(c echo.Context) error {
		resp := oauth.NewResponse()
		defer resp.Close()

		if ar := oauth.HandleAuthorizeRequest(resp, c.Request()); ar != nil {
			if c.QueryParam("authorized") == "" || c.QueryParam("authorized_code") == "" {
				c.Redirect(http.StatusFound, fmt.Sprintf("%s/oauth2/authorize.php?client_id=%s&response_type=%s&redirect_uri=%s&scope=%s",
					nerdz.Configuration.NERDZURL().String(),
					url.QueryEscape(c.QueryParam("client_id")),
					url.QueryEscape(c.QueryParam("response_type")),
					url.QueryEscape(c.QueryParam("redirect_uri")),
					url.QueryEscape(c.QueryParam("scope"))))
				return nil
			} else {
				var e error
				var userID uint64
				if userID, e = strconv.ParseUint(c.QueryParam("authorized"), 10, 64); e != nil {
					return c.JSON(http.StatusInternalServerError, &rest.Response{
						HumanMessage: "Invalid authorized (user id) value",
						Message:      e.Error(),
						Status:       http.StatusInternalServerError,
						Success:      false,
					})
				}

				var user *nerdz.User
				if user, e = nerdz.NewUser(userID); e != nil {
					return c.JSON(http.StatusInternalServerError, &rest.Response{
						HumanMessage: "Problem retrieving specified user",
						Message:      e.Error(),
						Status:       http.StatusInternalServerError,
						Success:      false,
					})
				}
				sha1_sum := fmt.Sprintf("%x", sha1.Sum([]byte(user.Username+user.Password+user.Email)))
				if sha1_sum != c.QueryParam("authorized_code") {
					message := "Invalid authorization code"
					return c.JSON(http.StatusInternalServerError, &rest.Response{
						HumanMessage: message,
						Message:      message,
						Status:       http.StatusInternalServerError,
						Success:      false,
					})
				}

				ar.UserData = user.Counter
				ar.Authorized = true
				oauth.FinishAuthorizeRequest(resp, c.Request(), ar)
			}
		}

		if resp.IsError && resp.InternalError != nil {
			return c.JSON(http.StatusInternalServerError, &rest.Response{
				HumanMessage: "Internal Server error",
				Message:      resp.InternalError.Error(),
				Status:       http.StatusInternalServerError,
				Success:      false,
			})
		}

		return osin.OutputJSON(resp, c.Response(), c.Request())
	}
}
196909
func issueRedirect(urlPath string) (string, bool) {
	m := issueNum.FindStringSubmatch(urlPath)
	if m == nil {
		return "", false
	}
	issueNumber := strings.TrimPrefix(m[1], "/")
	suffix := ""
	if issueNumber != "" {
		suffix = "/" + issueNumber
	}
	return "https://github.com/perkeep/perkeep/issues" + suffix, true
}
108109
func (ctxt *Context) Redirect(url string) {
	http.Redirect(ctxt, ctxt.Request, url, http.StatusFound)
}
706753
func makeRedirectURL(base, dest string) (string, error) {
	dest, err := normalizeURL(dest)
	if err != nil {
		return "", err
	}
	v := url.Values{}
	v.Set("r", dest)
	return base + "?" + v.Encode(), nil
}
299839
func (s *OauthService) AuthorizeURL(clientID string, options *AuthorizationOptions) string {
	uri, _ := url.Parse(strings.Replace(s.client.BaseURL, "api.", "", 1))
	uri.Path = "/oauth/authorize"
	query := uri.Query()
	query.Add("client_id", clientID)
	query.Add("response_type", "code")
	uri.RawQuery = query.Encode()

	path, _ := addURLQueryOptions(uri.String(), options)
	return path
}
620949
func Authorize(h http.Handler, secret string) *SecretHandler {
	return &SecretHandler{Handler: h, Secret: secret}
}
755526
func (c *Context) Redirect(location string, status ...int) {
	c.Context.Redirect(template.EscapePound(location), status...)
}
371891
func (service *Service) AuthorizeHandler(w http.ResponseWriter, request *http.Request) {

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

	//Check if the requested authorization grant type is supported
	requestedResponseType := request.Form.Get("response_type")
	if requestedResponseType != AuthorizationGrantCodeType {
		log.Debug("Invalid authorization grant type requested")
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	//Check if the user is already authenticated, if not, redirect to the login page before returning here
	var protectedSession bool
	username, err := service.GetWebuser(request, w)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if username == "" {
		username, err = service.GetOauthUser(request, w)
		if err != nil {
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		if username != "" {
			log.Debug("protected session")
			protectedSession = true
		} else {
			redirectToNextPage(w, request)
			return
		}
	}

	//Validate client and redirect_uri
	redirectURI, err := url.QueryUnescape(request.Form.Get("redirect_uri"))
	if err != nil {
		log.Debug("Unparsable redirect_uri")
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	clientID := request.Form.Get("client_id")
	mgr := NewManager(request)
	valid, err := validateRedirectURI(mgr, redirectURI, clientID)
	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	if !valid {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	requestedScopes := oauth2.SplitScopeString(request.Form.Get("scope"))
	possibleScopes, err := service.filterPossibleScopes(request, username, requestedScopes, true)
	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	authorizedScopes, err := service.filterAuthorizedScopes(request, username, clientID, possibleScopes)
	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	var authorizedScopeString string
	var validAuthorization bool

	if authorizedScopes != nil {
		authorizedScopeString = strings.Join(authorizedScopes, ",")
		validAuthorization = IsAuthorizationValid(possibleScopes, authorizedScopes)

		// Check if the user still has the given authorizations
		authorization, err := user.NewManager(request).GetAuthorization(username, clientID)
		if err != nil {
			log.Error("Failed to load authorization: ", err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		if validAuthorization {
			validAuthorization, err = UserHasAuthorizedScopes(request, authorization)
			if err != nil {
				log.Error("Failed to check if authorizated labels are still present: ", err)
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
				return
			}
		}

		//Check if we are redirected from the authorize page, it might be that not all authorizations were given,
		// authorize the login but only with the authorized scopes
		referrer := request.Header.Get("Referer")
		if referrer != "" && !validAuthorization { //If we already have a valid authorization, no need to check if we come from the authorize page
			if referrerURL, e := url.Parse(referrer); e == nil {
				validAuthorization = referrerURL.Host == request.Host && referrerURL.Path == "/authorize"
			} else {
				log.Debug("Error parsing referrer: ", e)
			}
		}
	}

	//If no valid authorization, ask the user for authorizations
	if !validAuthorization {
		if protectedSession {
			log.Debug("protected session active, but need to give authorizations")
			// We need a full session to give authorizations, so remove the l2fa entry
			// This way the login function will require 2fa and give a full session with admin scopes
			l2faMgr := organizationdb.NewLast2FAManager(request)
			if l2faMgr.Exists(clientID, username) {
				err = l2faMgr.RemoveLast2FA(clientID, username)
				if err != nil {
					log.Error(err)
					http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
					return
				}
			}
			redirectToNextPage(w, request)
			return
		}
		token, e := service.createItsYouOnlineAdminToken(username, request)
		if e != nil {
			log.Error(e)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		service.sessionService.SetAPIAccessToken(w, token)
		redirectToScopeRequestPage(w, request, possibleScopes)
		return
	}

	if clientID == "itsyouonline" {
		log.Warn("HACK attempt, someone tried to get a token as the 'itsyouonline' client")
		//TODO: log the entire request and everything we know
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	redirectURI, err = handleAuthorizationGrantCodeType(request, username, clientID, redirectURI, authorizedScopeString)

	if err != nil {
		log.Error(err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	log.Debug("Redirecting from authorize handler to: ", redirectURI)
	http.Redirect(w, request, redirectURI, http.StatusFound)

}
637619
func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
	p := provider.(*Provider)
	if params.Get("openid.mode") != "id_res" {
		return "", errors.New("Mode must equal to \"id_res\".")
	}

	if params.Get("openid.return_to") != s.CallbackURL {
		return "", errors.New("The \"return_to url\" must match the url of current request.")
	}

	v := make(url.Values)
	v.Set("openid.assoc_handle", params.Get("openid.assoc_handle"))
	v.Set("openid.signed", params.Get("openid.signed"))
	v.Set("openid.sig", params.Get("openid.sig"))
	v.Set("openid.ns", params.Get("openid.ns"))

	split := strings.Split(params.Get("openid.signed"), ",")
	for _, item := range split {
		v.Set("openid."+item, params.Get("openid."+item))
	}
	v.Set("openid.mode", "check_authentication")

	resp, err := p.Client().PostForm(apiLoginEndpoint, v)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	response := strings.Split(string(content), "\n")
	if response[0] != "ns:"+openIDNs {
		return "", errors.New("Wrong ns in the response.")
	}

	if response[1] == "is_valid:false" {
		return "", errors.New("Unable validate openId.")
	}

	openIDURL := params.Get("openid.claimed_id")
	validationRegExp := regexp.MustCompile("^(http|https)://steamcommunity.com/openid/id/[0-9]{15,25}$")
	if !validationRegExp.MatchString(openIDURL) {
		return "", errors.New("Invalid Steam ID pattern.")
	}

	s.SteamID = regexp.MustCompile("\\D+").ReplaceAllString(openIDURL, "")
	s.ResponseNonce = params.Get("openid.response_nonce")

	return s.ResponseNonce, nil
}
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
}
562694
func redirect(pathTemplate string, status int) router.Handler {
	if !strings.HasPrefix(pathTemplate, "/") {
		panic("pathTemplate must start with /")
	}

	return func(c *router.Context) {
		parts := strings.Split(pathTemplate, "/")
		for i, p := range parts {
			if strings.HasPrefix(p, ":") {
				parts[i] = c.Params.ByName(p[1:])
			}
		}
		u := *c.Request.URL
		u.Path = strings.Join(parts, "/")
		http.Redirect(c.Writer, c.Request, u.String(), status)
	}
}
458108
func (c *Context) Redirect(code int, url string) (err error) {
	c.Response().Header().Set(HeaderLocation, url)
	c.Response().WriteHeader(code)
	return nil
}
159212
func (ccc ClientCredentialsConfig) Authorizer() (autorest.Authorizer, error) {
	spToken, err := ccc.ServicePrincipalToken()
	if err != nil {
		return nil, fmt.Errorf("failed to get oauth token from client credentials: %v", err)
	}
	return autorest.NewBearerAuthorizer(spToken), nil
}
422833
func (m *Middleware) IsAuthorized(r *http.Request) bool {
	return m.GetAuthorizationToken(r) != nil
}
332235
func RedirectHandler(client Client, op *OpenIDProvider, successfulAuthRedirectURL string) gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		authError := c.Query("error")
		if authError != "" {
			session.Delete("state")
			err := errors.Unauthorizedf("OP was unable to successfully authenticate your request: %s", authError)
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		serverState := c.Query("state")
		localState := session.Get("state")
		if localState == nil {
			err := errors.NotValidf("Couldn't find the local state or nonce to verify the response from the OP")
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		if localState.(string) != serverState {
			c.String(http.StatusForbidden, "Nonce or state did not match")
			c.Abort()
		}

		code := c.Query("code")
		token, err := op.Exchange(code, client)
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		session.Set("OpenIDTokenResponse", token)
		ui, err := op.UserInfo(token.AccessToken)
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}
		session.Set("UserInfo", ui)
		session.Delete("nonce")
		err = session.Save()
		if err != nil {
			c.AbortWithError(http.StatusInternalServerError, err)
		}
		c.Redirect(http.StatusFound, successfulAuthRedirectURL)
	}
}
338906
func (c *LoginController) Authorize(ctx *app.AuthorizeLoginContext) error {
	return redirectWithParams(ctx, c.configuration, ctx.ResponseData.Header(), ctx.Params, authservice.LoginLoginPath())
}