Work with discourse users on an SPA

I am trying to find a way to get user specific data in an SPA from discourse.

Rough setup
SPA running at my-app.com
Discourse running at community.my-app.com

The SPA has no own user management, i would like to use discourse for that (because we have no other user specific stuff that would need an own user management)

But i would like to show the currently logged in user of discourse at the SPA, as well as show a widget of the unread topics (which are user specific) for example, so i need to load data via API from discourse.

Things i tried:

  • Use the Discourse SSO Path, which then redirects back to my SPA. Its fine, i get the current users email address, external id and so on - but nothing i could do the request with (token / key)
  • Playing with cookie settings to be able to use the discourse cookie to make the request (no success)
  • I have read about the user api key at User API keys specification, but i would feel weird for the user to allow an app, which is the same site, to access their discourse account.

Is there any possibility to achieve the behaviour i want?

Regards
Marcel

1 Like

Would this work?

  1. Use DiscourseConnect (ā€œDiscourse SSOā€) as described to get the username for the current user.
  2. Make an API key with the scopes you need and ā€œall usersā€ access.
  3. Obviously you canā€™t pass that key to the web app on the client side without compromising the site, so youā€™ll need to proxy requests from the web app through that appsā€™ backend to your Discourse instance. (And youā€™d need to validate that the username is legit from the backend ā€” I havenā€™t looked at DiscourseConnect but presumably thereā€™s a way to do that.)

(PS: I recommend using ā€˜example.comā€™ for your example domain. Someone could buy the one youā€™ve linked to and set up spam or malware or whatever, whereas example.[com|org|net] are officially reserved.)

1 Like

Yeah thatā€™s actually the way I used to implement it now.

Sending the user through the SSO, the Middleware creates a simple user with name, email and a token array, creates a token, passes it back to the SPA.

The middleware proxies the requests to discourse with an all user API key and validates the ā€œsession tokenā€ (to see which user it is) and some other security magic.

To let the user stay logged in I will use a cookie / local storage and will sync the logout via the logout direct option of discourse.

It works, but I still believe there should be a better option than handling with an admin API token in combination with a username. It breaks if some admin will change the username of someoneā€¦ I would like a hash ID or something like thatā€¦ But nothing I can change, so I will live with it :wink:

Thanks for your answer.

2 Likes