1defmodule ExampleOAuthPlug do
2 use Plug.Router
3 alias Atex.OAuth
4 alias Atex.XRPC
5
6 plug :put_secret_key_base
7
8 plug Plug.Session,
9 store: :cookie,
10 key: "atex-oauth",
11 signing_salt: "signing-salt"
12
13 plug :match
14 plug :dispatch
15
16 forward "/oauth", to: Atex.OAuth.Plug
17
18 get "/whoami" do
19 conn = fetch_session(conn)
20
21 with {:ok, client} <- XRPC.OAuthClient.from_conn(conn),
22 {:ok, response, client} <-
23 XRPC.post(client, %Com.Atproto.Repo.CreateRecord{
24 input: %Com.Atproto.Repo.CreateRecord.Input{
25 repo: client.did,
26 collection: "app.bsky.feed.post",
27 rkey: Atex.TID.now() |> to_string(),
28 record: %App.Bsky.Feed.Post{
29 text: "Hello world from atex!",
30 createdAt: NaiveDateTime.to_iso8601(NaiveDateTime.utc_now())
31 }
32 }
33 }) do
34 IO.inspect(response, label: "output")
35
36 conn
37 |> XRPC.OAuthClient.update_plug(client)
38 |> send_resp(200, response.uri)
39 else
40 :error ->
41 send_resp(conn, 401, "Unauthorized")
42
43 err ->
44 IO.inspect(err, label: "xrpc failed")
45 send_resp(conn, 500, "xrpc failed")
46 end
47 end
48
49 match _ do
50 send_resp(conn, 404, "oops")
51 end
52
53 def put_secret_key_base(conn, _) do
54 put_in(
55 conn.secret_key_base,
56 # Don't use this in production
57 "5ef1078e1617463a3eb3feb9b152e76587a75a6809e0485a125b6bb7ae468f086680771f700d77ff61dfdc8d8ee8a5c7848024a41cf5ad4b6eb3115f74ce6e46"
58 )
59 end
60end