Play Framework 2.4 License
I have a class (Account) that represents a custom system. The account contains the field role. This listing 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 authorization?
Deadbolt-2 library is the solution. However, if you want to create your own first, you need to read https://www.playframework.com/documentation/2.4.x/ScalaActionsComposition .
It's not really that hard, and you can implement a virtually unlimited, highly flexible solution.
The main 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 that actually take place. 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 an ActionRefiner, you can even extract additional information about the user and provide it to the latest actions like anyAction above.
I think you could use the Deadbolt-2 library listed in Play Framework Plugins .
In the same idea of not reinventing the wheel, have you looked at the Play-Authenticate plugin ? Another benefit of this latter is that it is Deadbolt-2 compatible.