// AuthURL generates the URL to redirect a client to start the authentication process
// as described here: http://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
320492
func (op *OpenIDProvider) AuthURL(c Client, state string) string {
	values := url.Values{"client_id": {c.ISS}, "state": {state}, "response_type": {"code"},
		"redirect_uri": {c.RedirectURI}, "scope": {"openid profile email"}}
	return fmt.Sprintf("%s?%s", op.Config.AuthorizationEndpoint, values.Encode())
}
164112
func OAuthEndpoint(domain string) oauth2.Endpoint {
	if domain == "" {
		domain = defaultDomain
	}
	authURL := fmt.Sprintf("https://meta%s/1/oauth2/authorize", domain)
	tokenURL := fmt.Sprintf("https://api%s/1/oauth2/token", domain)
	if domain == defaultDomain {
		authURL = "https://www.dropbox.com/1/oauth2/authorize"
	}
	return oauth2.Endpoint{AuthURL: authURL, TokenURL: tokenURL}
}
446964
func GetAuthnRequestURL(baseURL string, b64XML string, state string) (string, error) {
	u, err := url.Parse(baseURL)
	if err != nil {
		return "", err
	}

	q := u.Query()
	q.Add("SAMLRequest", b64XML)
	q.Add("RelayState", state)
	u.RawQuery = q.Encode()
	return u.String(), nil
}
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)
}
310585
func (s *Handler) authHandler(w http.ResponseWriter, r *http.Request) {
	formPassword := r.FormValue("password")

	insecure := s.config.Insecure
	password := s.config.Password
	secret := s.config.Secret

	if insecure {
		w.Header().Set("Content-Type", "application/json")
		resp := struct {
			Token string `json:"token"`
		}{
			Token: "insecure",
		}
		json.NewEncoder(w).Encode(resp)
		return
	}

	if password == "" || secret == "" {
		log.Error().Msg("admin_password and admin_secret must be set in configuration")
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	if formPassword == password {
		w.Header().Set("Content-Type", "application/json")
		token, err := generateSecureAdminToken(secret)
		if err != nil {
			log.Error().Msgf("error generating admin token: %v", err)
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}
		resp := map[string]string{
			"token": token,
		}
		json.NewEncoder(w).Encode(resp)
		return
	}
	http.Error(w, "Bad Request", http.StatusBadRequest)
}
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
}
643758
func (sp *SAMLServiceProvider) AuthRedirect(w http.ResponseWriter, r *http.Request, relayState string) (err error) {
	url, err := sp.BuildAuthURL(relayState)
	if err != nil {
		return err
	}

	http.Redirect(w, r, url, http.StatusFound)
	return nil
}
900204
func (c *Client) Auth(key string, secret string) *Client {
	c.APIKey = key
	c.APISecret = secret

	return c
}
575847
func (api *Client) SendAuthRevoke(token string) (*AuthRevokeResponse, error) {
	return api.SendAuthRevokeContext(context.Background(), token)
}
88735
func (p *ProviderData) GetLoginURL(redirectURI, state string) string {
	var a url.URL
	a = *p.LoginURL
	params, _ := url.ParseQuery(a.RawQuery)
	params.Set("redirect_uri", redirectURI)
	params.Set("approval_prompt", p.ApprovalPrompt)
	params.Add("scope", p.Scope)
	params.Set("client_id", p.ClientID)
	params.Set("response_type", "code")
	params.Add("state", state)
	a.RawQuery = params.Encode()
	return a.String()
}
1071153
func (r *redirector) AuthenticationRedirect(w http.ResponseWriter, req *http.Request) error {
	redirectURL, err := buildRedirectURL(r.RedirectURL, r.BaseRequestURL, req.URL)
	if err != nil {
		return nil
	}
	http.Redirect(w, req, redirectURL.String(), http.StatusFound)
	return nil
}
380220
func (a *Authorization) GetURL() string {
	if a == nil || a.URL == nil {
		return ""
	}
	return *a.URL
}
545163
func (p *Provider) BeginAuth(state string) (goth.Session, error) {
	u, err := p.getAuthURL()
	s := &Session{
		AuthURL:     u.String(),
		CallbackURL: p.CallbackURL,
	}
	return s, err
}
1083176
func (b *basicAuth) requestAuth(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm=%q`, b.opts.Realm))
	b.opts.UnauthorizedHandler.ServeHTTP(w, r)
}
613942
func (client *Socket) ClientAuthPlain(username, password string) error {
	err := client.SetPlainUsername(username)
	if err == nil {
		err = client.SetPlainPassword(password)
	}
	return err
}
1017618
func (user *User) OAuthHTTPClient() *http.Client {

	ps, _ := user.protectedSettings()

	if ps == nil {
		return nil
	}

	if ps.OAuthToken == "" {
		return nil
	}

	if user.ctx.Service().DefaultOAuth2 != nil {
		ts := user.ctx.OAuthProvider().OAuth2Client(user.ctx).TokenSource(oauth2.NoContext, &oauth2.Token{AccessToken: ps.OAuthToken, RefreshToken: ps.OAuthRefreshToken, Expiry: *ps.OAuthExpireDate, TokenType: "Bearer"})
		if ps.OAuthExpireDate != nil && ps.OAuthExpireDate.Before(time.Now().Add(time.Second*5)) {
			token, err := ts.Token()
			if err != nil {
				if strings.Contains(err.Error(), "revoked") || strings.Contains(err.Error(), "invalid_grant") {
					ps.OAuthToken = ""
					ps.OAuthExpireDate = nil
					user.saveProtectedSettings()
					//todo: provide revoked callback
				}
				user.ctx.Log().WithError(err).Error("OAuth token refresh failed")
				return nil
			}

			if token != nil {
				ps.OAuthToken = token.AccessToken
				if token.RefreshToken != "" {
					ps.OAuthRefreshToken = token.RefreshToken
				}
				ps.OAuthExpireDate = &token.Expiry
				user.saveProtectedSettings()
			}
		}
		return oauth2.NewClient(oauth2.NoContext, ts)
	} else if user.ctx.Service().DefaultOAuth1 != nil {
		//todo make a correct httpclient
		return http.DefaultClient
	}
	return nil
}
1089981
func (self *AuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	// Redirect the user, if required
	if self.provider.RedirectRequired(r) == true {
		self.provider.Redirect(w, r)
		return
	}

	// Get the authenticated user Id
	u, t, err := self.provider.GetAuthenticatedUser(w, r)
	if err != nil {
		// If there was a problem, invoke failure
		if self.Failure == nil {
			DefaultFailure(w, r, err)
		} else {
			self.Failure(w, r, err)
		}
		return
	}

	// Invoke the success function
	if self.Success == nil {
		DefaultSuccess(w, r, u, t)
	} else {
		self.Success(w, r, u, t)
	}
}