Integrate Golang web app with FireBack

مدیریت کاربران از پیش ساخته شده شما

مطالب پیش رو برای زبان فارسی تهیه نشده است.

If you are new to fireback, keep in mind that Fireback exposes HTTP endpoints, the code here is mostly an snippet that shows how to do it. You can implement it very different way if necessary.

In this document, we are going to implemenet a sample app with Gin framework. Steps for different frameworks might be quite similar.

Create a fireback.go file

You can create this anyway in the project within any namespace, usually a service folder.

1. Add types

We expose user information upon token validation, and the message contains:

type FirebackPassport struct {
	UniqueId    string `json:"uniqueId"`
	Type        string `json:"type"`
	AccessToken string `json:"accessToken"`
}

type FirebackContext struct {
	FirstName string `json:"firstName"`
	LastName  string `json:"lastName"`
	Passports []FirebackPassport
}

2. Create a function to send HTTP Post for validating token

Now, you need a simple function that sends a POST request to fireback endpoint. token is user token which is coming with every protected endpoint in the headers usually, Authorization section.

func getUserInformationFromFireback(token string) (interface{}, error) {
	client := http.Client{}
	config := utils.GetAppConfig()

	// Sample of the URL, usually you want to get this from an env variable or config file
	// req, err := http.NewRequest("POST", "http://localhost:4500/token", nil)
	req, err := http.NewRequest("POST", config.FirebackLocation+"/token", nil)

	q := req.URL.Query()

	req.URL.RawQuery = q.Encode()

	if err != nil {
		return nil, errors.New("FIREBACK_NOT_AVAILABLE")
	}

	req.Header = http.Header{
		"Accept":        {"application/json"},
		"Authorization": {token},
	}

	resp, err := client.Do(req)
	if err != nil {
		return nil, errors.New("FIREBACK_TOKEN_NOT_AVAILABLE")
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		log.Fatalln(err)
	}

	var bodyJson FirebackContext
	json.Unmarshal(body, &bodyJson)
	return bodyJson, nil
}

3. Use the withFireback callback

This function is used when mapping functions to http request in Gin. You might need to implement similar approach if using other frameworks.

func WithFireback() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" {
			c.AbortWithStatusJSON(401, gin.H{
				"error": gin.H{
					"message": "FIREBACK_AUTHORIZATION_TOKEN_IS_NEEDED",
				},
			})
			return
		}

		data, e := getUserInformationFromFireback(token)

		if e != nil {
			c.AbortWithStatusJSON(401, gin.H{
				"error": gin.H{
					"message": "FIREBACK_NOT_AVAILABLE",
				},
			})

			return
		}

		c.Set("fireback_context", data)
	}
}

4. Use it with protected routes.

Now, you need to add this function before every http endpoint you want to have it protected.


r.GET("/user", withFireback(), httpUserHandler)

and you can use it:

func httpGetFiles(c *gin.Context) {

	account, exists := c.Get("fireback_context")
	payload := account.(FirebackContext)

	c.JSON(200, gin.H{
		"data":   payload,
	})
}

Hope you have enjoyed this article, and could implement your own version.