Last active
April 23, 2016 16:06
-
-
Save alexflav23/6310076 to your computer and use it in GitHub Desktop.
RestHelper 401 response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package code.lib; | |
import net.liftweb.http.rest.RestHelper | |
import net.liftweb.http.{ LiftRules, LiftResponse, Req, UnauthorizedResponse } | |
import net.liftweb.common.{ Box, Full, Empty, Failure, ParamFailure } | |
trait TypesHelper { | |
implicit def pfAuthorize[A, B](in: PartialFunction[A, B]): OAuthPartialFunctionWrapper[A, B] = | |
new OAuthPartialFunctionWrapper[A, B](in) | |
} | |
object TypesHelper extends TypesHelper | |
trait OAuthServiceHelper[A, B] extends PartialFunction[A, B] { | |
def isAuthorized(r: A): Boolean | |
} | |
/** | |
* The OAuth guard class. | |
*/ | |
trait OAuthGuard extends OAuthServiceHelper[Req, () => Box[LiftResponse]] { | |
/** | |
* This method actually returns always true assuming the partial function applied | |
* on the REST service to protect | |
* | |
* @param r | |
* @return true if this service manage the request security, false otherwise | |
* | |
*/ | |
def isDefinedAt(r: Req): Boolean = true | |
/** | |
* The method should return the "access denied" message to the client | |
* | |
* @param r | |
* @return the response body with the error message | |
*/ | |
def apply(r: Req): () => Box[LiftResponse] = () => Full(new UnauthorizedResponse("You are not authenticated")) | |
/** | |
* The method should return false in case of access denied. | |
* | |
* @param r | |
* @return true if the other apply method is authorized, false otherwise. | |
*/ | |
def isAuthorized(r: Req): Boolean | |
} | |
final class OAuthPartialFunctionWrapper[A, B](other: PartialFunction[A, B]) { | |
/** | |
* Allows you to put a guard around a partial function | |
* such that the around's isAuthorized determines if the other | |
* apply method should be executed. In case of access denied the around | |
* apply method is called. | |
*/ | |
def ifAuthorizedBy(around: OAuthServiceHelper[A, B]): PartialFunction[A, B] = | |
new PartialFunction[A, B] { | |
def isDefinedAt(a: A) = around.isDefinedAt(a) && other.isDefinedAt(a) | |
def apply(a: A): B = { | |
if (around.isAuthorized(a)) | |
other.apply(a) | |
else | |
around.apply(a) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment