com.synhaptein.scalator.security.UserServiceComponent.scala Maven / Gradle / Ivy
The newest version!
package com.synhaptein.scalator.security
import com.synhaptein.scalator.context.Context
/**
* User service component and implementation.
*
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2010-2011, SynHaptein (http://www.synhaptein.com)
* @link http://www.synhaptein.com/scalator scalator project
* @since scalator 0.2
* @license http://www.synhaptein.com/scalator/license.html
*/
object UserServiceConstants {
val USER = classOf[User[_]].getName
}
trait UserServiceComponent[T<:User[E], E] {
this: UserRepositoryComponent[T] with HashServiceComponent =>
def userService(context: Context): UserService
class UserService(val context: Context)
{
def login(username: String, plainPassword: String): Option[T] = {
val user = userRepository.find(username)
user match {
case None => return None
case Some(u) =>
if (u.active && u.password.equals(hashService.hashString(plainPassword))) {
register(u)
return Some(u)
}
else {
return None
}
}
}
def register(user: T) = {
context.session(UserServiceConstants.USER) = user
}
def unregister() = {
context.session(UserServiceConstants.USER) = null
}
def get(): Option[T] = {
context.session(UserServiceConstants.USER)
}
def save(user: T) = {
user.id match {
case Some(id) =>
userRepository.update(user)
case _ =>
userRepository.create(user)
}
}
def delete(user: T) = {
userRepository.delete(user)
}
def isLoggedIn(): Boolean = {
get() match {
case Some(user) => true
case _ => false
}
}
def hasGroups(groups:String*): Boolean = {
get() match {
case Some(user) =>
def checkGroups(): Boolean = {
groups foreach ( group =>
if(!user.roles.contains(group)) {
return false
}
)
return true
}
checkGroups()
case _ =>
false
}
}
def isOwner(objects:ObjectOwner[E]*): Boolean = {
get() match {
case Some(user) =>
def checkObjects(): Boolean = {
objects foreach { obj =>
user.id match {
case Some(id) =>
if(id != obj.owner) {
return false
}
case _ =>
return false
}
}
return true
}
checkObjects()
case _ =>
false
}
}
}
}