// GetUserInformation is the handler for GET /users/{username}/info
760421
func (api UsersAPI) GetUserInformation(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	userMgr := user.NewManager(r)

	userobj, err := userMgr.GetByName(username)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	requestingClient, validClient := context.Get(r, "client_id").(string)
	if !validClient {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	availableScopes, _ := context.Get(r, "availablescopes").(string)
	isAdmin := oauth2.CheckScopes([]string{"user:admin"}, oauth2.SplitScopeString(availableScopes))

	authorization, err := userMgr.GetAuthorization(username, requestingClient)
	if handleServerError(w, "getting authorization", err) {
		return
	}

	//Create an administrator authorization
	// TODO: rework for non admin scope in client credentials
	// if authorization is nil we are already assured that this is client credentials due to the middleware
	authorizedScopes := oauth2.SplitScopeString(availableScopes)
	if authorization == nil {
		authorization = &user.Authorization{
			// TODO: check bool values
			Name:                    false,
			Github:                  false,
			Facebook:                false,
			Addresses:               []user.AuthorizationMap{},
			BankAccounts:            []user.AuthorizationMap{},
			DigitalWallet:           []user.DigitalWalletAuthorization{},
			EmailAddresses:          []user.AuthorizationMap{},
			ValidatedEmailAddresses: []user.AuthorizationMap{},
			Phonenumbers:            []user.AuthorizationMap{},
			ValidatedPhonenumbers:   []user.AuthorizationMap{},
			PublicKeys:              []user.AuthorizationMap{},
			Avatars:                 []user.AuthorizationMap{},
			Organizations:           []string{},
		}
		_, all := filterAuthorizedInfo(authorizedScopes, "user:name")
		if isAdmin || all {
			authorization.Name = true
		}
		_, all = filterAuthorizedInfo(authorizedScopes, "user:github")
		if isAdmin || all {
			authorization.Github = true
		}
		_, all = filterAuthorizedInfo(authorizedScopes, "user:facebook")
		if isAdmin || all {
			authorization.Facebook = true
		}
		for _, address := range userobj.Addresses {
			labels, all := filterAuthorizedInfo(authorizedScopes, "user:address")
			if all || isAdmin {
				authorization.Addresses = append(authorization.Addresses, user.AuthorizationMap{RequestedLabel: address.Label, RealLabel: address.Label})
				continue
			}
			for _, label := range labels {
				if label == address.Label {
					authorization.Addresses = append(authorization.Addresses, user.AuthorizationMap{RequestedLabel: address.Label, RealLabel: address.Label})
				}
			}
		}
		for _, a := range userobj.BankAccounts {
			labels, all := filterAuthorizedInfo(authorizedScopes, "user:bankaccount")
			if all || isAdmin {
				authorization.BankAccounts = append(authorization.BankAccounts, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				continue
			}
			for _, label := range labels {
				if label == a.Label {
					authorization.BankAccounts = append(authorization.BankAccounts, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				}
			}
		}
		for _, a := range userobj.DigitalWallet {
			labels, all := filterAuthorizedInfo(authorizedScopes, "user:digitalwalletaddress")
			if all || isAdmin {
				authorization.DigitalWallet = append(authorization.DigitalWallet, user.DigitalWalletAuthorization{Currency: a.CurrencySymbol, AuthorizationMap: user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label}})
				continue
			}
			for _, label := range labels {
				if label == a.Label {
					authorization.DigitalWallet = append(authorization.DigitalWallet, user.DigitalWalletAuthorization{Currency: a.CurrencySymbol, AuthorizationMap: user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label}})
				}
			}
		}
		for _, a := range userobj.EmailAddresses {
			labels, all := filterAuthorizedInfo(authorizedScopes, "user:email")
			if all || isAdmin {
				authorization.EmailAddresses = append(authorization.EmailAddresses, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				continue
			}
			for _, label := range labels {
				if label == a.Label {
					authorization.EmailAddresses = append(authorization.EmailAddresses, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				}
			}
		}
		for _, a := range userobj.EmailAddresses {
			labels, all := filterAuthorizedInfo(authorizedScopes, "user:validated:email")
			if all || isAdmin {
				authorization.ValidatedEmailAddresses = append(authorization.ValidatedEmailAddresses, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				continue
			}
			for _, label := range labels {
				if label == a.Label {
					authorization.ValidatedEmailAddresses = append(authorization.ValidatedEmailAddresses, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				}
			}
		}
		for _, a := range userobj.Phonenumbers {
			labels, all := filterAuthorizedInfo(authorizedScopes, "user:phone")
			if all || isAdmin {
				authorization.Phonenumbers = append(authorization.Phonenumbers, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				continue
			}
			for _, label := range labels {
				if label == a.Label {
					authorization.Phonenumbers = append(authorization.Phonenumbers, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				}
			}
		}
		for _, a := range userobj.Phonenumbers {
			labels, all := filterAuthorizedInfo(authorizedScopes, "user:validated:phone")
			if all || isAdmin {
				authorization.ValidatedPhonenumbers = append(authorization.ValidatedPhonenumbers, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				continue
			}
			for _, label := range labels {
				if label == a.Label {
					authorization.ValidatedPhonenumbers = append(authorization.ValidatedPhonenumbers, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				}
			}
		}
		for _, a := range userobj.PublicKeys {
			labels, all := filterAuthorizedInfo(authorizedScopes, "user:publickey")
			if all || isAdmin {
				authorization.PublicKeys = append(authorization.PublicKeys, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				continue
			}
			for _, label := range labels {
				if label == a.Label {
					authorization.PublicKeys = append(authorization.PublicKeys, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				}
			}
		}
		for _, a := range userobj.Avatars {
			labels, all := filterAuthorizedInfo(authorizedScopes, "user:avatar")
			if all || isAdmin {
				authorization.Avatars = append(authorization.Avatars, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				continue
			}
			for _, label := range labels {
				if label == a.Label {
					authorization.Avatars = append(authorization.Avatars, user.AuthorizationMap{RequestedLabel: a.Label, RealLabel: a.Label})
				}
			}
		}
		labels, _ := filterAuthorizedInfo(authorizedScopes, "user:memberof")
		if len(labels) > 0 || isAdmin {
			userOrgs, err := organizationDb.NewManager(r).AllByUserChain(username)
			if handleServerError(w, "Getting user organizations", err) {
				return
			}
			for _, a := range userOrgs {
				if isAdmin {
					authorization.Organizations = append(authorization.Organizations, a)
					continue
				}
				for _, l := range labels {
					if l == a {
						authorization.Organizations = append(authorization.Organizations, a)
					}
				}
			}
		}

	}
	if authorization == nil {
		http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		return
	}

	respBody := &Userview{
		Username:                userobj.Username,
		Github:                  user.GithubAccount{},
		Facebook:                user.FacebookAccount{},
		Addresses:               []user.Address{},
		EmailAddresses:          []user.EmailAddress{},
		ValidatedEmailAddresses: []user.EmailAddress{},
		Phonenumbers:            []user.Phonenumber{},
		ValidatedPhonenumbers:   []user.Phonenumber{},
		BankAccounts:            []user.BankAccount{},
		DigitalWallet:           []user.DigitalAssetAddress{},
		OwnerOf: user.OwnerOf{
			EmailAddresses: []string{},
		},
		PublicKeys:    []user.PublicKey{},
		Avatars:       []user.Avatar{},
		Organizations: []string{},
	}

	if authorization.Name {
		respBody.Firstname = userobj.Firstname
		respBody.Lastname = userobj.Lastname
	}

	if authorization.Github {
		respBody.Github = userobj.Github
	}

	if authorization.Facebook {
		respBody.Facebook = userobj.Facebook
	}

	if authorization.Addresses != nil {
		for _, addressmap := range authorization.Addresses {
			address, err := userobj.GetAddressByLabel(addressmap.RealLabel)
			if err == nil {
				newaddress := user.Address{
					Label:      addressmap.RequestedLabel,
					City:       address.City,
					Country:    address.Country,
					Nr:         address.Nr,
					Other:      address.Other,
					Postalcode: address.Postalcode,
					Street:     address.Street,
				}
				respBody.Addresses = append(respBody.Addresses, newaddress)
			} else {
				log.Debug(err)
			}
		}
	}

	if authorization.EmailAddresses != nil {
		for _, emailmap := range authorization.EmailAddresses {
			email, err := userobj.GetEmailAddressByLabel(emailmap.RealLabel)
			if err == nil {
				newemail := user.EmailAddress{
					Label:        emailmap.RequestedLabel,
					EmailAddress: email.EmailAddress,
				}
				respBody.EmailAddresses = append(respBody.EmailAddresses, newemail)
			} else {
				log.Debug(err)
			}
		}
	}

	if authorization.Phonenumbers != nil {
		for _, phonemap := range authorization.Phonenumbers {
			phonenumber, err := userobj.GetPhonenumberByLabel(phonemap.RealLabel)
			if err == nil {
				newnumber := user.Phonenumber{
					Label:       phonemap.RequestedLabel,
					Phonenumber: phonenumber.Phonenumber,
				}
				respBody.Phonenumbers = append(respBody.Phonenumbers, newnumber)
			} else {
				log.Debug(err)
			}
		}
	}

	if authorization.BankAccounts != nil {
		for _, bankmap := range authorization.BankAccounts {
			bank, err := userobj.GetBankAccountByLabel(bankmap.RealLabel)
			if err == nil {
				newbank := user.BankAccount{
					Label:   bankmap.RequestedLabel,
					Bic:     bank.Bic,
					Country: bank.Country,
					Iban:    bank.Iban,
				}
				respBody.BankAccounts = append(respBody.BankAccounts, newbank)
			} else {
				log.Debug(err)
			}
		}
	}

	if authorization.DigitalWallet != nil {
		for _, addressMap := range authorization.DigitalWallet {
			walletAddress, err := userobj.GetDigitalAssetAddressByLabel(addressMap.RealLabel)
			if err == nil {
				walletAddress.Label = addressMap.RequestedLabel
				respBody.DigitalWallet = append(respBody.DigitalWallet, walletAddress)
			} else {
				log.Debug(err)
			}
		}
	}

	if authorization.PublicKeys != nil {
		for _, publicKeyMap := range authorization.PublicKeys {
			publicKey, err := userobj.GetPublicKeyByLabel(publicKeyMap.RealLabel)
			if err == nil {
				publicKey.Label = publicKeyMap.RequestedLabel
				respBody.PublicKeys = append(respBody.PublicKeys, publicKey)
			} else {
				log.Debug(err)
			}
		}
	}

	if authorization.Avatars != nil {
		for _, avatarMap := range authorization.Avatars {
			avatar, err := userobj.GetAvatarByLabel(avatarMap.RealLabel)
			if err == nil {
				avatar.Label = avatarMap.RequestedLabel
				respBody.Avatars = append(respBody.Avatars, avatar)
			} else {
				log.Debug(err)
			}
		}
	}

	if authorization.Organizations != nil {
		respBody.Organizations = authorization.Organizations
	}

	valMgr := validationdb.NewManager(r)
	if authorization.ValidatedEmailAddresses != nil {
		for _, validatedEmailMap := range authorization.ValidatedEmailAddresses {
			email, err := userobj.GetEmailAddressByLabel(validatedEmailMap.RealLabel)
			if err == nil {
				validated, err := valMgr.IsEmailAddressValidated(authorization.Username, email.EmailAddress)
				if err != nil {
					log.Error("Failed to verify if email address is validated for this user: ", err)
					continue
				}
				if !validated {
					continue
				}
				email.Label = validatedEmailMap.RequestedLabel
				respBody.ValidatedEmailAddresses = append(respBody.ValidatedEmailAddresses, email)
			} else {
				log.Debug(err)
			}
		}

		if authorization.ValidatedPhonenumbers != nil {
			for _, validatedPhoneMap := range authorization.ValidatedPhonenumbers {
				phone, err := userobj.GetPhonenumberByLabel(validatedPhoneMap.RealLabel)
				if err == nil {
					validated, err := valMgr.IsPhonenumberValidated(authorization.Username, phone.Phonenumber)
					if err != nil {
						log.Error("Failed to verify if phone number is validated for this user: ", err)
						continue
					}
					if !validated {
						continue
					}
					phone.Label = validatedPhoneMap.RequestedLabel
					respBody.ValidatedPhonenumbers = append(respBody.ValidatedPhonenumbers, phone)
				} else {
					log.Debug(err)
				}
			}
		}
	}

	if authorization.OwnerOf.EmailAddresses != nil {
		respBody.OwnerOf.EmailAddresses = authorization.OwnerOf.EmailAddresses
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(respBody)
}
296578
func fetchUserInfo(url, accessToken string, transport http.RoundTripper) (map[string]interface{}, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))

	client := &http.Client{Transport: transport}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("non-200 response from UserInfo: %d, WWW-Authenticate=%s", resp.StatusCode, resp.Header.Get("WWW-Authenticate"))
	}

	// The UserInfo Claims MUST be returned as the members of a JSON object
	// http://openid.net/specs/openid-connect-core-1_0.html#UserInfoResponse
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return getJSON(data)
}
1192897
func (a *AccountService) Info() (AccountInfo, error) {
	req, err := a.client.newAuthenticatedRequest("GET", "account_infos", nil)

	if err != nil {
		return AccountInfo{}, err
	}

	var v []AccountInfo
	_, err = a.client.do(req, &v)

	if err != nil {
		return AccountInfo{}, err
	}

	return v[0], nil
}
770959
func (c *Client) ModelUserInfo() ([]params.ModelUserInfo, error) {
	var results params.ModelUserInfoResults
	err := c.facade.FacadeCall("ModelUserInfo", nil, &results)
	if err != nil {
		return nil, errors.Trace(err)
	}

	info := []params.ModelUserInfo{}
	for i, result := range results.Results {
		if result.Result == nil {
			return nil, errors.Errorf("unexpected nil result at position %d", i)
		}
		info = append(info, *result.Result)
	}
	return info, nil
}
595117
func (user *User) GetUserInfo(openID string) (userInfo *Info, err error) {
	var accessToken string
	accessToken, err = user.GetAccessToken()
	if err != nil {
		return
	}

	uri := fmt.Sprintf(userInfoURL, accessToken, openID)
	var response []byte
	response, err = util.HTTPGet(uri)
	if err != nil {
		return
	}
	userInfo = new(Info)
	err = json.Unmarshal(response, userInfo)
	if err != nil {
		return
	}
	if userInfo.ErrCode != 0 {
		err = fmt.Errorf("GetUserInfo Error , errcode=%d , errmsg=%s", userInfo.ErrCode, userInfo.ErrMsg)
		return
	}
	return
}
853325
func (a *Config) GetUserName(c echo.Context) string {
	username, _, _ := c.Request().BasicAuth()
	return username
}
989304
func (s *service) RetrieveUserInfoByUserId(userId uint) (resDTO rest.ResponseDTOUserInfo, error *servicehelper.Error) {
	entity, err := s.repo.FindByID(userId)
	if err != nil {
		return rest.ResponseDTOUserInfo{}, &servicehelper.Error{Detail: errors.New("no result found"), Code: servicehelper.NotFound}
	}
	return rest.ResponseDTOUserInfo{
		UserId: entity.ID,
		Email:  entity.Email,
	}, nil
}
692338
func (p *Provider) UserInfo(ctx context.Context, tokenSource oauth2.TokenSource) (*UserInfo, error) {
	if p.UserInfoURL == "" {
		return nil, ErrNotSupported
	}
	cli := oauth2.NewClient(ctx, tokenSource)
	resp, err := cli.Get(p.UserInfoURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("%s: %s", resp.Status, body)
	}

	var userInfo UserInfo
	if err := json.Unmarshal(body, &userInfo); err != nil {
		return nil, fmt.Errorf("oidc: failed to decode userinfo: %v", err)
	}
	userInfo.claims = body
	return &userInfo, nil
}
925785
func (c *Client) GetInfo() (*Info, error) {
	r := c.NewRequest("GET", "/v2/info")
	resp, err := c.DoRequest(r)
	if err != nil {
		return nil, errors.Wrap(err, "Error requesting info")
	}
	defer resp.Body.Close()
	var i Info
	err = json.NewDecoder(resp.Body).Decode(&i)
	if err != nil {
		return nil, errors.Wrap(err, "Error unmarshalling info")
	}
	return &i, nil
}
845085
func (c *Client) UserInfo(usernames []string, all IncludeDisabled) ([]params.UserInfo, error) {
	var results params.UserInfoResults
	var entities []params.Entity
	for _, username := range usernames {
		if !names.IsValidUser(username) {
			return nil, errors.Errorf("%q is not a valid username", username)
		}
		tag := names.NewUserTag(username)
		entities = append(entities, params.Entity{Tag: tag.String()})
	}
	args := params.UserInfoRequest{
		Entities:        entities,
		IncludeDisabled: bool(all),
	}
	err := c.facade.FacadeCall("UserInfo", args, &results)
	if err != nil {
		return nil, errors.Trace(err)
	}
	// Only need to look for errors if users were explicitly specified, because
	// if we didn't ask for any, we should get all, and we shouldn't get any
	// errors for listing all.  We care here because we index into the users
	// slice.
	if len(results.Results) == len(usernames) {
		var errorStrings []string
		for i, result := range results.Results {
			if result.Error != nil {
				annotated := errors.Annotate(result.Error, usernames[i])
				errorStrings = append(errorStrings, annotated.Error())
			}
		}
		// TODO(wallyworld) - we should return these errors to the caller so that any
		// users which are successfully found can be handled.
		if len(errorStrings) > 0 {
			return nil, errors.New(strings.Join(errorStrings, ", "))
		}
	}
	info := []params.UserInfo{}
	for i, result := range results.Results {
		if result.Result == nil {
			return nil, errors.Errorf("unexpected nil result at position %d", i)
		}
		info = append(info, *result.Result)
	}
	return info, nil
}
427277
func (c *Client) GetUser(name string) (services.User, error) {
	if name == "" {
		return nil, trace.BadParameter("missing username")
	}
	out, err := c.Get(c.Endpoint("users", name), url.Values{})
	if err != nil {
		return nil, trace.Wrap(err)
	}
	user, err := services.GetUserMarshaler().UnmarshalUser(out.Bytes(), services.SkipValidation())
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return user, nil
}
808264
func Convert_v1_UserInfo_To_authentication_UserInfo(in *v1.UserInfo, out *authentication.UserInfo, s conversion.Scope) error {
	return autoConvert_v1_UserInfo_To_authentication_UserInfo(in, out, s)
}
302641
func (c *Client) GetInfo() (info Info, err error) {
	r := c.NewRequest("GET", "/info")
	resp, err := c.DoRequest(r)

	if err != nil {
		log.Printf("Error requesting info %v", err)
		return
	}
	defer resp.Body.Close()

	resBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Printf("Error reading info request %v", resBody)
		return
	}
	err = json.Unmarshal(resBody, &info)
	if err != nil {
		log.Printf("Error unmarshaling info %v", err)
		return
	}
	return
}
274629
func (conn *Connection) GetUser(username string, userData interface{},
	auth Auth) (string, error) {
	userDb := conn.SelectDB("_users", auth)
	namestring := "org.couchdb.user:" + username
	return userDb.Read(namestring, &userData, nil)
}
494999
func GetUsername() *string {
	// user.Current only fails on some internal cache error: not sure what
	// corrective action is appropriate... on failure return NULL.
	if u, err := user.Current(); err == nil {
		return &u.Username
	}
	return nil
}
389054
func (s *UserService) GetUser(p *GetUserParams) (*GetUserResponse, error) {
	resp, err := s.cs.newRequest("getUser", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r GetUserResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}
1222670
func extractUserInfo(ctx context.Context) (*raven.User, error) {
	m, err := token.ReadManagerFromContext(ctx)
	if err != nil {
		return nil, err
	}

	q := *m
	token := goajwt.ContextJWT(ctx)
	if token == nil {
		return nil, fmt.Errorf("no token found in context")
	}
	t, err := q.ParseToken(ctx, token.Raw)
	if err != nil {
		return nil, err
	}

	return &raven.User{
		Username: t.Username,
		Email:    t.Email,
		ID:       t.Subject,
	}, nil
}