4

I have started developing web application where the back end is Go. I'm using beego framework to develop this application.Previously i used to program in java. Java has a filter function to filter the request by url. I came to know that we can implement it in beego after reading the documentation. There they have given the following example code

var FilterUser = func(ctx *context.Context) {
    if strings.HasPrefix(ctx.Input.URL(), "/login") {
        return
    }

    _, ok := ctx.Input.Session("uid").(int)
    if !ok {
        ctx.Redirect(302, "/login")
    }
}

beego.InsertFilter("/*", beego.BeforeRouter, FilterUser) 

The problem is I don't know where to use this block of code.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Rajesh Kumar
  • 207
  • 1
  • 6
  • 12

1 Answers1

2

You can do something like the following:

  • Set the URL you want to protect in router and the corresponding filter
  • Create a filter function which will be called by the router and check the user

In more detail:

// A URL set in router.go
beego.InsertFilter("/admin/", beego.BeforeRouter, controllers.ProtectAdminPages)

// A Filter that runs before the controller
// Filter to protect admin pages
var ProtectAdminPages = func(ctx *context.Context) {
    sess, _ := beego.GlobalSessions.SessionStart(ctx.ResponseWriter, ctx.Request)
    defer sess.SessionRelease(ctx.ResponseWriter)
    // read the session from the request
    ses := sess.Get("mysession")
    if ses != nil {
        s := ses.(map[string]string)
        // get the key identifying the user id
        userId, _ := strconv.Atoi(s["id"])
        // a utility function that searches the database
        // gets the user and checks for admin privileges
        if !utils.UserIsAdmin(userId) {
            ctx.Redirect(301, "/some-other-page")
        }
    } else {
        ctx.Redirect(301, "/")
    }
}
Stef K
  • 469
  • 8
  • 13
  • Thanks,Just what i wanted.I have a doubt in this..Do we have to start the session before the login...Sorry new to programming.Thanks – Rajesh Kumar Oct 07 '16 at 01:44
  • You can start the session at application startup, so pick your setup from http://beego.me/docs/mvc/controller/session.md and say in main before beego.run() set session's settings. – Stef K Oct 07 '16 at 17:22
  • Thanks for your help Mr.Stef K – Rajesh Kumar Nov 05 '16 at 00:59