Last active
August 29, 2015 14:18
-
-
Save arjan/21a501167133cbb38454 to your computer and use it in GitHub Desktop.
Twitter authorization controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule TestApp.TwitterController do | |
use Phoenix.Controller | |
# Routing configuration: | |
# | |
# scope "/twitter", TestApp do | |
# pipe_through :browser_session | |
# get "/:lang/authorize", TwitterController, :authorize | |
# get "/redirect", TwitterController, :authorize_return | |
require Plug.Conn | |
require Logger | |
plug :action | |
def configure_twitter(params, access_token \\ nil, access_token_secret \\ nil) do | |
config = Application.get_env(:testapp, :twitter) | |
if access_token != nil do | |
config = [{:access_token, access_token}, {:access_token_secret, access_token_secret} | config] | |
end | |
ExTwitter.configure(:process, config) | |
end | |
def authorize(conn, params) do | |
configure_twitter(params) | |
r = ExTwitter.API.Authorize.request_token() | |
redirect = Atom.to_string(conn.scheme) <> "://" <> get_host(conn) <> "/twitter/redirect" | |
{:ok, url} = ExTwitter.API.Authorize.authorize_url(r["oauth_token"], redirect, %{lang: params["lang"]}) | |
conn | |
|> put_session(:request_token, r["oauth_token"]) | |
|> put_session(:request_token_secret, r["oauth_token_secret"]) | |
|> redirect external: url | |
end | |
def authorize_return(conn, params) do | |
configure_twitter(params) | |
vars = case params["denied"] do | |
nil -> | |
case ExTwitter.API.Authorize.access_token(params["oauth_verifier"], get_session(conn, :request_token), get_session(conn, :request_token_secret)) do | |
{:error, code} -> | |
%{error: code} | |
params -> | |
%{params: params} | |
end | |
_ -> | |
%{error: :denied} | |
end | |
render conn, "return.html", vars | |
end | |
def popup_close(conn, params) do | |
render conn, "popup_close.html", %{params: params} | |
end | |
defp get_host(%Plug.Conn{port: port, host: host}) when port == 80 or port == 443 do | |
host | |
end | |
defp get_host(%Plug.Conn{port: port, host: host}) do | |
host <> ":" <> Integer.to_string(port) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment