Commit 78b149ed authored by Mathieu's avatar Mathieu
Browse files

Implements DB add user with a pre-existence test

parent efdd86a5
......@@ -43,7 +43,7 @@ object Application extends App {
server.start()
}
// DB.addUser(DB.Login("moo"), DB.Password("moo"), "moo@me.com")
DB.addUser(DB.Login("moo"), DB.Password("moo"), "moo@me.com")
println(DB.users)
......
......@@ -16,10 +16,15 @@ object DB {
case class Password(value: String) extends MappedTo[String]
case class User(login: Login, password: Password, email: String, uuid: UUID = UUID(""))
case class Role(value: String) extends MappedTo[String]
val admin = Role("admin")
val simpleUser = Role("simpleUser")
class Users(tag: Tag) extends Table[(UUID, Login, Password, String)](tag, "USERS") {
case class User(login: Login, password: Password, email: String, role: Role = simpleUser, uuid: UUID = UUID(""))
class Users(tag: Tag) extends Table[(UUID, Login, Password, String, Role)](tag, "USERS") {
def uuid = column[UUID]("UUID", O.PrimaryKey)
def login = column[Login]("LOGIN")
......@@ -28,7 +33,9 @@ object DB {
def email = column[String]("EMAIL")
def * = (uuid, login, password, email)
def role = column[Role]("ROLE")
def * = (uuid, login, password, email, role)
}
val userTable = TableQuery[Users]
......@@ -42,12 +49,12 @@ object DB {
Await.result(
db.run(userTable.result).map { x =>
x.map {
case (uuid, login, password, email) => User(login, password, email, uuid)
case (uuid, login, password, email, role) => User(login, password, email, role, uuid)
}
}, Duration.Inf
)
//Seq(User(Login("foo"), Password("foo"), UUID("foo-123-567-foo")), User(Login("bar"), Password("bar"), UUID("bar-123-567-bar")))
// val users = Seq(User(Login("foo"), Password("foo"), UUID("foo-123-567-foo")), User(Login("bar"), Password("bar"), UUID("bar-123-567-bar")))
def uuid(login: Login): Option[UUID] = users.find(_.login == login).map {
......@@ -65,14 +72,39 @@ object DB {
actions: _*
).transactionally), Duration.Inf)
def runQuery(query: TableQuery[DB.Users]) =
Await.result(
db.run(
query.result
), Duration.Inf
)
def initDB = {
runTransaction(userTable.schema.createIfNotExists)
if (DB.users.isEmpty) {
DB.addUser(DB.Login("admin"), DB.Password("admin"), "", DB.admin)
}
}
def addUser(login: Login, password: Password, email: String) =
if (!users.contains{u: User=> u.email == email}) {
def exists(email: String) = {
Await.result(
db.run(
(for {
u <- userTable if (u.email === email)
} yield (u)).result
).map {
_.length != 0
}, Duration.Inf
)
}
def addUser(login: Login, password: Password, email: String, role: Role = simpleUser) = {
if (!exists(email)) {
runTransaction(
userTable += (UUID(util.UUID.randomUUID().toString), login, password, email)
userTable += (UUID(util.UUID.randomUUID().toString), login, password, email, role)
)
}
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment