Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 60 lines (56 sloc) 2.548 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
(ns foreclojure.register
  (:require [sandbar.stateful-session :as session]
            [ring.util.response :as response])
  (:import [org.jasypt.util.password StrongPasswordEncryptor])
  (:use [hiccup.form-helpers :only [form-to text-field password-field]]
            [compojure.core :only [defroutes GET POST]]
            [foreclojure.utils :only [form-row assuming flash-error plausible-email?]]
            [foreclojure.template :only [def-page]]
            [foreclojure.messages :only [err-msgs]]
            [somnium.congomongo :only [insert! fetch-one]]))

(def-page register-page []
  {:title "4clojure – Register"
   :content
   (list
    [:div.error (session/flash-get :error)]
    (form-to [:post "/register"]
      [:table
       (map form-row
            [[text-field :user "Username (4-13 chars.)" (session/flash-get :user)]
             [password-field :pwd "Password (7+ chars.)"]
             [password-field :repeat-pwd "Repeat Password"]
             [text-field :email "Email" (session/flash-get :email)]])
       [:tr
        [:td [:button {:type "submit"} "Register"]]]]))})

(defn do-register [user pwd repeat-pwd email]
  (let [lower-user (.toLowerCase user)]
    (assuming [(nil? (fetch-one :users :where {:user lower-user}))
               (err-msgs "settings.user-exists"),
               (< 3 (.length lower-user) 14)
               (err-msgs "settings.uname-size"),
               (= lower-user
                  (first (re-seq #"[A-Za-z0-9_]+" lower-user)))
               (err-msgs "settings.uname-alphanum")
               (< 6 (.length pwd))
               (err-msgs "settings.pwd-size"),
               (= pwd repeat-pwd)
               (err-msgs "settings.pwd-match"),
               (plausible-email? email)
               (err-msgs "settings.email-invalid")
               (nil? (fetch-one :users :where {:email email}))
               (err-msgs "settings.email-exists")]
      (do
        (insert! :users
                 {:user lower-user
                  :pwd (.encryptPassword (StrongPasswordEncryptor.) pwd)
                  :email email})
        (session/session-put! :user lower-user)
        (response/redirect "/"))
      (do
        (session/flash-put! :user user)
        (session/flash-put! :email email)
        (flash-error "/register" why)))))

(defroutes register-routes
  (GET "/register" [] (register-page))
  (POST "/register" {{:strs [user pwd repeat-pwd email]} :form-params}
        (do-register user pwd repeat-pwd email)))
Something went wrong with that request. Please try again.