Last active
November 15, 2016 13:58
-
-
Save kolemannix/33db6593385ff6c5f706dad6b1fe92b0 to your computer and use it in GitHub Desktop.
Dynamically sanitizing Strings (XSS concerns) based on type tags
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
import scalaz.{ @@, Tag } | |
import org.apache.commons.lang.StringEscapeUtils | |
import org.joda.time.DateTime | |
import play.api.libs.json._ | |
trait DomRenderable | |
def RenderableString(s: String): String @@ DomRenderable = Tag[String, DomRenderable](s) | |
trait StringDate | |
/* This will only get called when a tagged type is required but an untagged is given */ | |
implicit def EpochTime(dt: DateTime): DateTime @@ StringDate = Tag[DateTime, StringDate](dt) | |
case class ResponseView( | |
messageSubject: String @@ DomRenderable, | |
messageBody: String @@ DomRenderable, | |
friendlyDescription: String, | |
dateCreated: DateTime, | |
dateModified: DateTime @@ StringDate | |
) | |
/* Just an example - could be more than just true or false */ | |
implicit val browserUserAgent: Boolean = true | |
implicit def domRenderableWrites(implicit userAgent: Boolean) = | |
Writes[String @@ DomRenderable] { taggedString => | |
JsString( | |
(userAgent, Tag.unwrap(taggedString)) match { | |
case (true, s) => StringEscapeUtils.escapeHtml(s) | |
case (false, s) => s | |
} | |
) | |
} | |
implicit val epochDateWrites = Writes[DateTime @@ StringDate](dt => JsString(Tag.unwrap(dt).toString)) | |
implicit val strImpliesRenderable: (String => String @@ DomRenderable) = s => RenderableString(s) | |
val responseView = ResponseView( | |
"<>", "<>", "<>", new DateTime, new DateTime | |
) | |
implicit val responseViewWrites = Json.writes[ResponseView] | |
val x = responseViewWrites.writes(responseView).toString() | |
/* | |
{ | |
"messageSubject": "<>", | |
"messageBody": "<>", | |
"friendlyDescription": "<>", | |
"dateCreated": 1479175039392, | |
"dateModified": "2016-11-14T20:57:19.392-05:00" | |
} | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment