示例#1
0
func (a *AuthAdaptorOauth) RegisterUser(user kit.User, data map[string]interface{}) (kit.AuthItem, apperror.Error) {
	serviceName, _ := GetStringFromMap(data, "service")
	if serviceName == "" {
		return nil, apperror.New("invalid_data_missing_service")
	}

	service := a.services[serviceName]
	if service == nil {
		return nil, &apperror.Err{
			Code:    "unconfigured_service",
			Message: fmt.Sprintf("The oauth service '%v' was not configured in oauth auth adaptor", serviceName),
		}
	}

	accessToken, _ := GetStringFromMap(data, "access_token")
	if accessToken == "" {
		return nil, apperror.New("invalid_data_missing_access_token")
	}

	// Exchange access token for long lived token.
	// This also verifies that the supplied token is valid.
	appToken, err := service.Exchange(accessToken)
	if err != nil {
		return nil, apperror.Wrap(err, "oauth_exchange_token_error", "")
	}

	userData, err := service.GetUserData(appToken)
	if err != nil {
		return nil, apperror.Wrap(err, "fetch_user_data_failed", "")
	}

	if userData.Id == "" {
		return nil, &apperror.Err{
			Code:    "fetched_userdata_missing_user_id",
			Message: "The userData fetched from the service does not contain a userId",
		}
	}

	item := &AuthItemOauth{
		Service:        serviceName,
		UserId:         user.GetStrId(),
		ExternalUserId: userData.Id,
		Token:          appToken,
	}
	item.Id = serviceName + "_" + userData.Id

	// Fill in user information.

	if user.GetEmail() == "" {
		if userData.Email != "" {
			user.SetEmail(userData.Email)
			user.SetIsEmailConfirmed(true)
		} else {
			return nil, &apperror.Err{
				Code:    "oauth_service_insufficient_data_error",
				Message: fmt.Sprintf("The oauth service %v did not supply the users email, which is required", serviceName),
			}
		}
	}

	if user.GetUsername() == "" && userData.Username != "" {
		user.SetUsername(userData.Username)
	}

	return item, nil
}