Advertisement
Guest User

Untitled

a guest
May 7th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. package controllers
  2.  
  3. import play.api._
  4. import play.api.mvc._
  5.  
  6. /**
  7. * 管理者のアカウントを取り扱うモジュール
  8. */
  9. trait AdminSecure {
  10. import play.api.mvc.Results._
  11.  
  12. private[this] val accounts = Map("admin" -> "password")
  13.  
  14. protected val basicRealm = "(my realm)"
  15.  
  16. /** ユーザー名とパスワードが一致するかを返します */
  17. protected def checkAccount(userName: String, password: String) =
  18. accounts.get(userName).filter(_ == password).nonEmpty
  19.  
  20.  
  21. /**
  22. * 認証を確認して実行するアクション
  23. */
  24. object AdminAction {
  25. private val AUTHORIZATION = "authorization"
  26. private val WWW_AUTHENTICATE = "WWW-Authenticate"
  27.  
  28. private def realm = "Basic realm=\"%s\"".format(basicRealm)
  29.  
  30. def apply(f: AuthenticatedRequest[AnyContent] => Result): Action[AnyContent] =
  31. apply(BodyParsers.parse.anyContent)(f)
  32.  
  33. def apply[A](p: BodyParser[A])(f: AuthenticatedRequest[A] => Result) = Action(p) { request =>
  34. request.headers.get(AUTHORIZATION) match {
  35. case Some(BasicAuthorization(name, pw)) if checkAccount(name, pw) =>
  36. f(new AuthenticatedRequest(name, request))
  37. case _ => Unauthorized("need admin login").withHeaders(WWW_AUTHENTICATE -> realm)
  38. }
  39. }
  40.  
  41. /**
  42. * Basic 認証の値の取り扱い
  43. */
  44. private object BasicAuthorization {
  45. private val basicPefix = "Basic "
  46. private val AUTHORIZATION_PARAMS = """([^:]+?):(.+)""".r
  47.  
  48. /**
  49. * Base64 エンコードで文字列化された Basic 認証値を、ユーザー名とパスワードに分解して返します
  50. *
  51. * @param auth Base64 エンコード文字列
  52. * @return 名前とパスワード
  53. */
  54. private[this] def decode(auth: String): Option[(String, String)] = {
  55. val d = javax.xml.bind.DatatypeConverter.parseBase64Binary(auth)
  56.  
  57. new String(d, "utf-8") match {
  58. case AUTHORIZATION_PARAMS(username, password) => Some(username, password)
  59. case _ => None
  60. }
  61. }
  62.  
  63. /**
  64. * WWW-Authenticate ヘッダの値から、ユーザー名とパスワードを取り出します。
  65. *
  66. * @param authorization WWW-Authenticate ヘッダ値。ヘッダの名前は含まない。
  67. * @return 名前とパスワード
  68. */
  69. def unapply(authorization: String): Option[(String, String)] = authorization match {
  70. case s if s startsWith basicPefix => decode(s drop basicPefix.length)
  71. case _ => None
  72. }
  73. }
  74.  
  75. /** 認証されて実行するリクエスト */
  76. class AuthenticatedRequest[A] private[controllers]
  77. (val userName: String, request: Request[A]) extends WrappedRequest(request)
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement