3
votes

I have a class (Account) that represents the user's system. Account contains a field role. It is the enum that contains three cases. Account class

public class Account extends Model {

@Id
@Email
public String email;

@Required
@NotNull
public String password;

@Required
@NotNull
public String firstName;

@Required
@NotNull
public String lastName;

@Required
public String phone;

public MyRole role;

MyRole

public enum MyRole {

ADMIN,
TEACHER,
USER

}

How can I implement an authorization?

2
If you choose Deadbolt 2, take a look at the quickstart guideSteve Chaloner

2 Answers

0
votes

Deadbolt-2 library is a solution. However, if you want to build your very own one, firstly, you need to read https://www.playframework.com/documentation/2.4.x/ScalaActionsComposition.

Actually, it is not that difficult and you can implement almost unlimited, very flexiable solution.

The basic idea is to define a UserAuthAction, like:

@Singleton
class UserAuthAction @Inject() (principalService: PrincipalService) extends ActionBuilder[Request] with ActionFilter[Request] {
  override protected def filter[A](request: Request[A]) = Future.successful {
    request.session.get(principalService.accessTokenCacheKey).map { accessToken =>
      if (principalService.authenticate(accessToken))
        None
      else
        Some(Results.Redirect(routes.PrincipalController.login()))
    } getOrElse {
      Some(Results.Redirect(routes.PrincipalController.login()))
    }
  }
}

And then compose it with the actions the do the actually job. For example:

@Singleton
class Application @Inject() (userAuthAction: UserAuthAction) extends Controller {
  def index = (userAuthAction andThen anyAction) { request =>
    Ok(views.html.index())
  }
}

Along the way, if you are using ActionRefiner, you can even extract additional user information and provide it to the latter actions, such as anyAction above.

1
votes

I think you could use Deadbolt-2 library, listed in the Play Framework plugins.

In the same idea of not reinvent the wheel, did you take a look at the Play-Authenticate plugin ? An another advantage of this last one is that it is compatible with Deadbolt-2.