Skip to content

Instantly share code, notes, and snippets.

@maekl
Last active April 27, 2019 14:08
Show Gist options
  • Select an option

  • Save maekl/5463ccc418e8653fe2a5729f0cba4230 to your computer and use it in GitHub Desktop.

Select an option

Save maekl/5463ccc418e8653fe2a5729f0cba4230 to your computer and use it in GitHub Desktop.
package se.picturizer.service.screen.internal
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.UUID
import CodeManager._
import akka.actor.Actor
import scala.collection.immutable
import scala.util.Random
private[internal] class CodeManager extends Actor {
private var codes: immutable.Map[UUID, RegistrationCode] = Map.empty
override def receive: Receive = {
case screenId: UUID =>
val code = RegistrationCode(screenId)
codes = codes.filterNot(_._2.expired) + (screenId -> code)
sender() ! code
case (screenId: UUID, code: String) =>
sender() ! codeOk(screenId, code)
}
private def codeOk(screenId: UUID, code: String): Boolean =
codes
.get(screenId)
.filterNot(_.expired)
.filter(_.code == code)
.filter(_.screen == screenId)
.isDefined
}
object CodeManager {
private[CodeManager] final case class RegistrationCode private[CodeManager$](screen: UUID, code: String, issued: Instant) {
def expired: Boolean = issued.plus(1, ChronoUnit.DAYS).isBefore(Instant.now)
}
private[CodeManager] object RegistrationCode {
def apply(screenId: UUID): RegistrationCode =
RegistrationCode(screenId, Random.alphanumeric.take(6).mkString("").toUpperCase, Instant.now)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment