wlminimal

wlminimal

Is there anyway to get conn value inside defhandler in drab?
I want to get a user from conn.assigns like this

defhandler shorten_url(socket, sender) do
    long_url = sender.params["long_url_textarea"]
    user = conn.assigns.current_user
    case Analytics.create_short_link(long_url) do
      {:ok, results} ->
        # Create bitly struct
        %{id: bitlink_id, link: bitlink_url, long_url: long_url} = results
        Bitly.create_bitly(%{bitlink_id: bitlink_id, bitlink_url: bitlink_url, long_url: long_url, total_clicks: 0, user_id: user.id})

        poke socket, long_url: bitlink_url
      {:error, errors} ->
        set_prop socket, "#long-url-error", innerHTML: "Something wrong found in your url. Make sure including http://, for example http://www.example.com"
    end
  end

Showing Posts 1 to 10

grych

grych

Creator of Drab

You can’t. Conn does not exists anymore - it is available only when rendering page with controller. While the page is already rendered and connected, the similar role for conn plays socket

To get the userid, you may use:

# app.html.eex:
<%= Drab.Client.run(@conn, current_user: @conn.assigns.current_user) %>

# your_commander.ex
defhandler shorten_url(socket, sender) do
    user = socket.assigns.current_user
end
grych

grych

Creator of Drab

Actually it is not complicated to get conn.assigns copied to socket.assigns (with some whitelisting to avoid storing large structs). If you feel it would be helpful, please make an issue on github. I did not think about this before, as IMO session provides better functionality for such stuff.

wlminimal

wlminimal OP

I tried first solution

  • session: there is a Drab.Core.get_session/2 for this

in config.exs I tried this but got an error

config :drab, MyAppWeb.Endpoint,
  :access_session, [:user_id]

so I did

config :drab, MyAppWeb.Endpoint,
  access_session: [:user_id]

in commander.ex

user_id = Drab.Core.get_session(socket, :user_id)
IO.inspect user_id

but it returns nil

and section solution

  • socket.assigns - you may add the assign to the socket struct when rendering Drab JS in app.html.eex,
    I tried what you exactly said. but in browser console it says

Firefox can’t establish a connection to the server at ws://localhost:4000/socket/websocket?__drab_return=SFMyNTY.g3QAAAACZAAEZGF0YWwAAAAFaAJkAAxfX2NvbnRyb2xsZXJkADFFbGl4aXIuVGV4dGluZ1dlYi5EYXNoYm9hcmQuQ2hlY2tvdXRTbXNDb250cm9sbGVyaAJkAAtfX2NvbW1hbmRlcmQAMEVsaXhpci5UZXh0aW5nV2ViL…

What am I missing?

grych

grych

Creator of Drab

Oh, there is an error in the documentation, thanks for pointing it out!

It might be a stupid question, but how do you set the session value in the controller? Can you share this part?

It is hard to say, is you code available somewhere like github, so I could take a look?

wlminimal

wlminimal OP

I put the user id session when user logs in like this

def create(conn, %{"token" => token}) do
    case Account.verify_token(token) do
      {:ok, user_id} ->
        user = Account.get_user_by_id(user_id)

        # Check if user has verified phone number
        check_phone_verified(conn, user)

      {:error, :invalid} ->
        conn
        |> put_flash(:error, "Invalid Link, Can't Log in")
        |> render("new.html")
      {:error, :expired} ->
        conn
        |> put_flash(:error, "Links has been expired. Please do it again")
        |> render("new.html")
    end
  end


  defp check_phone_verified(conn, user) do
    case user.phone_verified do
      true ->
        conn
        |> assign(:current_user, user)
        |> put_session(:user_id, user.id)
        |> configure_session(renew: true)
        |> put_flash(:info, "Successfully logged in!")
        |> redirect(to: dashboard_path(conn, :new))
      _    ->
        conn
        |> put_flash(:error, "You have to verify your phone number!")
        |> assign(:current_user, user)
        |> put_session(:user_id, user.id)
        |> configure_session(renew: true)
        |> redirect(to: phone_verify_path(conn, :new))
    end
  end

and using plug to check if user_id is in session like this

def call(conn, _opts) do
    case user_id = get_session(conn, :user_id) do
    	user_id when user_id != nil ->
    		user = Account.get_user_by_id(user_id)
    		assign(conn, :current_user, user)
    	user_id when is_nil(user_id) ->
    		conn
    		|> put_flash(:error, "You must sign in first")
    		|> redirect(to: Helpers.sign_in_path(conn, :new))
        |> halt()
    end
  end

in router.ex

  pipeline :dashboard do
    plug TextingWeb.Plugs.LoadUser
  end
wlminimal

wlminimal OP

