Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
karma4u101 committed Nov 25, 2011
0 parents commit a7bc300
Show file tree
Hide file tree
Showing 29 changed files with 1,149 additions and 0 deletions.
48 changes: 48 additions & 0 deletions README.md
@@ -0,0 +1,48 @@
User Authentication Authorization Using SquerylRecord
=====================================================

This Scala/Lift basic assembly example project demonstrates a basic squeryl-record ORM/DSL User (authentication/authorization) setup
with register/login/user-pages snippets. To make things easy to follow the examples has extensive logging.


Quick Start
-----------
The only prerequisites for running this Lift example is that you have Git and Java installed and configured on the target computer.
You don't need to use it but the project also includes a Eclipse plug-in for browsing and following/working with the code, see the Scala IDE section.


1) Get the examples

git clone git@github.com:karma4u101/Basic-SquerylRecord-User-Setup.git
cd Basic-SquerylRecord-User-Setup

2) Update & Run Jetty

There is also a sbt.bat for windows users.

./sbt update ~container:start

3) Launch Your Browser

http://localhost:8080/

Changing Database back end
--------------------------
For demonstration purpose and easy setup this example uses (by default) a in memory db but you can easily change database by
un-comment the corresponding db init line in Boot.scala. Database name, user and password is set in the default.props resources file.

Scala IDE for Eclipse
---------------------
Sbteclipse provides SBT command to create Eclipse project files

1) Usage

project$ ./sbt
> eclipse create-src

2) In eclipse do:

File ==> Import...
Select General ==> Existing Project into Workspace
Use "Brows" to look up the project root ....

43 changes: 43 additions & 0 deletions build.sbt
@@ -0,0 +1,43 @@

organization := "Lift"

name := "Basic SquerylRecord User Setup"

version := "0.1-SNAPSHOT"

scalaVersion := "2.9.1"

seq(webSettings :_*)

// If using JRebel
scanDirectories in Compile := Nil

logLevel := Level.Info

resolvers += "Java.net Maven2 Repository" at "http://download.java.net/maven/2/"

libraryDependencies ++= {
val liftVersion = "2.4-M5" // Put the current/latest lift version here
Seq(
"net.liftweb" %% "lift-webkit" % liftVersion % "compile->default" withSources(),
"net.liftweb" %% "lift-squeryl-record" % liftVersion % "compile->default",
"net.liftweb" %% "lift-mapper" % liftVersion % "compile->default",
"net.liftweb" %% "lift-wizard" % liftVersion % "compile->default",
"net.liftweb" %% "lift-testkit" % liftVersion % "compile->default"
)
}

// Customize any further dependencies as desired
libraryDependencies ++= Seq(
"org.eclipse.jetty" % "jetty-webapp" % "8.0.3.v20111011" % "container",
//"org.mortbay.jetty" % "jetty" % "6.1.22" % "container", // For Jetty 7
"javax.servlet" % "servlet-api" % "2.5" % "provided->default",
"org.mindrot" % "jbcrypt" % "0.3m" % "compile->default",
"com.h2database" % "h2" % "1.2.138", // In-process database, useful for development systems
"mysql" % "mysql-connector-java" % "5.1.17", //Used in dev-test-jetty-run i.e for development systems outside of jni context
"postgresql" % "postgresql" % "9.0-801.jdbc4", //Used in dev-test-jetty-run i.e for development systems outside of jni context
"org.slf4j" % "slf4j-log4j12" % "1.6.1" % "compile->default", // Logging
"junit" % "junit" % "4.8" % "test->default", // For JUnit 4 testing
"org.scala-tools.testing" %% "specs" % "1.6.9" % "test",
"org.specs2" %% "specs2" % "1.6.1" % "test"
)
16 changes: 16 additions & 0 deletions project/plugins.sbt
@@ -0,0 +1,16 @@
resolvers ++= Seq(
"Web plugin repo" at "http://siasia.github.com/maven2",
Resolver.url("Typesafe repository", new java.net.URL("http://typesafe.artifactoryonline.com/typesafe/ivy-releases/"))(Resolver.defaultIvyPatterns)
)

