Permalink
Browse files

Got authentication pages working

  • Loading branch information...
1 parent 25a1843 commit f4a8ae18cad578721e384835e9b920febdd55e12 David Davis committed Aug 4, 2012
Showing with 68 additions and 9 deletions.
  1. +17 −9 src/shared_resource/views/common.clj
  2. +51 −0 src/shared_resource/views/sessions.clj
@@ -1,12 +1,20 @@
(ns shared-resource.views.common
- (:use [noir.core :only [defpartial]]
- [hiccup.page :only [include-css html5]]))
+ (:use noir.core
+ hiccup.core
+ hiccup.element
+ [hiccup.page :only [include-css html5]])
+ (:require [noir.session :as session]))
(defpartial layout [& content]
- (html5
- [:head
- [:title "shared-resource"]
- (include-css "/css/reset.css")]
- [:body
- [:div#wrapper
- content]]))
+ (html5
+ [:head
+ [:title "shared-resource"]
+ (include-css "/css/reset.css")]
+ [:body
+ [:div#session
+ [:div#user-info (session/get :username)]
+ (if (session/get :username) (link-to "/sessions/destroy" "Logout") "")]
+ [:div#flash.success (session/flash-get :success)]
+ [:div#flash.error (session/flash-get :error)]
+ [:div#wrapper
+ content]]))
@@ -0,0 +1,51 @@
+(ns shared-resource.views.sessions
+ (:use noir.core
+ hiccup.core
+ hiccup.page
+ hiccup.element
+ hiccup.form)
+ (:require [shared-resource.models.user :as user]
+ [shared-resource.views.common :as common]
+ [noir.response :as resp]
+ [noir.session :as session]))
+
+(defpartial login-page [username]
+ (common/layout
+ (form-to [:post "/sessions"]
+ (label "username" "Username: ")
+ (text-field "username" username)
+ (label "password" "Password: ")
+ (password-field "password")
+ (submit-button "Login"))))
+
+(defn logged-in? []
+ (not (nil? (session/get :username))))
+
+;; Routes
+
+(pre-route "/" {}
+ (when-not (logged-in?)
+ (resp/redirect "/sessions/new")))
+
+(pre-route "/resources/*" {}
+ (when-not (logged-in?)
+ (resp/redirect "/sessions/new")))
+
+(defpage "/sessions/new" []
+ (login-page ""))
+
+(defpage [:post "/sessions"] {:keys [username password]}
+ (if (user/login? username password)
+ (do
+ (session/put! :username username)
+ (session/flash-put! :success "Successfully logged in.")
+ (resp/redirect "/"))
+ (do
+ (session/flash-put! :error "Failed to log in.")
+ (login-page username))))
+
+(defpage "/sessions/destroy" []
+ (do
+ (session/clear!)
+ ;; (session/flash-put! :success "Logged out.") can't session/clear to work with this
+ (resp/redirect "/sessions/new")))

0 comments on commit f4a8ae1

Please sign in to comment.