获取已登录的用户信息以进行显示 [英] Fetching Logged in User Info for display

查看:166
本文介绍了获取已登录的用户信息以进行显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 https://github.com/kataras/iris Go网络框架.我有:

  1. 用户注册
  2. 经过用户验证的&登录
  3. 使用用户(表和结构)username
  4. 创建并设置键username的会话

现在,这是我用于登录用户的代码:

// Loaded All DB and other required value above

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

在authcheck中间件中

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

我的会话功能

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

现在,我的问题是,如何将已记录的用户"值共享给模板中的所有路由.我当前的选项是:

// 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");
    });
}

但是上面代码的问题是,我将不得不为每个路由编写会话,然后为我运行并共享的每个路由再次运行查询.

我觉得,必须有更好的方法,而不是为authCheck中间件中的每个路由和为allRoutes.Get路由中的第二个路由加载两次会话.

我需要有关如何优化这一点的想法,以及如何通过仅编写一次代码而不在下面为每条路线重复代码就可以将用户数据共享到模板上.

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

解决方案

您可以轻松地使用ctx.Values().Set/Get在路由的处理程序或中间件之间共享某些内容.

// 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")
})

就这么简单,对吧?

但是我有一些笔记,如果您有更多时间请阅读.

当您位于根目录"/"上时,不必为添加中间件(开始(Use)或完成(Done))而为其创建派对(.Party),请使用只是iris.Application实例app.Use/Done.

不要这样写:

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

    allRoutes.Get("/", myHandler)
}

改为:

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

阅读和理解更加容易.

注意到,在使用Go编程编写程序时,您在功能末尾使用了;,您的编辑器和gocode工具将删除这些内容.使用您不应该使用的语言,请删除所有;.

最后,请阅读文档和示例,在 https中有很多示例和示例://github.com/kataras/iris/tree/master/_examples ,祝您一切顺利!

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)

解决方案

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!

这篇关于获取已登录的用户信息以进行显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