greyhwndz
Strange `CaseClauseError`
Hello everyone!
Can somebody help me understanding the following…
Why is it that:
mydata = %{id: user.id, email: user.email, username: user.username}
IO.inspect mydata
jwt = %{data: mydata, sub: user.id}
results in
iex(1)> %{email: "maria@hello.com", id: 4, username: "maria"}
while:
mydata = %{id: user.id, email: user.email, username: user.username}
jwt = %{data: mydata, sub: user.id}
IO.inspect mydata
results in
iex(1)> {:ok,
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.B0QRhfQku78gSaxGoC8sxcKVL1wScNCAQGU_lzV4sQ8",
%{}}
Most Liked
benwilson512
get_user_by_email! returns a %LibraryApi.Library.User{} not {:ok, %LibraryApi.Library.User{}}, so your case in your controller doesn’t match.
Also, you probably know this, but never store user passwords in the database unhashed.
benwilson512
I’m not a JWT power user or anything but can’t you just do
def render("token.json", %{user: user}) do
data = %{id: user.id, email: user.email, username: user.username}
jwt = %{data: data, sub: user.id}
token = MyAppWeb.Token.generate_and_sign!(jwt)
%{token: token}
end
benwilson512
No need to do this, just update here with more information and we’ll be able to provide a more detailed answer.
benwilson512
Well, let’s think about the control flow you might want. get_user_by_email! uses Repo.get_by!. What happens if it doesn’t return any records? It raises an exception. This means that you’d need to handle it with try / catch in your controller, but this probably isn’t what you want. So I’d get rid of the ! on get_by as well as on get_user_by_email to start with.
So now the question: what does get_by return? Well, it returns either the struct that that you asked for, or nil. So you need to handle the result out of get_user_by_email based on whether the result is nil or not. if is one option, pattern matching on %Library.User{} is another. I’ll leave the actual refactoring of the controller action as an exercise for the reader.
benwilson512
Ah yes, that is correct now, you changed from Joken.generate_and_sign which you had in the previous post to Joken.generate_and_sign!. Joken.generate_and_sign returns a tuple, Joken.generate_and_sign! returns a string. However if you changed that it shoul dhave solved yout :erlang.apply error, so what’s the new error you have?








