// googleAuth authenticates a user with Google+ using provided OAuth 2.0 access token.
// If authenticated successfully, user profile is retrieved from Google+ and user is given a JWT token in return.
969333
func googleAuth(ctx *neptulon.ReqCtx, db data.DB, pass string) error {
	var r tokenContainer
	if err := ctx.Params(&r); err != nil || r.Token == "" {
		ctx.Err = &neptulon.ResError{Code: 666, Message: "Malformed or null Google oauth access token was provided."}
		return fmt.Errorf("auth: google: malformed or null Google oauth token '%v' was provided: %v", r.Token, err)
	}

	p, err := getTokenInfo(r.Token)
	if err != nil {
		ctx.Err = &neptulon.ResError{Code: 666, Message: "Failed to authenticated with the given Google oauth access token."}
		return fmt.Errorf("auth: google: error during Google API call using provided token: %v with error: %v", r.Token, err)
	}

	// retrieve user information
	user, ok := db.GetByEmail(p.Email)
	if !ok {
		// this is a first-time registration so create user profile via Google+ profile info
		user = &models.User{Email: p.Email, Name: p.Name, Picture: p.Picture, Registered: time.Now()}

		// save the user information for user ID to be generated by the database
		if ierr := db.SaveUser(user); ierr != nil {
			return fmt.Errorf("auth: google: failed to persist user information: %v", ierr)
		}

		// create the JWT token
		token := jwt.New(jwt.SigningMethodHS256)
		token.Claims["userid"] = user.ID
		token.Claims["created"] = user.Registered.Unix()
		user.JWTToken, err = token.SignedString([]byte(pass))
		if err != nil {
			return fmt.Errorf("auth: google: jwt signing error: %v", err)
		}

		// now save the full user info
		if err := db.SaveUser(user); err != nil {
			return fmt.Errorf("auth: google: failed to persist user information: %v", err)
		}

		// store user ID in session so user can make authenticated call after this
		ctx.Conn.Session.Set("userid", user.ID)
	}

	ctx.Res = gAuthRes{ID: user.ID, Token: user.JWTToken, Name: user.Name, Email: user.Email, Picture: user.Picture}
	ctx.Session.Set(middleware.CustResLogDataKey, gAuthRes{ID: user.ID, Token: user.JWTToken, Name: user.Name, Email: user.Email})
	log.Printf("auth: google: logged in: %v, %v", p.Name, p.Email)
	return nil
}
1006733
func Google(conf *oauth2.Config) martini.Handler {
	conf.Endpoint = google.Endpoint
	return NewOAuth2Provider(conf)
}
237385
func getAuthenticatedUser(ctx context.Context) string {
	claimsIf := ctx.Value("claims")
	if claimsIf == nil {
		return ""
	}
	claims, ok := claimsIf.(jwt.Claims)
	if !ok {
		return ""
	}
	mapClaims, err := jwtutil.MapClaims(claims)
	if err != nil {
		return ""
	}
	return jwtutil.GetField(mapClaims, "sub")
}
660487
func (d *API) RegisterAuth(scheme string, handler runtime.Authenticator) {
	if d.authenticators == nil {
		d.authenticators = make(map[string]runtime.Authenticator)
	}
	d.authenticators[scheme] = handler
}
362621
func (context *APIContext) Authentication(request *restful.Request) (interface{}, error) {
	//FIXME: implement this properly

	t := request.QueryParameter("accesstoken")
	if len(t) == 0 {
		t = request.HeaderParameter("authorization")
		if strings.Index(t, " ") > 0 {
			t = strings.TrimSpace(strings.Split(t, " ")[1])
		}
	}

	return nil, nil // context.GetUserByAccessToken(t)
}
1095213
func AuthToken(ctx context.Context) (*types.AuthToken, bool) {
	if v, ok := ctx.Value(AuthTokenKey).(*types.AuthToken); ok {
		return v, ok
	}
	return nil, false
}
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)
}
136649
func (obj *Global) GetAuthenticatedUser(ctx context.Context) (string, error) {
	result := &struct {
		Return string	`json:"qReturn"`
	} {}
	err := obj.rpc(ctx, "GetAuthenticatedUser", result)
	return result.Return, err 
}
195891
func (a authenticator) localUserAuth() *authentication.UserAuthenticator {
	localUserIdentityLocation := url.URL{
		Scheme: "https",
		Host:   a.serverHost,
		Path:   localUserIdentityLocationPath,
	}
	return &authentication.UserAuthenticator{
		Service:                   a.ctxt.localUserBakeryService,
		Clock:                     a.ctxt.clock,
		LocalUserIdentityLocation: localUserIdentityLocation.String(),
	}
}
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
}
117941
func WithAuth(tokenToCheck, tokenHeaderName string, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get(tokenHeaderName) != tokenToCheck {
			http.Error(w, "not authorized", http.StatusUnauthorized)
			return
		}
		next.ServeHTTP(w, r)
	})
}
1330265
func (s *sdkGrpcServer) auth(ctx context.Context) (context.Context, error) {
	// Obtain token from metadata in the context
	token, err := grpc_auth.AuthFromMD(ctx, ContextMetadataTokenKey)
	if err != nil {
		return nil, err
	}

	// Determine issuer
	issuer, err := auth.TokenIssuer(token)
	if err != nil {
		return nil, status.Errorf(codes.PermissionDenied, "Unable to obtain issuer from token: %v", err)
	}

	// Authenticate user
	if authenticator, ok := s.config.Security.Authenticators[issuer]; ok {
		var claims *auth.Claims
		claims, err = authenticator.AuthenticateToken(ctx, token)
		if err == nil {
			// Add authorization information back into the context so that other
			// functions can get access to this information.
			// If this is in the context is how functions will know that security is enabled.
			ctx = auth.ContextSaveUserInfo(ctx, &auth.UserInfo{
				Username: authenticator.Username(claims),
				Claims:   *claims,
			})
			return ctx, nil
		} else {
			return nil, status.Error(codes.PermissionDenied, err.Error())
		}
	} else {
		return nil, status.Errorf(codes.PermissionDenied, "%s is not a trusted issuer", issuer)
	}
}
1174438
func (a TokenAuth) ApplyAuthentication(r *http.Request) {
	token := fmt.Sprintf("Token %s", a.Token)
	r.Header.Add("Authorization", token)

	r.URL.Host = a.Host
	r.Host = a.Host
}
554405
func (fb *Firebase) Auth(token string) {
	fb.paramsMtx.Lock()
	fb.params.Set(authParam, token)
	fb.paramsMtx.Unlock()
}
982084
func AuthUser(auth Auth) (Auth, error) {
	// TODO: Stop using package log, package httptest.
	config := &oauth.Config{
		ClientId:     auth.APIClientID,
		ClientSecret: auth.APIClientSecret,
		Scope:        "https://www.googleapis.com/auth/cloudprint https://www.googleapis.com/auth/googletalk",
		AuthURL:      "https://accounts.google.com/o/oauth2/auth",
		TokenURL:     "https://accounts.google.com/o/oauth2/token",
	}
	ch := make(chan string)
	randState, err := RandomID()
	if err != nil {
		return Auth{}, err
	}
	ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		if req.URL.Path == "/favicon.ico" {
			http.Error(rw, "", 404)
			return
		}
		if req.FormValue("state") != randState {
			log.Printf("State doesn't match: req = %#v", req)
			http.Error(rw, "", 500)
			return
		}
		if code := req.FormValue("code"); code != "" {
			fmt.Fprintf(rw, "<h1>Success</h1>Authorized.")
			rw.(http.Flusher).Flush()
			ch <- code
			return
		}
		log.Printf("no code")
		http.Error(rw, "", 500)
	}))
	defer ts.Close()

	config.RedirectURL = ts.URL
	authURL := config.AuthCodeURL(randState)
	go openURL(authURL)
	log.Printf("Authorize this app at: %s", authURL)
	code := <-ch
	log.Printf("Got code: %s", code)

	t := &oauth.Transport{
		Config:    config,
		Transport: http.DefaultTransport,
	}
	_, err = t.Exchange(code)
	if err != nil {
		log.Fatalf("Token exchange error: %v", err)
	}

	auth.Token = *t.Token
	return auth, nil
}
1036534
func (c *ZkConn) AddAuth(ctx context.Context, scheme string, auth []byte) error {
	return c.withRetry(ctx, func(conn *zk.Conn) error {
		err := conn.AddAuth(scheme, auth)
		return err
	})
}
647022
func (self *OAuth2Mixin) GetAuthenticatedUser(endpoint string, accessToken string, resp interface{}) error {

	//create the user url
	endpointUrl, _ := url.Parse(endpoint)
	endpointUrl.RawQuery = "access_token="+accessToken

	//create the http request for the user Url
	req := http.Request{
		URL:        endpointUrl,
		Method:     "GET",
		ProtoMajor: 1,
		ProtoMinor: 1,
		Close:      true,
	}

	//do the http request and get the response
	r, err := http.DefaultClient.Do(&req)
	if err != nil {
		return err
	}

	//get the response body
	userData, err := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	if err != nil {
		return err
	}

	//unmarshal user json
	return json.Unmarshal(userData, &resp)
}