From _t cookie how to get the current user id?

I am trying to develop an app using the same DB as discourse.

Discourse is run from:
www.example.com/forums/

The app is run from:
www.example.com/app/

Inside /app/ app on server side I have access to _t token.

From the _t token how do I get the user id by querying the Postgres DB.

I know I can use SSO but that requires making a request to the client side. So I want to keep things simple and get the logged in user’s identity by just querying the postgres DB directly from inside the app running at www.example.com/app/

In postgres table user_auth_tokens the field auth_tokens has the value “Gzfb6AV4VkGvumpIm54u6hxdBuU”

In the cookie _t the value is 35d802b49d5565441aedf58410064505

From “35d802b49d5565441aedf58410064505” how do I derive “Gzfb6AV4VkGvumpIm54u6hxdBuU” ?

I have the following hypothesis:

  1. In the DB table user_auth_tokens the field auth_tokens is storing the hashed value of the cookie _t.

  2. The hashing is being done by https://github.com/discourse/discourse/blob/c68999e1283ea7f9bc50fe6e8df3c4ddc05b7df0/app/models/user_auth_token.rb#L111

Digest::SHA1.base64digest("#{token}#{GlobalSetting.safe_secret_key_base}")

  1. To get the value of GlobalSetting.safe_secret_key_base from redis I will get the value of SECRET_TOKEN

127.0.0.1:6379> get SECRET_TOKEN
“eadc1240dfa7cccc5801e82f1b302913a91604a0d97dcc1fb7b44d8275037904fa517710d29059e53251f5bf46ebbe16d0686226a6bc5032bbafcc987a2bd30b”

ref: https://github.com/discourse/discourse/blob/a1ee61ec25d8de128faf46d765d1aeda9d880654/app/models/global_setting.rb#L23

Are my hypothesis correct?

When I do sha1 for

35d802b49d5565441aedf58410064505eadc1240dfa7cccc5801e82f1b302913a91604a0d97dcc1fb7b44d8275037904fa517710d29059e53251f5bf46ebbe16d0686226a6bc5032bbafcc987a2bd30b

I get

1b37dbe805785641afba6a489b9e2eea1c5d06e5

And base64digest for 1b37dbe805785641afba6a489b9e2eea1c5d06e5 is: MWIzN2RiZTgwNTc4NTY0MWFmYmE2YTQ4OWI5ZTJlZWExYzVkMDZlNQ==

Why is it not matching the value stored in the table user_auth_tokens the field auth_tokens?

Putting aside the part where this is a Bad Idea™ because eventually Discourse will update and this will break…

Are you sure you did that last step correctly? https://play.golang.org/p/6bWfZ8uDX5

5 Likes

Thank you. it works!!

3 Likes