Search code examples
gogo-iris

Fetching Logged in User Info for display


I am using https://github.com/kataras/iris Go web framework. I have:

  1. User Registered
  2. User Verified & Logged in
  3. Session created and set with key username with user (table & struct) username

Now, here is my code for logged in user:

// Loaded All DB and other required value above

allRoutes := app.Party("/", logThisMiddleware, authCheck) {
    allRoutes.Get("/", func(ctx context.Context) {
        ctx.View("index.html");
    });
}

In authcheck middleware

func authcheck(ctx context.Context) {
    // Loaded session.
    // Fetched Session key "isLoggedIn"
    // If isLoggedIn == "no" or "" (empty)
    // Redirected to login page
    // else
    ctx.Next()
}

My Session function

func connectSess() *sessions.Sessions {
    // Creating Gorilla SecureCookie Session
    // returning session
}

Now, my problem is, how do I share Logged User value to all routes in template. My Current option is:

// Loaded all DB and required value
allRoutes := app.Party("/", logThisMiddleware, authCheck) {

    allRoutes.Get("/", func(ctx context.Context) {
        // Load Session again
        // Fetch username stored in session
        // Run Query against DB
        // Share the user struct value.
        // Example ctx.ViewData("user", user)
        ctx.View("index.html");
    });

    allRoutes.Get("dashboard", func(ctx context.Context) {
        // Load Session again
        // Fetch username stored in session
        // Run Query against DB
        // Share the user struct value.
        // Example ctx.ViewData("user", user)
        ctx.View("index.html");
    });
}

But problem with above code is, I will have to write session for each route and run query again for each route I run and than share.

I feel, there must be better way of doing it , rather than loading session twice for each route one in authCheck middleware and second inside allRoutes.Get route.

I need ideas on how this can be optimised and user data can be shared to template by just writing code one time and not repeating below for each route

        // Load Session again
        // Fetch username stored in session
        // Run Query against DB
        // Share the user struct value.
        // Example ctx.ViewData("user", user)

Solution

  • it's easy you can use the ctx.Values().Set/Get to make something shareable between your route's handlers or middleware(s).

    // load session manager once
    sess := connectSess()
    
    func authCheck(ctx context.Context) {
        session := sess.Start(ctx)
        // Load your user here.
        // [...]
        // Save the returning user to the local storage of this handlers chain, once. 
        ctx.Values().Set("user", user) // <-- IMPORTANT
    }
    
    app.Get("/", func(ctx context.Context) {
        // Get the user from our handlers chain's local storage.
        user := ctx.Values().Get("user") // <-- IMPORTANT
    
        // Bind the "{{.user}}" to the user instance.
        ctx.ViewData("user", user)
        // Render the template file.
        ctx.View("index.html")
    })
    
    app.Get("dashboard", func(ctx context.Context) {
        // The same, get the user from the local storage...
        user := ctx.Values().Get("user") // <-- IMPORTANT
    
        ctx.ViewData("user", user)
        ctx.View("index.html")
    })
    

    That's all, pretty simple, right?

    But I have some notes for you, read them if you have more time.

    When you're on root "/" you don't have to create a party for it(.Party) in order to add middlewares (begin(Use) or finish(Done)), use just the iris.Application instance, app.Use/Done.

    Don't write this:

    allRoutes := app.Party("/", logThisMiddleware, authCheck) {
    
        allRoutes.Get("/", myHandler)
    }
    

    Do that instead:

    app.Use(logThisMiddleware, authCheck)
    app.Get("/", myHandler)
    

    It's easier to read and understand.

    I've also noticed that you're using ; at the end of your functions, your editor and gocode tool will remove those, when you write a program using the Go Programming Language you shouldn't do that, remove all ;.

    Last, please read the documentation and the examples, we have many of them at https://github.com/kataras/iris/tree/master/_examples , hopes you the best!