Packages

This library is no longer being developed. Please use "untis" instead.

Current section

Files

Jump to
webuntis lib webuntis auth json_auth.ex
Raw

lib/webuntis/auth/json_auth.ex

defmodule Webuntis.Auth.JsonAuth do
@moduledoc """
Authentication module to use the mobile endpoint of Webuntis
"""
@doc false
def start_link() do
Agent.start_link(fn -> %{auth: false, username: "", secret: "", school_id: ""} end,
name: __MODULE__
)
end
@doc """
Start the json auth agent to use methods which requires authentication.
Use the information provided by <https://mese.webuntis.com/WebUntis/api/profile/access>
or use the gui to display the QR-code.
"""
@doc since: "2.0.0"
def login(username, secret, school_id) do
start_link()
Agent.update(__MODULE__, fn _ ->
%{username: username, secret: secret, school_id: school_id}
end)
end
@doc """
Request the shared app secret of the given user.
But you need the school-id (e.g. 2567800 for `mcg-gehrden`)
"""
@doc since: "2.0.0"
def shared_secret(username, password, school) do
params = %{
"userName" => username,
"password" => password
}
data = %{
"jsonrpc" => "2.0",
"id" => "",
"method" => "getAppSharedSecret",
"params" => [params]
}
HTTPoison.post!(
"https://mobile.webuntis.com/ms/app/" <> school <> "?m=getAppSharedSecret",
Jason.encode!(data),
[
{"Content-Type", "application/json; charset=UTF-8"}
]
).body
|> Jason.decode!()
|> Map.fetch!("result")
end
@doc false
def auth_map() do
state = current_state()
%{
"user" => state.username,
"otp" => Webuntis.Auth.Totp.generate_totp(state.secret),
"clientTime" => :os.system_time(:millisecond)
}
end
@doc false
def school_id() do
current_state().school_id
|> to_string
end
defp current_state() do
Agent.get(__MODULE__, fn state -> state end)
end
end