libraryDependencies <+= sbtVersion(v => "com.github.siasia" %% "xsbt-web-plugin" % (v+"-0.2.6"))

resolvers += {
val typesafeRepoUrl = new java.net.URL("http://repo.typesafe.com/typesafe/releases")
val pattern = Patterns(false, "[organisation]/[module]/[sbtversion]/[revision]/[type]s/[module](-[classifier])-[revision].[ext]")
Resolver.url("Typesafe Repository", typesafeRepoUrl)(pattern)
}

resolvers += Classpaths.typesafeResolver

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse" % "1.4.0")
1 change: 1 addition & 0 deletions sbt
@@ -0,0 +1 @@
java -XX:MaxPermSize=512m -Xmx712M -Xss2M -XX:+CMSClassUnloadingEnabled -jar `dirname $0`/sbt-launch.jar "$@"
Binary file added sbt-launch.jar
Binary file not shown.
2 changes: 2 additions & 0 deletions sbt.bat
@@ -0,0 +1,2 @@
set SCRIPT_DIR=%~dp0
java -XX:+CMSClassUnloadingEnabled -XX:MaxPermSize=256m -Xmx712M -Xss2M -jar "%SCRIPT_DIR%\sbt-launch.jar" %*
Empty file added src/main/resources/.keep
Empty file.
22 changes: 22 additions & 0 deletions src/main/resources/props/default.log4j.props
@@ -0,0 +1,22 @@
log4j.rootLogger=DEBUG, CONSOLE, FILE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=DEBUG
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-5p [%c{1}] %m%n

log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.threshold=DEBUG
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d{ISO8601} %-5p [%c{1}] %m%n

#
# Note, changing log4j.appender.FILE.append=false will result in logs being
# overwritten without archiving the previous version of the log.
#
log4j.appender.FILE.append=true
log4j.appender.FILE.file=./var/log/app.log
log4j.appender.FILE.bufferedIO=false
log4j.appender.FILE.maxBackupIndex=3
log4j.appender.FILE.maxFileSize=10MB
17 changes: 17 additions & 0 deletions src/main/resources/props/default.props
@@ -0,0 +1,17 @@
##h2 db setup
h2.db.driver=org.h2.Driver
h2.db.url=jdbc:h2:mem:testXYZDB;DB_CLOSE_DELAY=-1;LOCK_TIMEOUT=3000
h2.db.user=test
h2.db.pass=test

##mysql db setup
mysql.db.driver=com.mysql.jdbc.Driver
mysql.db.url=jdbc:mysql://localhost:3306/testXYZDB
mysql.db.user=test
mysql.db.pass=test

##postgres db setup
postgres.db.driver=org.postgresql.Driver
postgres.db.url=jdbc:postgresql://localhost:5432/testXYZDB
postgres.db.user=test
postgres.db.pass=test
115 changes: 115 additions & 0 deletions src/main/scala/bootstrap/liftweb/Boot.scala
@@ -0,0 +1,115 @@
package bootstrap.liftweb

import net.liftweb._
import util._
import Helpers._
import common.{Box,Full,Empty,Loggable}
import http._
import sitemap._
import Loc._
import code.model._
import net.liftweb.squerylrecord.RecordTypeMode._
import code.model.MySchema
import code.snippet.RegisterLogin

