Example #1
0
func TestPublicData_WithArray(t *testing.T) {

	o := new(test.TestObjectWithFacade)
	o1 := new(test.TestObjectWithFacade)
	o2 := new(test.TestObjectWithFacade)

	arr := []interface{}{o, o1, o2}

	o.Mock.On("PublicData", map[string]interface{}{}).Return(objx.New(map[string]interface{}{"theName": "1"}), nil)
	o1.Mock.On("PublicData", map[string]interface{}{}).Return(objx.New(map[string]interface{}{"theName": "2"}), nil)
	o2.Mock.On("PublicData", map[string]interface{}{}).Return(objx.New(map[string]interface{}{"theName": "3"}), nil)

	public, err := PublicData(arr, map[string]interface{}{})

	if assert.Nil(t, err) {
		assert.Equal(t, reflect.Slice, reflect.TypeOf(public).Kind(), "Result should be array not %v", reflect.TypeOf(public))
	}

	mock.AssertExpectationsForObjects(t, o.Mock, o1.Mock, o2.Mock)

	publicArray := public.([]interface{})
	if assert.Equal(t, 3, len(publicArray)) {
		assert.Equal(t, publicArray[0].(objx.Map).Get("theName").Str(), "1", "o")
		assert.Equal(t, publicArray[1].(objx.Map).Get("theName").Str(), "2", "o1")
		assert.Equal(t, publicArray[2].(objx.Map).Get("theName").Str(), "3", "o2")
	}

}
Example #2
0
func (rule *Rule) Check(cell *Cell) {
	if cell != nil && !rule.shouldCheck {
		// Don't invoke js if no cells mentioned in the
		// condition callback changed. If rules are run
		// not due to a cell being changed, still need
		// to call JS though.
		return
	}
	rule.tracker.StartTrackingDeps()
	shouldFire, newValue := rule.cond.Check(cell)
	var args objx.Map
	rule.tracker.StoreRuleDeps(rule)
	rule.shouldCheck = false

	switch {
	case !shouldFire:
		return
	case newValue != nil:
		args = objx.New(map[string]interface{}{
			"newValue": newValue,
		})
	case cell != nil:
		args = objx.New(map[string]interface{}{
			"device":   cell.DevName(),
			"cell":     cell.Name(),
			"newValue": cell.Value(),
		})
	}
	rule.then(args)
}
Example #3
0
func loginHandler(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	action := segs[2]
	provider := segs[3]

	switch action {

	case "login":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error while getting provider:", provider, " : ", err)
		}
		loginUrl, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("Error while getting GetBeginAuthURL for", provider, " : ", err)
		}
		w.Header().Set("Location", loginUrl)
		w.WriteHeader(http.StatusTemporaryRedirect)

	case "callback":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error while getting provider:", provider, " : ", err)
		}
		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("Error while completing auth for", provider, " : ", err)
		}

		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("Error while getting user for", provider)
		}

		// User Id is a md5 of the name
		m := md5.New()
		io.WriteString(m, strings.ToLower(user.Email()))
		userId := fmt.Sprintf("%x", m.Sum(nil))

		// save some data
		authCookieValue := objx.New(map[string]interface{}{
			"userid":     userId,
			"name":       user.Name(),
			"avatar_url": user.AvatarURL(),
			"email":      user.Email(),
		}).MustBase64()
		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/",
		})

		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)

	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "Auth action %s not supported", action)
	}
}
Example #4
0
// PublicDataMap calls PublicData and returns the result after type asserting to objx.Map
func PublicDataMap(object interface{}, options map[string]interface{}) (objx.Map, error) {

	data, err := publicData(object, 0, options)

	if err != nil {
		return nil, err
	}

	if data == nil {
		return nil, nil
	}

	switch data.(type) {
	case map[string]interface{}:
		return objx.New(data.(map[string]interface{})), nil
	case objx.Map:
		return data.(objx.Map), nil
	default:
		if dataMap, ok := data.(objx.Map); ok {
			return dataMap, nil
		} else {
			panic(fmt.Sprintf("codecs: PublicDataMap must refer to a map[string]interface{} or objx.Map, not %s.  Did you mean to implement the Facade interface?", reflect.TypeOf(data)))
		}
	}
}
Example #5
0
func callbackHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	providerName := kami.Param(ctx, "provider")

	provider, err := gomniauth.Provider(providerName)
	if err != nil {
		log.Fatalln("認証プロバイダーの取得に失敗しました", provider, "-", err)
	}
	creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
	if err != nil {
		log.Fatalln("認証を完了できませんでした", provider, "-", err)
	}
	user, err := provider.GetUser(creds)
	if err != nil {
		log.Fatalln("ユーザーの取得に失敗しました", provider, "- ", err)
	}

	authCookieValue := objx.New(map[string]interface{}{
		"name": user.Name(),
	}).MustBase64()

	http.SetCookie(w, &http.Cookie{
		Name:  "auth",
		Value: authCookieValue,
		Path:  "/"})
	log.Println("######### ", authCookieValue)

	w.Header()["Location"] = []string{"/"}
	w.WriteHeader(http.StatusTemporaryRedirect)
}
Example #6
0
func (ctx *ESContext) getJSObject(objIndex int, top bool) interface{} {
	t := duktape.Type(ctx.GetType(-1))
	switch {
	case t.IsNone() || t.IsUndefined() || t.IsNull(): // FIXME
		return nil // FIXME
	case t.IsBool():
		return ctx.GetBoolean(objIndex)
	case t.IsNumber():
		return ctx.GetNumber(objIndex)
	case t.IsString():
		return ctx.GetString(objIndex)
	case t.IsObject():
		if ctx.IsArray(objIndex) {
			return ctx.getArray(objIndex)
		}
		m := ctx.getObject(objIndex)
		if top {
			return objx.New(m)
		} else {
			return m
		}
	case t.IsBuffer():
		wbgo.Error.Println("buffers aren't supported yet")
		return nil
	case t.IsPointer():
		return ctx.GetPointer(objIndex)
	default:
		wbgo.Error.Panicf("bad object type %d", t)
		return nil // avoid compiler warning
	}
}
Example #7
0
// loginHandlerはサードパーティーへのログインの処理を受け持ちます
// パスの形式: /auth/{action}/{provider}
func loginHandler(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	action := segs[2]
	provider := segs[3]
	switch action {
	case "login":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("認証プロバイダーの取得に失敗しました:", provider, "-", err)
		}
		loginUrl, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("GetBeginAuthURL の呼び出し中にエラーが発生しました:", provider, "-", err)
		}
		w.Header().Set("Location", loginUrl)
		w.WriteHeader(http.StatusTemporaryRedirect)
	case "callback":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("認証プロバイダーの取得に失敗しました", provider, "-", err)
		}

		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("認証を完了できませんでした", provider, "-", err)
		}

		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("ユーザーの取得に失敗しました", provider, "-", err)
		}

		chatUser := &chatUser{User: user}
		m := md5.New()
		io.WriteString(m, strings.ToLower(user.Name()))
		chatUser.uniqueID = fmt.Sprintf("%x", m.Sum(nil))
		avatarURL, err := avatars.GetAvatarURL(chatUser)
		if err != nil {
			log.Fatalln("GetAvatarURLに失敗しました", "-", err)
		}

		// データを保存します
		authCookieValue := objx.New(map[string]interface{}{
			"userid":     chatUser.uniqueID,
			"name":       user.Name(),
			"avatar_url": avatarURL,
		}).MustBase64()
		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/"})

		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "アクション%sには非対応です", action)
	}
}
Example #8
0
File: auth.go Project: onufert/chat
//loginHandler handle the third party login process
//format: /auth/{action}/{provider}
func loginHandler(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	if len(segs) != 4 {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprintf(w, "Invalid URL path %s", r.URL.Path)
		return
	}
	action := segs[2]
	provider := segs[3]
	switch action {
	case "login":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}
		loginURL, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("Error when trying to GetBeginAuthURL for", provider, "-", err)
		}
		w.Header().Set("Location", loginURL)
		w.WriteHeader(http.StatusTemporaryRedirect)
	case "callback":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}
		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("Error when trying to complete auth for", provider, "-", err)
		}
		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("Error when trying to get user creds for", provider, "-", err)
		}
		chatUser := &chatUser{User: user}
		m := md5.New()
		io.WriteString(m, strings.ToLower(user.Email()))
		userid := fmt.Sprintf("%x", m.Sum(nil))
		chatUser.uniqueID = userid
		avatarURL, err := avatars.GetAvatarURL(chatUser)
		if err != nil {
			log.Fatalln("Error when trying to getAvatarURL", "-", err)
		}
		authCookieValue := objx.New(map[string]interface{}{
			"userID":     userid,
			"name":       user.Name(),
			"avatar_url": avatarURL,
		}).MustBase64()
		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/"})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "Auth action %s not supported", action)
	}
}
Example #9
0
// loginHandler handles the third-party login process.
func loginHandler(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	action := segs[2]
	provider := segs[3]
	switch action {
	case "login":

		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}

		loginUrl, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("Error when trying to GetBeginAuthURL for", provider, "-", err)
		}

		w.Header()["Location"] = []string{loginUrl}
		w.WriteHeader(http.StatusTemporaryRedirect)

	case "callback":

		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}

		// get the credentials
		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("Error when trying to complete auth for", provider, "-", err)
		}

		// get the user
		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("Error when trying to get user from", provider, "-", err)
		}

		// save some data
		authCookieValue := objx.New(map[string]interface{}{
			"name": user.Name(),
		}).MustBase64()
		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/"})

		w.Header().Set("Location", "/chat")
		w.WriteHeader(http.StatusTemporaryRedirect)

	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "Auth action %s not supported", action)
	}
}
Example #10
0
// ProviderPublicData gets the public data for the specified provider.
//
// The options should contain the `loginpathFormat`, which will determine how the
// loginpath value is created.
func ProviderPublicData(provider common.Provider, options map[string]interface{}) (interface{}, error) {

	optionsx := objx.New(options)

	return map[string]interface{}{
		"name":      provider.Name(),
		"display":   provider.DisplayName(),
		"loginpath": fmt.Sprintf(optionsx.Get("loginpathFormat").Str("auth/%s/login"), provider.Name()),
	}, nil

}
Example #11
0
func loginHandler(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	action := segs[2]
	provider := segs[3]
	switch action {

	case "login":

		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatal("Failed autorizatoin: ", provider, "-", err)
		}

		loginURL, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("Had error during calling GetBeginAuthURL:", provider, "-", err)
		}

		w.Header().Set("Location", loginURL)
		w.WriteHeader(http.StatusTemporaryRedirect)

	case "callback":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("failed to get authorization from auth provider", provider, "-", err)
		}

		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("Could not finish authorization", provider, "-", err)
		}

		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("failed get user", provider, "-", err)
		}

		authCookieValue := objx.New(map[string]interface{}{
			"name":       user.Name(),
			"avatar_url": user.AvatarURL(),
		}).MustBase64()

		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/"})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)

	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "can't handle action: %s", action)
	}
}
Example #12
0
func (engine *ESEngine) esWbSpawn() int {
	if engine.ctx.GetTop() != 5 || !engine.ctx.IsArray(0) || !engine.ctx.IsBoolean(2) ||
		!engine.ctx.IsBoolean(3) {
		return duktape.DUK_RET_ERROR
	}

	args := engine.ctx.StringArrayToGo(0)
	if len(args) == 0 {
		return duktape.DUK_RET_ERROR
	}

	callbackFn := ESCallbackFunc(nil)

	if engine.ctx.IsFunction(1) {
		callbackFn = engine.ctx.WrapCallback(1)
	} else if !engine.ctx.IsNullOrUndefined(1) {
		return duktape.DUK_RET_ERROR
	}

	var input *string
	if engine.ctx.IsString(4) {
		instr := engine.ctx.GetString(4)
		input = &instr
	} else if !engine.ctx.IsNullOrUndefined(4) {
		return duktape.DUK_RET_ERROR
	}

	captureOutput := engine.ctx.GetBoolean(2)
	captureErrorOutput := engine.ctx.GetBoolean(3)
	go func() {
		r, err := Spawn(args[0], args[1:], captureOutput, captureErrorOutput, input)
		if err != nil {
			wbgo.Error.Printf("external command failed: %s", err)
			return
		}
		if callbackFn != nil {
			engine.model.CallSync(func() {
				args := objx.New(map[string]interface{}{
					"exitStatus": r.ExitStatus,
				})
				if captureOutput {
					args["capturedOutput"] = r.CapturedOutput
				}
				args["capturedErrorOutput"] = r.CapturedErrorOutput
				callbackFn(args)
			})
		} else if r.ExitStatus != 0 {
			wbgo.Error.Printf("command '%s' failed with exit status %d",
				strings.Join(args, " "), r.ExitStatus)
		}
	}()
	return 0
}
Example #13
0
func loginHandler(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	action := segs[2]
	provider := segs[3]

	switch action {
	case "login":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Failed to get authentication provider from ", provider, " - ", err)
		}
		loginURL, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("Failed in GetBeginAuthURL for ", provider, " - ", err)
		}
		w.Header().Set("Location", loginURL)
		w.WriteHeader(http.StatusTemporaryRedirect)
	case "callback":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Failed to get authentication provider from ", provider, " - ", err)
		}

		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("Failed in authentication for ", provider, " - ", err)
		}

		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("Failed to get user from ", provider, " - ", err)
		}

		authCookieValue := objx.New(map[string]interface{}{
			"name":  user.Name(),
			"email": user.Email(),
		}).MustBase64()

		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/",
		})

		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "action %s is not supported", action)
	}
}
Example #14
0
func loginHandler(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	action := segs[2]
	provider := segs[3]
	switch action {
	case "login":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("認証プロバイダーの取得に失敗しました:", provider, "-", err)
		}
		loginUrl, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("GetBeginAuthURLの呼び出し中にエラーが発生しました", provider, "-", err)
		}
		w.Header().Set("Location", loginUrl)
		w.WriteHeader(http.StatusTemporaryRedirect)
	case "callback":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("認証プロバイダーの取得に失敗しました。", provider, "-", err)
		}

		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("認証を完了できませんでした", provider, "-", err)
		}

		user, err := provider.GetUser(creds)

		if err != nil {
			log.Fatalln("ユーザーの取得に失敗しました", provider, "-", err)
		}

		authCookieValue := objx.New(map[string]interface{}{
			"name": user.Name(),
		}).MustBase64()

		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/",
		})

		w.Header().Set("Location", "/chat")
		w.WriteHeader(http.StatusTemporaryRedirect)

	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "アクション%sには非対応です", action)
	}
}
Example #15
0
func TestPublicDataMap(t *testing.T) {

	o := new(test.TestObjectWithFacade)
	o.Mock.On("PublicData", map[string]interface{}{}).Return(objx.New(map[string]interface{}{"theName": "Mat"}), nil)

	public, err := PublicDataMap(o, map[string]interface{}{})

	if assert.Nil(t, err) {
		assert.Equal(t, public.Get("theName").Str(), "Mat")
	}

	mock.AssertExpectationsForObjects(t, o.Mock)

}
Example #16
0
func loginHandler(w http.ReponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	action := segs[2]
	provider := segs[3]
	switch action {
	case "login":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("fail to get provider", provider, "-", err)
		}
		loginUrl, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("error GetBeginAuthURL", provider, "-", err)
		}
		w.Header().Set("Location", loginUrl)
		w.WriteHeader(http.StatusTemporaryRedirect)
	case "callback":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("fail to get provider", provider, "-", err)
		}
		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("error CompleteAuth", provider, "-", err)
		}
		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("error GetUser", provider, "-", err)
		}
		authCookieValue := objx.New(map[string]interface{}{
			"name": user.Name(),
		}).MustBase64()
		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/",
		})
		w.Header()["Location"] = []string("/2/1")
		w.WriteHeader(http.StatusTemporaryRedirect)

	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "not accept %s", action)
	}
}
Example #17
0
// Marshal converts an object to a []byte representation.
// You can optionally pass additional arguments to further customize this call.
func (c *SimpleXmlCodec) Marshal(object interface{}, options map[string]interface{}) ([]byte, error) {

	var output []string

	// add the declaration
	output = append(output, XMLDeclaration)

	// add the rest of the XML
	bytes, err := marshal(object, true, 0, objx.New(options))

	if err != nil {
		return nil, err
	}

	output = append(output, string(bytes))

	// return the output
	return []byte(strings.Join(output, "")), nil
}
Example #18
0
func (engine *ESEngine) esWbCellObject() int {
	if engine.ctx.GetTop() != 2 || !engine.ctx.IsString(-1) || !engine.ctx.IsObject(-2) {
		return duktape.DUK_RET_ERROR
	}
	devProxy, ok := engine.ctx.GetGoObject(-2).(*DeviceProxy)
	if !ok {
		wbgo.Error.Printf("invalid _wbCellObject call")
		return duktape.DUK_RET_TYPE_ERROR
	}
	cellProxy := devProxy.EnsureCell(engine.ctx.GetString(-1))
	engine.ctx.PushGoObject(cellProxy)
	engine.ctx.DefineFunctions(map[string]func() int{
		"rawValue": func() int {
			engine.ctx.PushString(cellProxy.RawValue())
			return 1
		},
		"value": func() int {
			m := objx.New(map[string]interface{}{
				"v": cellProxy.Value(),
			})
			engine.ctx.PushJSObject(m)
			return 1
		},
		"setValue": func() int {
			if engine.ctx.GetTop() != 1 || !engine.ctx.IsObject(-1) {
				return duktape.DUK_RET_ERROR
			}
			m, ok := engine.ctx.GetJSObject(-1).(objx.Map)
			if !ok || !m.Has("v") {
				wbgo.Error.Printf("invalid cell definition")
				return duktape.DUK_RET_TYPE_ERROR
			}
			cellProxy.SetValue(m["v"])
			return 1
		},
		"isComplete": func() int {
			engine.ctx.PushBoolean(cellProxy.IsComplete())
			return 1
		},
	})
	return 1
}
Example #19
0
func TestPublicData_WithRecursion_WithObjects(t *testing.T) {

	o := new(test.TestObjectWithFacade)
	o1 := new(test.TestObjectWithFacade)
	o2 := new(test.TestObjectWithFacade)

	args := map[string]interface{}{constants.OptionKeyClientCallback: "~d"}

	o.Mock.On("PublicData", args).Return(o1, nil)
	o1.Mock.On("PublicData", args).Return(o2, nil)
	o2.Mock.On("PublicData", args).Return(objx.New(map[string]interface{}{"theName": "Mat"}), nil)

	public, err := PublicData(o, args)

	if assert.Nil(t, err) {
		assert.Equal(t, public.(objx.Map).Get("theName").Str(), "Mat")
	}

	mock.AssertExpectationsForObjects(t, o.Mock, o1.Mock, o2.Mock)

}
Example #20
0
// loginHandler handles the third-party login process
// format: /auth/{action}/{provider}
// callback: /auth/callback/{provider}
func loginHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("req url path:", r.URL.Path)

	segs := strings.Split(r.URL.Path, "/")
	action := segs[2]
	provider := segs[3]

	switch action {
	case "login":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("error when trying to get provider", provider, "-", err)
		}
		loginUrl, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("error when trying to get GetBeginAuthURL for", provider, "-", err)
		}
		w.Header().Set("Location", loginUrl)
		w.WriteHeader(http.StatusTemporaryRedirect)
	case "callback":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("error when trying to get provider", provider, "-", err)
		}

		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("error when trying to complete auth for", provider, "-", err)
		}

		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("error when trying to get user from", provider, "-", err)
		}

		// log.Println("user name:", user.Name())
		// log.Println("user avatar url:", user.AvatarURL())

		m := md5.New()
		io.WriteString(m, strings.ToLower(user.Name()))

		chatUser := &chatUser{User: user}
		chatUser.uniqueId = fmt.Sprintf("%x", m.Sum(nil))

		avatarUrl, err := avatars.GetAvatarURL(chatUser)
		if err != nil {
			log.Fatalln("error when trying to GetAvatarURL", "-", err)
		}

		// save some data
		authCookieValue := objx.New(map[string]interface{}{
			"userid":     chatUser.UniqueId(),
			"name":       user.Name(),
			"avatar_url": avatarUrl,
		}).MustBase64()

		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/",
		})

		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	default:
		// todo: use /auth/nonsense ?

		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "Auth action %s not supported", action)
	}
}
Example #21
0
File: auth.go Project: oywc410/MYPG
//地址类型 /auth/{action}/{provider}
func loginHandler(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	action := segs[2]
	provider := segs[3]
	switch action {
	case "login": //登入
		log.Println("TODO: 登入处理", provider)
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("认证获取失败", provider, "-", err)
		}
		loginUrl, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("GetBeginAuthUrl获取失败", provider, "-", err)
		}
		w.Header().Set("Location", loginUrl)
		w.WriteHeader(http.StatusTemporaryRedirect)
	case "callback": //认证成功返回信息解析
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("认证获取失败", provider, "-", err)
		}

		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("认证中断未完成", provider, "-", err)
		}

		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("用户信息获取失败", provider, "-", err)
		}

		chatUser := &chatUser{User: user}
		m := md5.New()
		io.WriteString(m, strings.ToLower(user.Name()))
		chatUser.uniqueID = fmt.Sprintf("%x", m.Sum(nil))
		avatarURL, err := avatars.GetAvatarURL(chatUser)
		if err != nil {
			log.Fatalln("GetAvatarURL获取失败", "-", err)
		}

		authCookieValue := objx.New(map[string]interface{}{
			"userid":     chatUser.uniqueID,
			"name":       user.Name(),
			"avatar_url": avatarURL,
		}).MustBase64()

		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/",
		})

		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "操作%s非对应", action)
	}
}
Example #22
0
// loginHandler handles the third-party login process.
// format: /auth/{action}/{provider}
func loginHandler(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	action := segs[2]
	provider := segs[3]
	switch action {
	case "login":
		// get the provider object that matches the object specfied in the URL (such as google or github)
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatal("Error when trying to get provider", provider, "-", err)
		}
		// get the location where we must send users in order to start the authentication process
		// GetBeginAuthURL
		// first argument:
		//   is a state map of data that is encoded, and signed and sent to the authentication provider.
		//   The provider doesn't do anything with the state, it just sends it back to our callback endpoint.
		//   This is useful if, for example, we want to redirect the user back to the original page they were
		//   trying to access before the authentication process intervened. For our purpose, we have only the
		//   /chat endpoint, so we don't need to worry about sending any state.
		// second argument:
		//   is a map of additional options that will be sent to the authentication provider,
		//   which somehow modi es the behavior of the authentication process.
		//   For example, you can specify your own scope parameter, which allows you to make a request
		//   for permission to access additional information from the provider. For more information
		//   about the available options, search for OAuth2 on the Internet or read the documentation
		//   for each provider, as these values differ from service to service.
		loginUrl, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("Error when trying to GetBeginAuthURL for", provider, "-", err)
		}
		w.Header().Set("Location", loginUrl)
		w.WriteHeader(http.StatusTemporaryRedirect)
	case "callback":
		// get the provider
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}

		// exchanging it for an access token as per the OAuth specification
		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("Error when trying to complete auth for", provider, "-", err)
		}

		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("Error when trying to get user from", provider, "-", err)
		}

		m := md5.New()
		io.WriteString(m, strings.ToLower(user.Name()))
		userId := fmt.Sprintf("%x", m.Sum(nil))
		// save some data
		authCookieValue := objx.New(map[string]interface{}{
			"userid":     userId,
			"name":       user.Name(),
			"avatar_url": user.AvatarURL(),
			"email":      user.Email(),
		}).MustBase64()
		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/",
		})

		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "Auth action %s not supported", action)
	}
}
Example #23
0
// loginHandler handles the third-party login process.
// format: /auth/{action}/{provider}
func loginHandler(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	// TODO: handle exception if there are too few segments
	action := segs[2]
	provider := segs[3]
	switch action {
	case "login":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Eerror when trying to get provider", provider, "-", err)
		}
		loginURL, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("error when trying to GetBeginAuthURL for", provider, "-", err)
		}
		// Since http.ResponseWriter is an interface and header is a method on that
		// interface, we have to call it so it will return an http.Header
		// instead of w.Header.Set(...) we use w.Header().Set(...)
		w.Header().Set("Location", loginURL)
		w.WriteHeader(http.StatusTemporaryRedirect)

	case "callback":

		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}
		// Parsin RawQuery from http.Request into objx.Map (multi-purpose map type
		// that gomniauth uses) and the CompleteAuth method uses the URL query param
		// values to complete the authentication handshake. If all is okay - creds
		// are given
		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("Error when trying to complete auth for", provider, "-", err)
		}
		// now accessing user's basic data
		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("Error when trying to get user from", provider, "-", err)
		}
		chatUser := &chatUser{User: user}
		fmt.Println("User authenticated: ", user.Name())
		// creating new md5 hasher from crypto package, implements io.Writer interface
		m := md5.New()
		// ensuring email is lower case and generate md5 hash
		// writing a string of bytes to hasher through io.WriteString
		io.WriteString(m, strings.ToLower(user.Name()))
		// caling Sum on hasher returns the current hash for the bytes written
		chatUser.uniqueID = fmt.Sprintf("%x", m.Sum(nil))
		avatarURL, err := avatars.GetAvatarURL(chatUser)
		if err != nil {
			log.Fatalln("Error when trying to GetAvatarURL", "-", err)
		}
		// encoding user data with Base64 in JSON object
		authCookieValue := objx.New(map[string]interface{}{
			"userid": chatUser.uniqueID,
			"name":   user.Name(),
			// adding avatar URL to cookie
			"avatar_url": avatarURL,
			"email":      user.Email(),
		}).MustBase64()
		// storing encoded object in cookie
		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/"})

		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)

	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "auth action %s not supported", action)

	}
}
Example #24
0
// loginHander handles the third-party login process.
// format: /auth/{action}/{provider}
func loginHander(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	if len(segs) < 4 {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "format: /auth/{action}/{provider}")
		return
	}
	action := segs[2]
	provider := segs[3]
	switch action {
	case "login":
		// redirect users to the provider's authentication page
		// when they land on our /auth/login/{provider} path.
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}

		loginURL, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("Error when trying to GetBeginAuthURL for", provider, "-", err)
		}
		w.Header().Set("Location", loginURL)
		w.WriteHeader(http.StatusTemporaryRedirect)
	case "callback":
		// the provider rediect back to our callback endpoint, the
		// Gomniauth will exchange the grant code for an access token.
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}

		// parse the RawQuery from the http.Request into objx.Map and the
		// CompleteAuth method uses the URL query parameter values to
		// complete the authentication handshake with the provider.
		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("Error when trying to complete auth for", provider, "-", err)
		}

		// use the specified credential to access the basic user info.
		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("Error when trying to get user from", provider, "-", err)
		}

		chatUser := &chatUser{User: user}
		// create a new md5 hasher, because the hasher implements
		// the io.Writer interface, we can use io.WriteString to
		// write a string of bytes to it. Calling Sum returns the
		// current hash for the bytes written.
		m := md5.New()
		io.WriteString(m, strings.ToLower(user.Email()))
		chatUser.uniqueID = fmt.Sprintf("%x", m.Sum(nil))
		avatarURL, err := avatars.GetAvatarURL(chatUser)
		if err != nil {
			log.Fatalln("Error when trying to GetAvatarURL", "-", err)
		}
		// save the auth info into cookie
		authCookieValue := objx.New(map[string]interface{}{
			"userid":     chatUser.uniqueID,
			"name":       user.Name(),
			"avatar_url": avatarURL,
		}).MustBase64()
		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/",
		})

		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	default:
		// write out an error message and return an
		// http.StatusNotFound status code (404)
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "Auth action %s not supported", action)
	}
}
Example #25
0
func loginHander(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	action := segs[2]
	provider := segs[3]

	switch action {
	case "login":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}

		loginUrl, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("Error when trying to GetBeginAuthURL for", provider, "-", err)
		}
		w.Header()["Location"] = []string{loginUrl}
		w.WriteHeader(http.StatusTemporaryRedirect)

	case "callback":
		provider, err := gomniauth.Provider(provider)

		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}

		//get the credentials
		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}

		//get the user
		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("Error when trying to get user from", provider, "-", err)
		}
		chatUser := &chatUser{User: user}
		m := md5.New()
		io.WriteString(m, strings.ToLower(user.Name()))
		chatUser.uniqueID = fmt.Sprintf("%x", m.Sum(nil))

		avatarURL, err := avatars.GetAvatarURL(chatUser)
		if err != nil {
			log.Fatalln("Error when trying to GetAvatarURL", "-", err)
		}

		//save data
		authCookieValue := objx.New(map[string]interface{}{
			"userid":     chatUser.uniqueID,
			"name":       user.Name(),
			"avatar_url": avatarURL,
			"email":      user.Email(),
		}).MustBase64()

		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/"})

		w.Header().Set("Location", "/chat")
		w.WriteHeader(http.StatusTemporaryRedirect)

	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprint(w, "Auth actions %s no supported", action)
	}
}
Example #26
0
File: auth.go Project: mxjxn/gochat
func loginHandler(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	action := segs[2]
	provider := segs[3]
	switch action {
	case "callback":
		providerobj, err := gomniauth.Provider(provider)
		log.Println("providerobj: ", providerobj)
		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}

		omap, err := objx.FromURLQuery(r.URL.RawQuery)
		log.Println(omap)
		if err != nil {
			log.Fatalln("Error when trying to get object from query", provider, "-", err)
		}

		creds, err := providerobj.CompleteAuth(omap)
		log.Println("creds: ", creds, err)
		if err != nil {
			log.Fatalln("Error when trying to complete auth for", provider, "-", err)
		}

		log.Println("retrieving user")
		user, err := providerobj.GetUser(creds)
		log.Println("user: "******"Error when trying to get user from", provider, "-", err)
		}

		m := md5.New()
		io.WriteString(m, strings.ToLower(user.Name()))
		userId := fmt.Sprintf("%x", m.Sum(nil))
		authCookieValue := objx.New(map[string]interface{}{
			"userid":     userId,
			"name":       user.Name(),
			"avatar_url": user.AvatarURL(),
			"email":      user.Email(),
		}).MustBase64()
		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/"})
		w.Header()["Location"] = []string{"/chat"}
		w.WriteHeader(http.StatusTemporaryRedirect)
	case "login":
		providerobj, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error when trying to get the provider", provider, "-", err)
		}
		loginUrl, err := providerobj.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("error when trying to GetBeginAuthURL for", provider, "-", err)
		}
		w.Header().Set("Location", loginUrl)
		w.WriteHeader(http.StatusTemporaryRedirect)
	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "Auth action %s not supported", action)
	}
}
Example #27
0
// loginHandler handles the third-party login process.
// 1.ユーザーはプロバイダーを選択する
// 2.プロバイダーのサイトにクライアントアプリケーションのIDと共にリダイレクトされる
// 3.ユーザーはクライアントアプリケーションからのデータへのアクセスを許可
// 4.ユーザーは認可コードと共にクライアントアプリケーションにリダイレクト
// 5.クライアントアプリケーションはプロバイダーに認可コードを送信する
// 6.プロバイダーからクライアントアプリケーションにアクセストークンが送信される
// 7.アクセストークンを使用して、ユーザーの情報にアクセスする
func loginHandler(w http.ResponseWriter, r *http.Request) {
	segs := strings.Split(r.URL.Path, "/")
	action := segs[2]
	provider := segs[3]
	switch action {
	case "login":
		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}

		// func (provider *SoundcloudProvider) GetBeginAuthURL(state *common.State, options objx.Map) (string, error) {...}
		// 認証プロセスが開始される前にリファラーにリダイレクトする場合は第一引数を指定する
		// 認証プロバイダーから追加情報を取得したい場合は第二引数を指定する
		loginURL, err := provider.GetBeginAuthURL(nil, nil)
		if err != nil {
			log.Fatalln("Error when trying to GetBeginAuthURL for", provider, "-", err)
		}

		w.Header()["Location"] = []string{loginURL}
		w.WriteHeader(http.StatusTemporaryRedirect)
	case "callback":

		provider, err := gomniauth.Provider(provider)
		if err != nil {
			log.Fatalln("Error when trying to get provider", provider, "-", err)
		}

		// get the credentials
		creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery))
		if err != nil {
			log.Fatalln("Error when trying to complete auth for", provider, "-", err)
		}

		// get the user
		user, err := provider.GetUser(creds)
		if err != nil {
			log.Fatalln("Error when trying to get user from", provider, "-", err)
		}
		chatUser := &chatUser{User: user}
		m := md5.New()
		io.WriteString(m, strings.ToLower(user.Name()))
		chatUser.uniqueID = fmt.Sprintf("%x", m.Sum(nil))
		avatarURL, err := avatars.URL(chatUser)

		// クッキーにキャッシュされる
		authCookieValue := objx.New(map[string]interface{}{
			"userId":     chatUser.uniqueID,
			"name":       user.Name(),
			"avatar_url": avatarURL,
			"email":      user.Email(),
		}).MustBase64()
		http.SetCookie(w, &http.Cookie{
			Name:  "auth",
			Value: authCookieValue,
			Path:  "/"})

		w.Header().Set("Location", "/chat")
		w.WriteHeader(http.StatusTemporaryRedirect)
	default:
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "Auth action %s not supported", action)
	}
}