//验证OSS向业务服务器发来的回调函数。
//该方法是并发安全的
//pubKeyUrl 回调请求头中[x-oss-pub-key-url]一项，以Base64编码
//reqUrl oss所发来请求的url，由path+query组成
//reqBody oss所发来请求的body
//authorization authorization为回调头中的签名
359474
func AuthenticateCallBack(pubKeyUrl, reqUrl, reqBody, authorization string) error {
	//获取证书url
	keyURL, err := base64.URLEncoding.DecodeString(pubKeyUrl)
	if err != nil {
		return err
	}
	url := string(keyURL)
	//判断证书是否来自于阿里云
	if !urlReg.Match(keyURL) {
		return errors.New("certificate address error")
	}
	//获取文件名
	rs := []rune(url)
	filename := string(rs[strings.LastIndex(url, "/") : len(rs)-1])
	authentication.lock.RLock()
	certificate := authentication.certificate[filename]
	authentication.lock.RUnlock()
	//内存中没有证书，下载
	if certificate == nil {
		authentication.lock.Lock()
		res, err := http.Get(url)
		if err != nil {
			return err
		}
		defer res.Body.Close()
		body, err := ioutil.ReadAll(res.Body)
		if err != nil {
			return err
		}
		block, _ := pem.Decode(body)
		if block == nil {
			return errors.New("certificate error")
		}
		pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
		if err != nil {
			return err
		}
		certificate = pubKey.(*rsa.PublicKey)
		authentication.certificate[filename] = certificate
		authentication.lock.Unlock()
	}
	//证书准备完毕，开始验证
	//解析签名
	signature, err := base64.StdEncoding.DecodeString(authorization)
	if err != nil {
		return err
	}
	hashed := md5.New()
	hashed.Write([]byte(reqUrl + "\n" + reqBody))
	if err := rsa.VerifyPKCS1v15(certificate, crypto.MD5, hashed.Sum(nil), signature); err != nil {
		return err
	}
	//验证通过
	return nil
}
652329
func Basic(realm string, f func(user, passwd string) bool) goproxy.ReqHandler {
	return goproxy.FuncReqHandler(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
		if !auth(req, f) {
			return nil, BasicUnauthorized(req, realm)
		}
		return req, nil
	})
}
931878
func main() {
	ws := new(restful.WebService)
	ws.Route(ws.GET("/secret").Filter(basicAuthenticate).To(secret))
	restful.Add(ws)
	log.Fatal(http.ListenAndServe(":8080", nil))
}
1087264
func (c *Client) Authorization(authURI string) (Authorization, error) {
	var auth Authorization
	resp, err := c.client.Get(authURI)
	if err != nil {
		return auth, err
	}
	defer resp.Body.Close()
	if err = checkHTTPError(resp, http.StatusOK); err != nil {
		return auth, err
	}

	if err := json.NewDecoder(resp.Body).Decode(&auth); err != nil {
		return auth, fmt.Errorf("decoding response body: %v", err)
	}
	return auth, nil
}
1157683
func ossGatewayMain(ctx *cli.Context) {
	if ctx.Args().First() == "help" {
		cli.ShowCommandHelpAndExit(ctx, ossBackend, 1)
	}

	// Validate gateway arguments.
	host := ctx.Args().First()
	logger.FatalIf(minio.ValidateGatewayArguments(ctx.GlobalString("address"), host), "Invalid argument")

	minio.StartGateway(ctx, &OSS{host})
}
935099
func GetBeginAuthURLWithBase(base string, state *common.State, config *common.Config) (string, error) {

	if config == nil {
		panic("OAuth2Handler: Must have valid Config specified.")
	}

	// copy the config
	params := objx.MSI(
		OAuth2KeyClientID, config.Get(OAuth2KeyClientID).Str(),
		OAuth2KeyRedirectUrl, config.Get(OAuth2KeyRedirectUrl).Str(),
		OAuth2KeyScope, config.Get(OAuth2KeyScope).Str(),
		OAuth2KeyAccessType, config.Get(OAuth2KeyAccessType).Str(),
		OAuth2KeyApprovalPrompt, config.Get(OAuth2KeyApprovalPrompt).Str(),
		OAuth2KeyResponseType, config.Get(OAuth2KeyResponseType).Str())

	if state != nil {

		// set the state
		stateValue, stateErr := state.SignedBase64(common.GetSecurityKey())

		if stateErr != nil {
			return "", stateErr
		}

		params.Set("state", stateValue)

	}

	// generate the query part
	query, queryErr := params.URLQuery()

	if queryErr != nil {
		return "", queryErr
	}

	// put the strings together
	return base + "?" + query, nil
}
787453
func OAuth2(code, message string, query url.Values) Error {
	return WrapWithMessage(&OAuth2Error{
		Code:    code,
		Message: message,
		Query:   query,
	}, message)
}
1307173
func (k *PublicKey) AuthorizedString() string {
	return fmt.Sprintf(_TPL_PUBLICK_KEY, setting.AppPath, k.ID, setting.CustomConf, k.Content)
}
1183057
func (h *BasicAuthHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	authInfo, err := h.Authenticator.Authenticate(req)
	if err != nil {
		w.Header().Set("WWW-Authenticate", `Basic realm="juju"`)
		if common.IsDischargeRequiredError(err) {
			sendErr := sendError(w, err)
			if sendErr != nil {
				logger.Errorf("%v", sendErr)
			}
			return
		}
		http.Error(w,
			fmt.Sprintf("authentication failed: %s", err),
			http.StatusUnauthorized,
		)
		return
	}
	if h.Authorizer != nil {
		if err := h.Authorizer.Authorize(authInfo); err != nil {
			http.Error(w,
				fmt.Sprintf("authorization failed: %s", err),
				http.StatusForbidden,
			)
			return
		}
	}
	ctx := context.WithValue(req.Context(), authInfoKey{}, authInfo)
	req = req.WithContext(ctx)
	h.Handler.ServeHTTP(w, req)
}
672003
func parsePubKey(in []byte, algo string) (pubKey PublicKey, rest []byte, err error) {
	switch algo {
	case KeyAlgoRSA:
		return parseRSA(in)
	case KeyAlgoDSA:
		return parseDSA(in)
	case KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521:
		return parseECDSA(in)
	case CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01:
		cert, err := parseCert(in, certToPrivAlgo(algo))
		if err != nil {
			return nil, nil, err
		}
		return cert, nil, nil
	}
	return nil, nil, fmt.Errorf("ssh: unknown key algorithm: %v", err)
}
719381
func (k macOSXKeychain) Get(service, username string) (string, error) {
	out, err := exec.Command(
		execPathKeychain,
		"find-generic-password",
		"-s", service,
		"-wa", username).CombinedOutput()
	if err != nil {
		if strings.Contains(fmt.Sprintf("%s", out), "could not be found") {
			err = ErrNotFound
		}
		return "", err
	}
	// if the added secret has multiple lines, osx will hex encode it
	trimStr := strings.TrimSpace(string(out[:]))
	dec, err := hex.DecodeString(trimStr)
	// if there was an error hex decoding the string, assume it's not encoded
	if err != nil {
		return fmt.Sprintf("%s", trimStr), nil
	}
	return fmt.Sprintf("%s", dec), err
}
766809
func BasicAuth(user, pass string) RequestOption {
	return func(req *http.Request) error {
		req.SetBasicAuth(user, pass)
		return nil
	}
}
766977
func authGooglePlus(url string) (string, string, common.Address, error) {
	// Ensure the user specified a meaningful URL, no fancy nonsense
	parts := strings.Split(url, "/")
	if len(parts) < 4 || parts[len(parts)-2] != "posts" {
		return "", "", common.Address{}, errors.New("Invalid Google+ post URL")
	}
	username := parts[len(parts)-3]

	// Google's API isn't really friendly with direct links. Still, we don't
	// want to do ask read permissions from users, so just load the public posts and
	// scrape it for the Ethereum address and profile URL.
	res, err := http.Get(url)
	if err != nil {
		return "", "", common.Address{}, err
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return "", "", common.Address{}, err
	}
	address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
	if address == (common.Address{}) {
		return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
	}
	var avatar string
	if parts = regexp.MustCompile("src=\"([^\"]+googleusercontent.com[^\"]+photo.jpg)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
		avatar = parts[1]
	}
	return username + "@google+", avatar, address, nil
}
201136
func (a *AuthorizationApp) GetURL() string {
	if a == nil || a.URL == nil {
		return ""
	}
	return *a.URL
}
78589
func (k AccountKey) URI() string {
	uri := "accounts"
	if k != "" {
		uri = fmt.Sprintf("accounts/%s", k)
	}
	return uri
}
791213
func (output *SignURLOutput) SignedURL(scheme string) string {
	query := &url.Values{}
	query.Set("algorithm", output.Algorithm)
	query.Set("expires", output.Expires)
	query.Set("keyId", output.KeyID)
	query.Set("signature", output.Signature)

	sUrl := url.URL{}
	sUrl.Scheme = scheme
	sUrl.Host = output.host
	sUrl.Path = output.objectPath
	sUrl.RawQuery = query.Encode()

	return sUrl.String()
}
887019
func IsURL(str string) bool {
	if str == "" || utf8.RuneCountInString(str) >= maxURLRuneCount || len(str) <= minURLRuneCount || strings.HasPrefix(str, ".") {
		return false
	}
	strTemp := str
	if strings.Contains(str, ":") && !strings.Contains(str, "://") {
		// support no indicated urlscheme but with colon for port number
		// http:// is appended so url.Parse will succeed, strTemp used so it does not impact rxURL.MatchString
		strTemp = "http://" + str
	}
	u, err := url.Parse(strTemp)
	if err != nil {
		return false
	}
	if strings.HasPrefix(u.Host, ".") {
		return false
	}
	if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) {
		return false
	}
	return rxURL.MatchString(str)
}