/**
* A class that's instantiated early and run. It allows the application
* to modify lift's environment
*/
class Boot extends Loggable {
def boot {

Props.mode match {
case Props.RunModes.Development => logger.info("RunMode is DEVELOPMENT")
case Props.RunModes.Production => logger.info("RunMode is PRODUCTION")
case _ => logger.info("RunMode is TEST, PILOT or STAGING")
}

// where to search snippet
LiftRules.addToPackages("code")

/*un-comment and switch to db of your liking */
MySchemaHelper.initSquerylRecordWithInMemoryDB
//MySchemaHelper.initSquerylRecordWithMySqlDB
//MySchemaHelper.initSquerylRecordWithPostgresDB

/*OBS! do no use this in a production env*/
if(Props.RunModes.Development==true){
MySchemaHelper.dropAndCreateSchema
}

def loggedIn = {
() => {
User.isLoggedIn match {
case true => Empty
case false => {
//redirect and set notice message
Full(S.redirectTo("/registerLogin",() => S.notice("","You need to login to access this page!")))
}
}
}
}

// Build SiteMap
def sitemap = SiteMap(
Menu.i("Home") / "index", // the simple way to declare a menu
Menu.i("My Pages") / "user" / "index" >> EarlyResponse(loggedIn), //Show the page but redirect if user is not logged in
RegisterLogin.menu, //the register/login snippet menu part

// more complex because this menu allows anything in the
// /static path to be visible
Menu(Loc("Static", Link(List("static"), true, "/static/index"),
"Static Content")))

//def sitemapMutators = User.sitemapMutator

// set the sitemap. Note if you don't want access control for
// each page, just comment this line out.
LiftRules.setSiteMapFunc(() => sitemap/*sitemapMutators(sitemap)*/)

// Use jQuery 1.4
LiftRules.jsArtifacts = net.liftweb.http.js.jquery.JQuery14Artifacts

//Show the spinny image when an Ajax call starts
LiftRules.ajaxStart =
Full(() => LiftRules.jsArtifacts.show("ajax-loader").cmd)

// Make the spinny image go away when it ends
LiftRules.ajaxEnd =
Full(() => LiftRules.jsArtifacts.hide("ajax-loader").cmd)

// Force the request to be UTF-8
LiftRules.early.append(_.setCharacterEncoding("UTF-8"))

// What is the function to test if a user is logged in?
LiftRules.loggedInTest = Full(() => User.isLoggedIn)

// Use HTML5 for rendering
LiftRules.htmlProperties.default.set((r: Req) =>
new Html5Properties(r.userAgent))

//notice fade out (start after x, fade out duration y)
LiftRules.noticesAutoFadeOut.default.set( (notices: NoticeType.Value) => {
notices match {
case NoticeType.Notice => {
//logger.debug("Notice has been detected and fadeout is set ")
Full((8 seconds, 4 seconds))
}
case _ => {
Empty
}
}
}
)

// Make a transaction span the whole HTTP request
S.addAround(new LoanWrapper
{
override def apply[T](f: => T): T =
{
inTransaction{ f }
}
})

}
}
Empty file added src/main/scala/code/comet/.keep
Empty file.
57 changes: 57 additions & 0 deletions src/main/scala/code/lib/DependencyFactory.scala
@@ -0,0 +1,57 @@
package code {
package lib {

import net.liftweb._
import http._
import util._
import common._
import _root_.java.util.Date

/**
* A factory for generating new instances of Date. You can create
* factories for each kind of thing you want to vend in your application.
* An example is a payment gateway. You can change the default implementation,
* or override the default implementation on a session, request or current call
* stack basis.
*/
object DependencyFactory extends Factory {
implicit object time extends FactoryMaker(net.liftweb.util.Helpers.now _)

/**
* objects in Scala are lazily created. The init()
* method creates a List of all the objects. This
* results in all the objects getting initialized and
* registering their types with the dependency injector
*/
private def init() {
List(time)
}
init()
}

/*
/**
* Examples of changing the implementation
*/
sealed abstract class Changer {
def changeDefaultImplementation() {
DependencyFactory.time.default.set(() => new Date())
}
def changeSessionImplementation() {
DependencyFactory.time.session.set(() => new Date())
}
def changeRequestImplementation() {
DependencyFactory.time.request.set(() => new Date())
}
def changeJustForCall(d: Date) {
DependencyFactory.time.doWith(d) {
// perform some calculations here
}
}
}
*/
}
}
17 changes: 17 additions & 0 deletions src/main/scala/code/model/DemoData.scala
@@ -0,0 +1,17 @@
package code
package model

import lib.util._

object DemoData {

def createDemoData {
val usersList = prepareUser()
usersList.foreach(MySchema.users.insert(_))
}

def prepareUser(): List[User] = {
List()
}

}

0 comments on commit a7bc300

Please sign in to comment.