one more question.
I am trying to use drab to shorten url.
There is a form that has several input field.
and when I click a button to shorten url using drab, but text in other field refreshed and get emptied.
it doesn’t look like a refreshing page. but it clear all the other field.
is this normal behavior?
I put those in two separate form element.

grych

grych

Creator of Drab

Strange, all looks OK. Let’s try to debug it.

  1. Could you please check what is in socket.assigns[:__session]?
  2. Could you check also Drab.Config.get(MyAppWeb.Endpoint, :access_session)?
grych

grych

Creator of Drab

It might be that your handler function updates not only the requested field, but also the whole form. Could you please share the form and the commander handler function?

wlminimal

wlminimal OP

<div class="row">
	<%= form_for @recipients_changeset, checkout_sms_path(@conn, :preview_sms), [as: :sms], fn f -> %>
	<div class="col s8">
		<div>
			<div class="row">
				<div class="input-field col s12">
					<label for="sms[name]">Name</label>
					<%= text_input f, :name, placeholder: "Enter Name for this campaign", maxlength: 20, class: "validate", required: true  %>
					<%= error_tag f, :name %>
				</div>
			</div>
			<div class="row">
				<div class="input-field col s12">
				<label for="sms[description]">Description</label>
				<%= text_input f, :description, placeholder: "Enter Description for this campaign", maxlength: 50, class: "validate", required: true %>
				<%= error_tag f, :description %>
				</div>
			</div>

			<div class="row">
				<div class="input-field col s12">
					<i class="material-icons prefix">message</i>
					<%= textarea f, :message, class: "materialize-textarea", id: "message", required: true %>
					<label for="message">Message</label>
					<%= error_tag f, :message %>
					<span class="helper-text d-helper-text">Max length of text is 160 in English(alphabetic language) and other languages(Korean, Japanese, Chinese etc)'s limit is 70 character.
					if you try to send message longer than a limit, it will charge double (like sending 2 messages). </span>
					<span id="message-length-info" class="helper-text d-helper-text">
					</span>
				</div>
			</div>

			<%= hidden_input f, :total_credit, value: 1 %>
			<div class="row">
				<div class="col s12">
					<button class="btn waves-effect waves-light" type="submit" name="action">Next
						<i class="material-icons right">send</i>
					</button>
				</div>
			</div>
		</div>
	</div>
	<% end %>
	<!-- Short url generation section -->
	<div class="col s4">
		<form>
			<div class="row">
				<div class="input-field col s12">
					<label for="long_url">Type long URL here.</label>
					<textarea class="materialize-textarea" id="long-url-textarea" name="long_url_textarea"><%= @long_url %> </textarea>
					<p id="long-url-error"></p>
				</div>
			</div>
			<div class="row">
				<div class="input-field col s6">
					<button class="btn waves-effect waves-light" drab="click:shorten_url">Shorten
						<i class="material-icons right">content_cut</i>
					</button>
				</div>
				
			</div>
		</form>
		<!-- Shortened Url -->
		<div class="row">
			<div class="input-field col s12">
				<label for="long_url">Your short Url</label>
				<textarea class="materialize-textarea" id="short-url-textarea"><%= @shorten_url %> </textarea>
				<span class="helper-text d-helper-text">Copy this text and paste in your message. </span>
			</div>
		</div>
		
	</div>
</div>

and defhandler here

defhandler shorten_url(socket, sender) do
    long_url = sender.params["long_url_textarea"]
    user_id = socket.assigns.current_user_id

    case Analytics.create_short_link(long_url) do
      {:ok, results} ->
        # Create bitly struct
        %{id: bitlink_id, link: bitlink_url, long_url: long_url} = results
        Bitly.create_bitly(%{bitlink_id: bitlink_id, bitlink_url: bitlink_url, long_url: long_url, total_clicks: 0, user_id: user_id})

        poke socket, shorten_url: bitlink_url, long_url: long_url
      {:error, errors} ->
        IO.puts "++++++++++++++++++++++++++++++++++++++"
        IO.inspect errors
        IO.puts "++++++++++++++++++++++++++++++++++++++"
        set_prop socket, "#long-url-error", innerHTML: "Something wrong found in your url. Make sure including http://, for example http://www.example.com"
    end
  end
wlminimal

wlminimal OP

iex(4)> socket.assigns[:__session]
%{}

iex(5)> Drab.Config.get(TextingWeb.Endpoint, :access_session)
[]

in config.exs

config :drab, TextingWeb.Endpoint,
  otp_app: :texting,
  access_session: [:user_id]

in commander.ex

current_user_id = Drab.Core.get_session(socket, :user_id)
    IO.puts "++++++++++++++++++++++++++++++++++++++"
    IO.inspect current_user_id
    IO.puts "++++++++++++++++++++++++++++++++++++++"

return nil

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews