Skip to content

Commit

Permalink
Authorization manager
Browse files Browse the repository at this point in the history
The authorization manager takes care of the authorization when talking
to a bot.
This way you could create a private bot that will only respond to
specific channels.
The authorization can work either by whitelisting or blacklisting
channels.
By default the policy is to accept all channels.
  • Loading branch information
ex0ns committed Jan 6, 2016
1 parent c7da69e commit 044507a
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
63 changes: 63 additions & 0 deletions src/main/scala/info/mukel/telegram/bots/AuthorizationManager.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package info.mukel.telegram.bots

import info.mukel.telegram.bots.Policy._

import scala.collection.mutable

sealed trait Policy

object Policy {
case object Accept extends Policy
case object Decline extends Policy
}

/**
* Filter the channels to which the bot could/should not respond
* Two policies are available:
*
* - Accept: respond to any channels, except the ones that are blacklisted
* - Decline: do not respond to any channels, except the ones that are whitelisted
*/
object AuthorizationManager {

private val authorizations = mutable.Set[Int]()
private var policy : Policy = Accept

/**
* Finds if a channel is authorized or not
* @param channel
* The channel to look the authorization for.
* @return
* Whether or not the bot can respond to this channel
*/
def isAuthorized(channel: Int) : Boolean = {
val authorization = authorizations.contains(channel)
policy match {
case Accept => !authorization
case Decline => authorization
}
}

/**
* Add a channel to the whitelisted/blacklisted
* @param channel
* The channel to add
*/
def add(channel: Int) = authorizations.add(channel)

/**
* Remove a channel to the whitelisted/blacklisted
* @param channel
* The channel to add
*/
def remove(channel: Int) = authorizations.remove(channel)

/**
* Set the Manager policy
* @param policy
* The new authorization policy
*/
def setPolicy(policy: Policy) = this.policy = policy

}

4 changes: 2 additions & 2 deletions src/main/scala/info/mukel/telegram/bots/Commands.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ trait Commands {
// Allows targeting specific bots eg. /hello@FlunkeyBot
val cmdAt = "@"

private val commands = mutable.HashMap[String, (Int, Seq[String]) => Unit]()
private val commands = mutable.HashMap[String, (Int, Seq[String]) => Unit]()

/**
* handleUpdate
Expand All @@ -44,7 +44,7 @@ trait Commands {
*/
override def handleUpdate(update: Update): Unit = {
for {
msg <- update.message
msg <- update.message if AuthorizationManager.isAuthorized(msg.chat.id)
text <- msg.text
} /* do */ {

Expand Down

0 comments on commit 044507a

Please sign in to comment.