Created
December 3, 2018 05:50
-
-
Save phenan/9e5fece462d2ba3feb9e74b8ef40afcb to your computer and use it in GitHub Desktop.
Simple HTML Sanitizer
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
object HTMLInterpolation { | |
// definition of tagged type | |
type Tagged[U] = { type Tag = U } | |
type @@[T, U] = T with Tagged[U] | |
trait Sanitized | |
// use tagged type to express sanitized string | |
type SanitizedString = String @@ Sanitized | |
private def sanitized (s: String): SanitizedString = s.asInstanceOf[SanitizedString] | |
implicit class HTMLContext (sc: StringContext) { | |
def html (args: SanitizedString*): SanitizedString = { | |
sanitized(sc.s(args:_*)) | |
} | |
} | |
import scala.language.implicitConversions | |
implicit def autoStringSanitizer (string: String): SanitizedString = { | |
sanitized(string | |
.replaceAll("&", "&") | |
.replaceAll("<", "<") | |
.replaceAll(">", ">") | |
.replaceAll("\"", """) | |
.replaceAll("'", "'")) | |
} | |
implicit def autoIntSanitizer (n: Int): SanitizedString = sanitized(n.toString) | |
implicit def autoLongSanitizer (n: Long): SanitizedString = sanitized(n.toString) | |
implicit def autoDoubleSanitizer (d: Double): SanitizedString = sanitized(d.toString) | |
} | |
// usage | |
object Main { | |
def main (args: Array[String]): Unit = { | |
import HTMLInterpolation._ | |
val a = html"<div>${"<script>alert(\"hello!\");</script>"}</div>" | |
println(a) | |
val b = html"<div>$a</div>" | |
println(b) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment