SlideShare a Scribd company logo
1 of 18
Download to read offline
Finch + Finagle-OAuth2
=
Purely Functional REST API
Vladimir Kostyukov
@vkostyukov
Finagle-OAuth2: Highlights
• Asynchronous version of Nulab’s scala-oauth2-provider
!
• Finagle-friendly API: OAuth2Request, OAuth2Filter	
!
• Does not depend on Finch
2
1 trait DataHandler[U] {	
2 ... 	
3 def findUser(username: String, password: String): Future[Option[U]]	
4 def createAccessToken(authInfo: AuthInfo[U]): Future[AccessToken]	
5 def getStoredAccessToken(authInfo: AuthInfo[U]): Future[Option[AccessToken]]	
6 def findAccessToken(token: String): Future[Option[AccessToken]]	
7 ...	
8 }	
Finagle-OAuth2: Step #1
DataHandler
3
Finagle-OAuth2: Step #2
Typesafe Auth
1 import com.twitter.finagle.oauth2._	
2 import com.twitter.finagle.oauth2.{OAuth2Filter, OAuth2Request}	
3 	
4 val auth = new OAuth2Filter(dataHandler)	
5 	
6 val hello = new Service[OAuth2Request[User], Response] {	
7 def apply(req: OAuth2Request[User]) = {	
8 println(s"Hello, ${req.authInfo.user}!")	
9 Future.value(Response())	
10 }	
11 }	
12 	
13 val backend: Service[Request, Response] = auth andThen hello	
4
1 import com.twitter.finagle.oauth2._	
2 import com.twitter.finagle.oauth2.OAuth2Endpoint	
3 	
4 val tokens: Service[Request, Response] = 	
5 new OAuth2Endpoint(dataHandler) with OAuthErrorInJson with OAuthTokenInJson	
Finagle-OAuth2: Step #3
Issue Acces Token
5
Thin layer of purely-functional basic blocks
on top of Finagle for building composable
REST APIs
Finch
https://github.com/finagle/finch
6
Finch: Highlights
• Was #1 Scala trending repo on GitHub for 95 mins
!
!
!
!
!
!
!
• Happily used in production by 2 customers:
• Konfettin
• JusBrasil
!
• Super simple & lightweight (~ 1.5k SLOC)
7
Finch: Quickstart
1 def hello(name: String) = new Service[HttpRequest, HttpResponse] = {	
2 def apply(req: HttpRequest) = for {	
3 title <- OptionalParam("title")(req)	
4 } yield Ok(s"Hello, ${title.getOrElse("")} $name!")	
5 }	
6 	
7 val endpoint = new Endpoint[HttpRequest, HttpResponse] {	
8 def route = {	
9 // routes requests like '/hello/Bob?title=Mr.'	
10 case Method.Get -> Root / "hello" / name => 	
11 BasicallyAuthorize("user", "password") ! hello(name)	
12 }	
13 }	
14 	
15 val service: Service[HttpRequest, HttpResponse] = endpoint.toService 	
8
Finch: Request Reader
(Reader Monad)
1 trait RequestReader[A] {	
2 	
3 def apply(req: HttpRequest): Future[A]	
4 	
5 def flatMap[B](fn: A => RequestReader[B]): RequestReader[B] = ???	
6 	
7 def map[B](fn: A => B): RequestReader[B] = ???	
8 }	
9
Finch: Request Reader
1 val pagination: RequestReader[(Int, Int)] = for {	
2 offset <- OptionalIntParam("offset")	
3 limit <- OptionalIntParam("limit")	
4 } yield (offset.getOrElse(0), math.min(limit.getOrElse(50), 50))	
5 	
6 val service = new Service[HttpRequest, HttpResponse] {	
7 def apply(req: HttpRequest) = for {	
8 (offsetIt, limit) <- pagination(req)	
9 } yield Ok(s"Fetching items $offset..${offset+limit}")	
10 }	
10
Finch: Params Validation
1 case class User(age: Int)	
2 	
3 val user: RequestReader[User] = 	
4 for { age <- RequiredIntParam("age") } yield User(age)	
5 	
6 val adult: RequestReader[User] = for {	
7 u <- user	
8 _ <- ValidationRule("age", "should be greater then 18") { user.age > 18 }	
9 } yield u	
10 	
11 val u: Future[JsonResponse] = adult(request) map { 	
12 JsonObject("age" -> _.age) 	
13 } handle {	
14 case e: ParamNotFound =>	
15 JsonObject("error" -> e.getMessage, "param" -> e.param)	
16 case e: ValidationFailed => 	
17 JsonObject("error" -> e.getMessage, "param" -> e.param)	
18 }	
11
Finch:
Request Reader Highlights
• RequiredParam, RequiredIntParam, etc 	
• Future.value[A]	
• Future.exception[ParamNotFound]
!
• OptionalParam, OptionalIntParam, etc	
• Future.value[Option[A]]
!
• Multi-value Params: RequiredParams, OptionalIntParams, etc.
• Future.value[List[A]]
!
• Params Validation: ValidationRule	
• Future.value[Unit]	
• Future.exception[ValidationFailed]
12
Finch: Responses
1 // empty response with status 200	
2 val a = Ok()	
3 	
4 // 'plain/text' response with status 404	
5 val b = NotFound("body")	
6 	
7 // 'application/json' response with status 201	
8 val c = Created(JsonObject("id" -> 100))	
9 	
10 // ‘plain/text' response with custom header and status 403	
11 val d = Forbidden.withHeaders("Some-Header" -> "Secret")("body") 	
13
Finch: Endpoints Highlights
• Finch’s Endpoints are composable routers
!
• Endpoints might be treated as Scala’s
PartialFunctions[Request, Service[_, _]]
!
• Endpoints are convertible to Finagle Service’s
!
• Endpoints might be composed with Service’s, Filter’s or
other Endpoint’s.
14
Finch:
Endpoints Composition
1 val ab: Filter[A, C, B, C] = ???	
2 val bc: Endpoint[B, C] = ???	
3 val cd: Service[C, D]	
4 	
5 val ad1: Endpoint[A, D] = ab ! bc ! cd	
6 val ad2: Endpoint[A, D] = ???	
7 	
8 val ad3: Endpoint[A, D] = ad1 orElse ad2	
15
Finagle rocks!
16
• A better JSON
• Lightweight in-memory caching API
Finch: Further Steps
17
• https://github.com/finagle/finch
• https://github.com/finagle/finagle-oauth2
Resources
@vkostyukov
18

More Related Content

What's hot

2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.jsNoritada Shimizu
 
The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185Mahmoud Samir Fayed
 
Javascript compilation execution
Javascript compilation executionJavascript compilation execution
Javascript compilation executionFanis Prodromou
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYMalikireddy Bramhananda Reddy
 
PyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for TornadoPyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for Tornadoemptysquare
 
JavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyJavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyYasuharu Nakano
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805t k
 
Guava - Elements of Functional Programming
Guava - Elements of Functional Programming Guava - Elements of Functional Programming
Guava - Elements of Functional Programming Anna Shymchenko
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OBuzzcapture
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲームNoritada Shimizu
 
c++ project on restaurant billing
c++ project on restaurant billing c++ project on restaurant billing
c++ project on restaurant billing Swakriti Rathore
 
Tilting at Windmills with ctypes and cygwinreg
Tilting at Windmills with ctypes and cygwinregTilting at Windmills with ctypes and cygwinreg
Tilting at Windmills with ctypes and cygwinregSimon Law
 

What's hot (20)

2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js2016 gunma.web games-and-asm.js
2016 gunma.web games-and-asm.js
 
20151224-games
20151224-games20151224-games
20151224-games
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
Introduction to Go for Java Programmers
Introduction to Go for Java ProgrammersIntroduction to Go for Java Programmers
Introduction to Go for Java Programmers
 
The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185
 
Javascript compilation execution
Javascript compilation executionJavascript compilation execution
Javascript compilation execution
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 
PyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for TornadoPyCon lightning talk on my Toro module for Tornado
PyCon lightning talk on my Toro module for Tornado
 
JavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyJavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovy
 
サイ本 文
サイ本 文サイ本 文
サイ本 文
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
 
ECMAScript 5: Новое в JavaScript
ECMAScript 5: Новое в JavaScriptECMAScript 5: Новое в JavaScript
ECMAScript 5: Новое в JavaScript
 
Guava - Elements of Functional Programming
Guava - Elements of Functional Programming Guava - Elements of Functional Programming
Guava - Elements of Functional Programming
 
Python meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/OPython meetup: coroutines, event loops, and non-blocking I/O
Python meetup: coroutines, event loops, and non-blocking I/O
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲーム
 
Queue oop
Queue   oopQueue   oop
Queue oop
 
c++ project on restaurant billing
c++ project on restaurant billing c++ project on restaurant billing
c++ project on restaurant billing
 
Tilting at Windmills with ctypes and cygwinreg
Tilting at Windmills with ctypes and cygwinregTilting at Windmills with ctypes and cygwinreg
Tilting at Windmills with ctypes and cygwinreg
 
Textile
TextileTextile
Textile
 

Similar to Finch + Finagle OAuth2

Rpi python web
Rpi python webRpi python web
Rpi python websewoo lee
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswanivvaswani
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparisonHiroshi Nakamura
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented NetworkingMostafa Amer
 
Introduction to Finch
Introduction to FinchIntroduction to Finch
Introduction to FinchSeiya Mizuno
 
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the AirAvitoTech
 
Ruby on Rails: Tasty Burgers
Ruby on Rails: Tasty BurgersRuby on Rails: Tasty Burgers
Ruby on Rails: Tasty BurgersAaron Patterson
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveJeff Smith
 
Phoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってるPhoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってるTakahiro Kobaru
 
Julio Capote, Twitter
Julio Capote, TwitterJulio Capote, Twitter
Julio Capote, TwitterOntico
 
Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)danwrong
 
DevOpsCon 2021: Go Web Development 101
DevOpsCon 2021: Go Web Development 101DevOpsCon 2021: Go Web Development 101
DevOpsCon 2021: Go Web Development 101Jan Stamer
 
Let's read code: the python-requests library
Let's read code: the python-requests libraryLet's read code: the python-requests library
Let's read code: the python-requests librarySusan Tan
 
entwickler.de Go Day: Go Web Development 101
entwickler.de Go Day: Go Web Development 101entwickler.de Go Day: Go Web Development 101
entwickler.de Go Day: Go Web Development 101Jan Stamer
 

Similar to Finch + Finagle OAuth2 (20)

Rpi python web
Rpi python webRpi python web
Rpi python web
 
Http4s
Http4s Http4s
Http4s
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
 
Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6Tamir Dresher - What’s new in ASP.NET Core 6
Tamir Dresher - What’s new in ASP.NET Core 6
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented Networking
 
Introduction to Finch
Introduction to FinchIntroduction to Finch
Introduction to Finch
 
Solr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene EuroconSolr @ Etsy - Apache Lucene Eurocon
Solr @ Etsy - Apache Lucene Eurocon
 
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
“iOS 11 в App in the Air”, Пронин Сергей, App in the Air
 
Ruby on Rails: Tasty Burgers
Ruby on Rails: Tasty BurgersRuby on Rails: Tasty Burgers
Ruby on Rails: Tasty Burgers
 
Tools for Making Machine Learning more Reactive
Tools for Making Machine Learning more ReactiveTools for Making Machine Learning more Reactive
Tools for Making Machine Learning more Reactive
 
Socket.io
Socket.ioSocket.io
Socket.io
 
Time for Functions
Time for FunctionsTime for Functions
Time for Functions
 
Phoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってるPhoenix + Reactで 社内システムを 密かに作ってる
Phoenix + Reactで 社内システムを 密かに作ってる
 
Julio Capote, Twitter
Julio Capote, TwitterJulio Capote, Twitter
Julio Capote, Twitter
 
Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)
 
DevOpsCon 2021: Go Web Development 101
DevOpsCon 2021: Go Web Development 101DevOpsCon 2021: Go Web Development 101
DevOpsCon 2021: Go Web Development 101
 
Let's read code: the python-requests library
Let's read code: the python-requests libraryLet's read code: the python-requests library
Let's read code: the python-requests library
 
entwickler.de Go Day: Go Web Development 101
entwickler.de Go Day: Go Web Development 101entwickler.de Go Day: Go Web Development 101
entwickler.de Go Day: Go Web Development 101
 
Having Fun Programming!
Having Fun Programming!Having Fun Programming!
Having Fun Programming!
 

Recently uploaded

Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Romil Mishra
 
Novel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending ActuatorsNovel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending ActuatorsResearcher Researcher
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESCME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESkarthi keyan
 
KCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosKCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosVictor Morales
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdfsahilsajad201
 
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfPaper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfNainaShrivastava14
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdfCaalaaAbdulkerim
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfalene1
 
Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodManicka Mamallan Andavar
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptxmohitesoham12
 
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTFUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTSneha Padhiar
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating SystemRashmi Bhat
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdfHafizMudaserAhmad
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solidnamansinghjarodiya
 
signals in triangulation .. ...Surveying
signals in triangulation .. ...Surveyingsignals in triangulation .. ...Surveying
signals in triangulation .. ...Surveyingsapna80328
 
Artificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewArtificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewsandhya757531
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 

Recently uploaded (20)

Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________Gravity concentration_MI20612MI_________
Gravity concentration_MI20612MI_________
 
Novel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending ActuatorsNovel 3D-Printed Soft Linear and Bending Actuators
Novel 3D-Printed Soft Linear and Bending Actuators
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTESCME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
CME 397 - SURFACE ENGINEERING - UNIT 1 FULL NOTES
 
KCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitosKCD Costa Rica 2024 - Nephio para parvulitos
KCD Costa Rica 2024 - Nephio para parvulitos
 
Robotics Group 10 (Control Schemes) cse.pdf
Robotics Group 10  (Control Schemes) cse.pdfRobotics Group 10  (Control Schemes) cse.pdf
Robotics Group 10 (Control Schemes) cse.pdf
 
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdfPaper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
Paper Tube : Shigeru Ban projects and Case Study of Cardboard Cathedral .pdf
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdf
 
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdfComprehensive energy systems.pdf Comprehensive energy systems.pdf
Comprehensive energy systems.pdf Comprehensive energy systems.pdf
 
Levelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument methodLevelling - Rise and fall - Height of instrument method
Levelling - Rise and fall - Height of instrument method
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
 
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENTFUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
FUNCTIONAL AND NON FUNCTIONAL REQUIREMENT
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating System
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf
 
Engineering Drawing section of solid
Engineering Drawing     section of solidEngineering Drawing     section of solid
Engineering Drawing section of solid
 
signals in triangulation .. ...Surveying
signals in triangulation .. ...Surveyingsignals in triangulation .. ...Surveying
signals in triangulation .. ...Surveying
 
Artificial Intelligence in Power System overview
Artificial Intelligence in Power System overviewArtificial Intelligence in Power System overview
Artificial Intelligence in Power System overview
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 

Finch + Finagle OAuth2

  • 1. Finch + Finagle-OAuth2 = Purely Functional REST API Vladimir Kostyukov @vkostyukov
  • 2. Finagle-OAuth2: Highlights • Asynchronous version of Nulab’s scala-oauth2-provider ! • Finagle-friendly API: OAuth2Request, OAuth2Filter ! • Does not depend on Finch 2
  • 3. 1 trait DataHandler[U] { 2 ... 3 def findUser(username: String, password: String): Future[Option[U]] 4 def createAccessToken(authInfo: AuthInfo[U]): Future[AccessToken] 5 def getStoredAccessToken(authInfo: AuthInfo[U]): Future[Option[AccessToken]] 6 def findAccessToken(token: String): Future[Option[AccessToken]] 7 ... 8 } Finagle-OAuth2: Step #1 DataHandler 3
  • 4. Finagle-OAuth2: Step #2 Typesafe Auth 1 import com.twitter.finagle.oauth2._ 2 import com.twitter.finagle.oauth2.{OAuth2Filter, OAuth2Request} 3 4 val auth = new OAuth2Filter(dataHandler) 5 6 val hello = new Service[OAuth2Request[User], Response] { 7 def apply(req: OAuth2Request[User]) = { 8 println(s"Hello, ${req.authInfo.user}!") 9 Future.value(Response()) 10 } 11 } 12 13 val backend: Service[Request, Response] = auth andThen hello 4
  • 5. 1 import com.twitter.finagle.oauth2._ 2 import com.twitter.finagle.oauth2.OAuth2Endpoint 3 4 val tokens: Service[Request, Response] = 5 new OAuth2Endpoint(dataHandler) with OAuthErrorInJson with OAuthTokenInJson Finagle-OAuth2: Step #3 Issue Acces Token 5
  • 6. Thin layer of purely-functional basic blocks on top of Finagle for building composable REST APIs Finch https://github.com/finagle/finch 6
  • 7. Finch: Highlights • Was #1 Scala trending repo on GitHub for 95 mins ! ! ! ! ! ! ! • Happily used in production by 2 customers: • Konfettin • JusBrasil ! • Super simple & lightweight (~ 1.5k SLOC) 7
  • 8. Finch: Quickstart 1 def hello(name: String) = new Service[HttpRequest, HttpResponse] = { 2 def apply(req: HttpRequest) = for { 3 title <- OptionalParam("title")(req) 4 } yield Ok(s"Hello, ${title.getOrElse("")} $name!") 5 } 6 7 val endpoint = new Endpoint[HttpRequest, HttpResponse] { 8 def route = { 9 // routes requests like '/hello/Bob?title=Mr.' 10 case Method.Get -> Root / "hello" / name => 11 BasicallyAuthorize("user", "password") ! hello(name) 12 } 13 } 14 15 val service: Service[HttpRequest, HttpResponse] = endpoint.toService 8
  • 9. Finch: Request Reader (Reader Monad) 1 trait RequestReader[A] { 2 3 def apply(req: HttpRequest): Future[A] 4 5 def flatMap[B](fn: A => RequestReader[B]): RequestReader[B] = ??? 6 7 def map[B](fn: A => B): RequestReader[B] = ??? 8 } 9
  • 10. Finch: Request Reader 1 val pagination: RequestReader[(Int, Int)] = for { 2 offset <- OptionalIntParam("offset") 3 limit <- OptionalIntParam("limit") 4 } yield (offset.getOrElse(0), math.min(limit.getOrElse(50), 50)) 5 6 val service = new Service[HttpRequest, HttpResponse] { 7 def apply(req: HttpRequest) = for { 8 (offsetIt, limit) <- pagination(req) 9 } yield Ok(s"Fetching items $offset..${offset+limit}") 10 } 10
  • 11. Finch: Params Validation 1 case class User(age: Int) 2 3 val user: RequestReader[User] = 4 for { age <- RequiredIntParam("age") } yield User(age) 5 6 val adult: RequestReader[User] = for { 7 u <- user 8 _ <- ValidationRule("age", "should be greater then 18") { user.age > 18 } 9 } yield u 10 11 val u: Future[JsonResponse] = adult(request) map { 12 JsonObject("age" -> _.age) 13 } handle { 14 case e: ParamNotFound => 15 JsonObject("error" -> e.getMessage, "param" -> e.param) 16 case e: ValidationFailed => 17 JsonObject("error" -> e.getMessage, "param" -> e.param) 18 } 11
  • 12. Finch: Request Reader Highlights • RequiredParam, RequiredIntParam, etc • Future.value[A] • Future.exception[ParamNotFound] ! • OptionalParam, OptionalIntParam, etc • Future.value[Option[A]] ! • Multi-value Params: RequiredParams, OptionalIntParams, etc. • Future.value[List[A]] ! • Params Validation: ValidationRule • Future.value[Unit] • Future.exception[ValidationFailed] 12
  • 13. Finch: Responses 1 // empty response with status 200 2 val a = Ok() 3 4 // 'plain/text' response with status 404 5 val b = NotFound("body") 6 7 // 'application/json' response with status 201 8 val c = Created(JsonObject("id" -> 100)) 9 10 // ‘plain/text' response with custom header and status 403 11 val d = Forbidden.withHeaders("Some-Header" -> "Secret")("body") 13
  • 14. Finch: Endpoints Highlights • Finch’s Endpoints are composable routers ! • Endpoints might be treated as Scala’s PartialFunctions[Request, Service[_, _]] ! • Endpoints are convertible to Finagle Service’s ! • Endpoints might be composed with Service’s, Filter’s or other Endpoint’s. 14
  • 15. Finch: Endpoints Composition 1 val ab: Filter[A, C, B, C] = ??? 2 val bc: Endpoint[B, C] = ??? 3 val cd: Service[C, D] 4 5 val ad1: Endpoint[A, D] = ab ! bc ! cd 6 val ad2: Endpoint[A, D] = ??? 7 8 val ad3: Endpoint[A, D] = ad1 orElse ad2 15
  • 17. • A better JSON • Lightweight in-memory caching API Finch: Further Steps 17