Skip to content

Commit

Permalink
sanitizedText
Browse files Browse the repository at this point in the history
  • Loading branch information
barryoneill committed May 27, 2022
1 parent 3e6b34f commit 0c6acc5
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
20 changes: 15 additions & 5 deletions src/main/scala/io/laserdisc/slack4s/slack/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import com.slack.api.model.block.element._
import io.laserdisc.slack4s.slashcmd.URL

import scala.jdk.CollectionConverters._
import scala.util.matching.Regex

package object slack {

Expand Down Expand Up @@ -117,16 +118,25 @@ package object slack {

implicit class SlashCommandPayloadOps(val p: SlashCommandPayload) extends AnyVal {

/* Trying a hack to get a (relatively) unique & short request ID using triggerID
* Trigger IDs are a period-separated sequence of alphanumerics of which the third
* appears distinctly random. We'll try just using the last few chars, and see if
* it's random _enough_ to differentiate a slackbot's requests */
/** A hack to get a (relatively) unique & short request ID using triggerID Trigger IDs are a period-separated sequence of alphanumerics
* of which the third appears distinctly random. We'll try just using the last few chars, and see if it's random _enough_ to
* differentiate a slackbot's requests
*/
def requestId: String =
Option(p.getTriggerId)
.map(_.trim.takeRight(8))
.filter(!_.isEmpty)
.filter(_.nonEmpty)
.getOrElse("n/a")

/** Load the sanitized payload text, where all characters not matching the regex are dropped
* @param regex
* Match 'safe' characters. Default is alphanumeric, dashes and spaces: `"[^A-Za-z0-9\\-\\s]"`
*/
def sanitizedText(regex: Regex = "[^A-Za-z0-9\\-\\s]".r): String =
Option(p.getText)
.map(_.trim)
.map(_.replaceAll(regex.regex, ""))
.getOrElse("")
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package io.laserdisc.slack4s.slack

import com.slack.api.app_backend.slash_commands.payload.SlashCommandPayload
import munit.FunSuite

class SlashCommandPayloadOpsSpec extends FunSuite {

test("SlashCommandPayloadOps should properly sanitize input text") {

assertEquals(mkCmd("hello there").sanitizedText(), "hello there")
assertEquals(mkCmd("pt *234234*").sanitizedText(), "pt 234234")
assertEquals(mkCmd("pt `234234`").sanitizedText(), "pt 234234")
assertEquals(mkCmd("pt `234234` ").sanitizedText(), "pt 234234")
assertEquals(mkCmd(" pt 234234 ").sanitizedText(), "pt 234234")

}

def mkCmd(txt: String): SlashCommandPayload = {
// the slack SDK forces mutability..
val cmd = new SlashCommandPayload()
cmd.setText(txt)
cmd
}

}

0 comments on commit 0c6acc5

Please sign in to comment.