-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Basic authentication & callback routing * Backend auth dance * Provide an empty history for new users
- Loading branch information
Showing
19 changed files
with
443 additions
and
110 deletions.
There are no files selected for viewing
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
Empty file.
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
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
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
77 changes: 51 additions & 26 deletions
77
dokusho-server/src/main/scala/dokusho/ReadingHistoryRouter.scala
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,37 +1,62 @@ | ||
package dokusho | ||
|
||
import cats.data.OptionT | ||
import cats.effect.IO | ||
import io.circe.Json | ||
import org.http4s.HttpService | ||
import org.http4s.util.CaseInsensitiveString | ||
import org.http4s.{Header, HttpService, Request, Response} | ||
|
||
class ReadingHistoryRouter(readingHistoryService: ReadingHistoryService) extends Http4sRouter { | ||
|
||
private val service = readingHistoryService | ||
case class SuccessfulPut(userId: String) | ||
|
||
def getUserId(req: Request[IO]): IO[Option[String]] = | ||
IO(req.headers.find(_.name == CaseInsensitiveString("User")).map(_.value)) | ||
|
||
implicit class ReqHelper(req: Request[IO]) { | ||
def withReadingHistory(f: ReadingHistory => IO[UserReadingHistory]): IO[UserReadingHistory] = | ||
req.as[ReadingHistory].flatMap(f(_)) | ||
|
||
def withEntry(f: NewEntry => IO[UserReadingHistory]): IO[UserReadingHistory] = | ||
req.as[NewEntry].flatMap(f(_)) | ||
} | ||
|
||
implicit private def routeWithErrorHandling(io: OptionT[IO, IO[Response[IO]]]): IO[Response[IO]] = | ||
io.value.flatMap(_.getOrElse(NotFound())) | ||
|
||
val orNotFound = (io: OptionT[IO, IO[Response[IO]]]) => | ||
io.value.flatMap(_.getOrElse(NotFound())) | ||
|
||
val routes: HttpService[IO] = HttpService[IO] { | ||
case GET -> Root / "history" / userId => | ||
for { | ||
userReadingHistory <- readingHistoryService.getReadingHistory(userId) | ||
json: Option[Json] = userReadingHistory.map(_.asJson) | ||
resp <- json.fold(NotFound())(j => Ok(j)) | ||
} yield resp | ||
case req@PUT -> Root / "history" / userId => | ||
for { | ||
readingHistory <- req.as[ReadingHistory] | ||
storedHistory <- readingHistoryService.upsert(UserReadingHistory(userId, readingHistory)) | ||
json: Json = SuccessfulPut(storedHistory.userId).asJson | ||
response <- Ok(json) | ||
} yield response | ||
case req@POST -> Root / "history" / userId / "add" => | ||
for { | ||
entry <- req.as[NewEntry] | ||
storedHistory <- readingHistoryService.addNewEntry(userId, entry) | ||
json = storedHistory.map(_.asJson) | ||
result <- json.fold(NotFound())(j => Ok(j)) | ||
} yield result | ||
case PUT -> Root / "history" / userId / "reset" => | ||
readingHistoryService.reset(userId) | ||
case req@GET -> Root / "history" => | ||
OptionT(getUserId(req)) | ||
.flatMapF(userId => service.getReadingHistory(userId)) | ||
.map(_.asJson) | ||
.flatMap(j => Ok(j)) | ||
.map(json => Ok(json)) | ||
.value.flatMap(_.getOrElse(NotFound())) | ||
case req@PUT -> Root / "history" => | ||
OptionT(getUserId(req)) | ||
.semiflatMap(userId => req.withReadingHistory(rh => service.upsert(UserReadingHistory(userId, rh)))) | ||
.map(storedHistory => SuccessfulPut(storedHistory.userId)) | ||
.map(sp => Ok(sp.asJson)) | ||
.value.flatMap(_.getOrElse(NotFound())) | ||
case req@POST -> Root / "history" / "add" => | ||
OptionT(getUserId(req)) | ||
.semiflatMap(userId => req.withEntry(e => service.upsertNewEntry(userId, e))) | ||
.map(storedHistory => storedHistory.asJson) | ||
.map(json => Ok(json)) | ||
.value.flatMap(_.getOrElse(BadRequest())) | ||
case req@PUT -> Root / "history" / "reset" => | ||
OptionT(getUserId(req)) | ||
.semiflatMap(userId => service.reset(userId)) | ||
.map(_.asJson) | ||
.map(j => Ok(j)) | ||
.value.flatMap(_.getOrElse(BadRequest())) | ||
case req@GET -> Root / "auth" => | ||
// This endpoint should be removed, but right now it's handy for development | ||
val headerOpt: Header = req.headers | ||
.find(_.name == CaseInsensitiveString("User")) | ||
.getOrElse(Header("User", "None")) | ||
|
||
Ok("Hello: " + headerOpt.value) | ||
} | ||
} |
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
52 changes: 52 additions & 0 deletions
52
dokusho-server/src/main/scala/dokusho/middleware/Auth0Middleware.scala
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package dokusho.middleware | ||
|
||
import cats.data.OptionT | ||
import cats.effect.IO | ||
import dokusho.Http4sRouter | ||
import org.http4s._ | ||
import org.http4s.client.Client | ||
import org.http4s.util.CaseInsensitiveString | ||
|
||
sealed trait Auth0Response | ||
|
||
case class AuthSuccessResponse(sub: String) extends Auth0Response | ||
|
||
case class FailureResponse(reason: String) extends Auth0Response | ||
|
||
class Auth0Middleware(client: Client[IO]) extends Http4sRouter { | ||
|
||
def authenticationMiddleware(service: HttpService[IO]): HttpService[IO] = cats.data.Kleisli { req: Request[IO] => | ||
|
||
val authToken: Option[Header] = | ||
req.headers | ||
.find(_.name == CaseInsensitiveString("accessToken")) | ||
.map(header => Header.apply("Authorization", "Bearer " + header.value)) | ||
|
||
authToken match { | ||
case Some(headers) => | ||
OptionT( | ||
callService(client, headers) | ||
.map(userInfo => req.putHeaders(Header.apply("User", userInfo))) | ||
.flatMap(req => service.apply(req.putHeaders(headers)).value)) | ||
case None => | ||
val response: Response[IO] = Response.apply[IO](status = Unauthorized) | ||
OptionT(IO.pure(Option(response))) | ||
} | ||
} | ||
|
||
private def callService(c: Client[IO], authToken: Header): IO[String] = { | ||
c.fetch(Request.apply[IO]( | ||
method = GET, | ||
uri = Uri.unsafeFromString("https://dokusho.eu.auth0.com/userinfo"), | ||
headers = Headers(authToken) | ||
)) { r => | ||
r.status.responseClass match { | ||
case Status.Successful => r.as[AuthSuccessResponse] | ||
case _ => IO.apply(FailureResponse("unauthorised")) | ||
} | ||
}.map { | ||
case AuthSuccessResponse(sub: String) => println(s"Got sub: $sub"); sub.dropWhile(_ != '|').tail | ||
case FailureResponse(r: String) => r | ||
} | ||
} | ||
} |
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,54 @@ | ||
[%bs.raw {|require('./toolbox/theme.css')|}]; | ||
|
||
open Dokusho; | ||
[%bs.raw {|require('../node_modules/auth0-js/build/auth0.js')|}]; | ||
|
||
[@bs.module] | ||
external theme : ReactToolbox.ThemeProvider.theme = "./toolbox/theme"; | ||
[%bs.raw {|require('./toolbox/theme.css')|}]; | ||
|
||
let component = ReasonReact.statelessComponent("App"); | ||
open Dokusho; | ||
open Types; | ||
|
||
type action = | ||
| ChangeRoute(Routes.route); | ||
|
||
let reducer = (action, _state) => | ||
switch action { | ||
| ChangeRoute(route) => ReasonReact.Update( route ) | ||
}; | ||
|
||
let component = ReasonReact.reducerComponent("App"); | ||
|
||
let mapUrlToRoute = (url: ReasonReact.Router.url) => { | ||
switch url.path { | ||
| ["callback"] => { | ||
let _token = LoginButton.Auth.handleAuth(url); | ||
Routes.Home; | ||
} | ||
| [] => { | ||
Js.Console.log("Home"); | ||
Routes.Home; | ||
} | ||
| _ => { | ||
Routes.Home; | ||
} /* Routes.NotFound */ | ||
} | ||
}; | ||
|
||
let make = _children => { | ||
...component, | ||
render: _self => | ||
reducer, | ||
initialState: () => { Routes.Home }, | ||
subscriptions: (self) => [ | ||
Sub( | ||
() => ReasonReact.Router.watchUrl((url) => self.send(ChangeRoute(url |> mapUrlToRoute))), | ||
ReasonReact.Router.unwatchUrl | ||
) | ||
], | ||
render: self => | ||
<ReactToolbox.ThemeProvider theme> | ||
<div className="app"> | ||
<Dokusho/> | ||
(switch self.state { | ||
| Routes.Home => <Dokusho/> | ||
}) | ||
</div> | ||
</ReactToolbox.ThemeProvider> | ||
}; | ||
}; |
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
Oops, something went wrong.