Skip to content

Instantly share code, notes, and snippets.

@mmower
Created January 11, 2017 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmower/cc52e86b7a743de0872eef4d229db84d to your computer and use it in GitHub Desktop.
Save mmower/cc52e86b7a743de0872eef4d229db84d to your computer and use it in GitHub Desktop.
(ns jester.handler
(:require [aprint.core :refer [aprint]]
[clojure.edn :as edn]
[cheshire.core :refer [generate-string parse-string]]
[compojure.core :refer [ANY POST GET defroutes]]
[compojure.route :refer [resources]]
[ring.util.response :refer [resource-response]]
[ring.middleware.reload :refer [wrap-reload]]
[ring.middleware.json :refer [wrap-json-params wrap-json-body]]
[liberator.core :refer [defresource]]
[liberator.dev :refer [wrap-trace]]
[buddy.auth.backends :as backends]
[buddy.auth.middleware :refer (wrap-authentication)]
[buddy.hashers :as hashers]
[buddy.sign.jwt :as jwt]
[hugsql.core :as hugsql]))
(hugsql/def-db-fns "sql/accounts.sql")
(def db-conn {:classname "com.mysql.cj.jdbc.Driver" :subprotocol "mysql" :subname "//localhost/jester?autoReconnect=true&useSSL=false" :user "root" :password ""})
(def auth-secret "captainmidnight")
(def auth-backend (backends/jws {:secret auth-secret}))
(defn auth-fn [email password]
(if-let [account (select-account-by-email db-conn {:email email})]
(if (hashers/check password (:password account))
(select-keys account [:id :name :email]))))
(defresource tokens
:allowed-methods [:post]
:available-media-types ["application/json"]
:post! (fn [ctx]
(let [body (get-in ctx [:request :body])
email (get body "email")
password (get body "password")
account (auth-fn email password)]
(if account
{::account account})))
:handle-created (fn [ctx]
(if-let [account (::account ctx)]
{:status 201
:body (generate-string {:id (:id account)
:name (:name account)
:email (:email account)
:token (jwt/sign account auth-secret)})}
{:status 401
:body {:message "Invalid credentials"}})))
(defroutes routes
(POST "/tokens" [] tokens)
(GET "/" [] (resource-response "index.html" {:root "public"}))
(resources "/"))
(def dev-handler (-> #'routes
(wrap-reload)
(wrap-json-body)
(wrap-trace :header :ui)
(wrap-authentication auth-backend)))
(def handler (-> #'routes
(wrap-json-body)
(wrap-authentication auth-backend)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment