Safe Haskell | None |
---|---|
Language | Haskell2010 |
Modules and support functions required by most or all provider implementations. May also be useful for writing local providers.
Synopsis
- authGetProfile :: FromJSON a => Text -> Manager -> OAuth2Token -> URI -> IO (a, ByteString)
- scopeParam :: Text -> [Text] -> (ByteString, ByteString)
- setExtra :: OAuth2Token -> ByteString -> [(Text, Text)]
- data Text
- decodeUtf8 :: ByteString -> Text
- encodeUtf8 :: Text -> ByteString
- (.:) :: FromJSON a => Object -> Text -> Parser a
- (.:?) :: FromJSON a => Object -> Text -> Parser (Maybe a)
- (.=) :: (KeyValue kv, ToJSON v) => Text -> v -> kv
- (<>) :: Semigroup a => a -> a -> a
- class FromJSON a where
- class ToJSON a where
- toJSON :: a -> Value
- toEncoding :: a -> Encoding
- toJSONList :: [a] -> Value
- toEncodingList :: [a] -> Encoding
- eitherDecode :: FromJSON a => ByteString -> Either String a
- withObject :: String -> (Object -> Parser a) -> Value -> Parser a
- throwIO :: (MonadThrow m, Exception e) => e -> m a
- data OAuth2 = OAuth2 {}
- data OAuth2Token = OAuth2Token {}
- newtype AccessToken = AccessToken {}
- newtype RefreshToken = RefreshToken {}
- data Manager
- class (Yesod master, PathPiece (AuthId master), RenderMessage master FormMessage) => YesodAuth master where
- type AuthId master
- authLayout :: (MonadHandler m, HandlerSite m ~ master) => WidgetFor master () -> m Html
- loginDest :: master -> Route master
- logoutDest :: master -> Route master
- authenticate :: (MonadHandler m, HandlerSite m ~ master) => Creds master -> m (AuthenticationResult master)
- getAuthId :: (MonadHandler m, HandlerSite m ~ master) => Creds master -> m (Maybe (AuthId master))
- authPlugins :: master -> [AuthPlugin master]
- loginHandler :: AuthHandler master Html
- renderAuthMessage :: master -> [Text] -> AuthMessage -> Text
- redirectToReferer :: master -> Bool
- redirectToCurrent :: master -> Bool
- authHttpManager :: (MonadHandler m, HandlerSite m ~ master) => m Manager
- onLogin :: (MonadHandler m, master ~ HandlerSite m) => m ()
- onLogout :: (MonadHandler m, master ~ HandlerSite m) => m ()
- maybeAuthId :: (MonadHandler m, master ~ HandlerSite m) => m (Maybe (AuthId master))
- onErrorHtml :: (MonadHandler m, HandlerSite m ~ master) => Route master -> Text -> m Html
- runHttpRequest :: (MonadHandler m, HandlerSite m ~ master, MonadUnliftIO m) => Request -> (Response BodyReader -> m a) -> m a
- data AuthPlugin master = AuthPlugin {
- apName :: Text
- apDispatch :: Method -> [Piece] -> AuthHandler master TypedContent
- apLogin :: (Route Auth -> Route master) -> WidgetFor master ()
- data Creds master = Creds {
- credsPlugin :: Text
- credsIdent :: Text
- credsExtra :: [(Text, Text)]
- type URI = URIRef Absolute
- newtype Host = Host {
- hostBS :: ByteString
- module URI.ByteString.Extension
- authOAuth2 :: YesodAuth m => Text -> OAuth2 -> FetchCreds m -> AuthPlugin m
- authOAuth2Widget :: YesodAuth m => WidgetFor m () -> Text -> OAuth2 -> FetchCreds m -> AuthPlugin m
Provider helpers
authGetProfile :: FromJSON a => Text -> Manager -> OAuth2Token -> URI -> IO (a, ByteString) Source #
Retrieve a user's profile as JSON
The response should be parsed only far enough to read the required
. Additional information should either be re-parsed by or
fetched via additional requests by consumers.credsIdent
scopeParam :: Text -> [Text] -> (ByteString, ByteString) Source #
A tuple of "scope"
and the given scopes separated by a delimiter
setExtra :: OAuth2Token -> ByteString -> [(Text, Text)] Source #
Construct part of credsExtra
Always the following keys:
accessToken
: to support follow-up requestsuserResponse
: to support getting additional information
May set the following keys:
refreshToken
: if the provider supports refreshing theaccessToken
Text
A space efficient, packed, unboxed Unicode text type.
Instances
decodeUtf8 :: ByteString -> Text #
Decode a ByteString
containing UTF-8 encoded text that is known
to be valid.
If the input contains any invalid UTF-8 data, an exception will be
thrown that cannot be caught in pure code. For more control over
the handling of invalid data, use decodeUtf8'
or
decodeUtf8With
.
encodeUtf8 :: Text -> ByteString #
Encode text using UTF-8 encoding.
JSON
(.:) :: FromJSON a => Object -> Text -> Parser a #
Retrieve the value associated with the given key of an Object
.
The result is empty
if the key is not present or the value cannot
be converted to the desired type.
This accessor is appropriate if the key and value must be present
in an object for it to be valid. If the key and value are
optional, use .:?
instead.
(.:?) :: FromJSON a => Object -> Text -> Parser (Maybe a) #
Retrieve the value associated with the given key of an Object
. The
result is Nothing
if the key is not present or if its value is Null
,
or empty
if the value cannot be converted to the desired type.
This accessor is most useful if the key and value can be absent
from an object without affecting its validity. If the key and
value are mandatory, use .:
instead.
(<>) :: Semigroup a => a -> a -> a infixr 6 #
An associative operation.
>>>
[1,2,3] <> [4,5,6]
[1,2,3,4,5,6]
A type that can be converted from JSON, with the possibility of failure.
In many cases, you can get the compiler to generate parsing code for you (see below). To begin, let's cover writing an instance by hand.
There are various reasons a conversion could fail. For example, an
Object
could be missing a required key, an Array
could be of
the wrong size, or a value could be of an incompatible type.
The basic ways to signal a failed conversion are as follows:
fail
yields a custom error message: it is the recommended way of reporting a failure;empty
(ormzero
) is uninformative: use it when the error is meant to be caught by some(
;<|>
)typeMismatch
can be used to report a failure when the encountered value is not of the expected JSON type;unexpected
is an appropriate alternative when more than one type may be expected, or to keep the expected type implicit.
prependFailure
(or modifyFailure
) add more information to a parser's
error messages.
An example type and instance using typeMismatch
and prependFailure
:
-- Allow ourselves to writeText
literals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceFromJSON
Coord whereparseJSON
(Object
v) = Coord<$>
v.:
"x"<*>
v.:
"y" -- We do not expect a non-Object
value here. -- We could useempty
to fail, buttypeMismatch
-- gives a much more informative error message.parseJSON
invalid =prependFailure
"parsing Coord failed, " (typeMismatch
"Object" invalid)
For this common case of only being concerned with a single
type of JSON value, the functions withObject
, withScientific
, etc.
are provided. Their use is to be preferred when possible, since
they are more terse. Using withObject
, we can rewrite the above instance
(assuming the same language extension and data type) as:
instanceFromJSON
Coord whereparseJSON
=withObject
"Coord" $ \v -> Coord<$>
v.:
"x"<*>
v.:
"y"
Instead of manually writing your FromJSON
instance, there are two options
to do it automatically:
- Data.Aeson.TH provides Template Haskell functions which will derive an instance at compile time. The generated instance is optimized for your type so it will probably be more efficient than the following option.
- The compiler can provide a default generic implementation for
parseJSON
.
To use the second, simply add a deriving
clause to your
datatype and declare a Generic
FromJSON
instance for your datatype without giving
a definition for parseJSON
.
For example, the previous example can be simplified to just:
{-# LANGUAGE DeriveGeneric #-} import GHC.Generics data Coord = Coord { x :: Double, y :: Double } derivingGeneric
instanceFromJSON
Coord
The default implementation will be equivalent to
parseJSON =
; if you need different
options, you can customize the generic decoding by defining:genericParseJSON
defaultOptions
customOptions =defaultOptions
{fieldLabelModifier
=map
toUpper
} instanceFromJSON
Coord whereparseJSON
=genericParseJSON
customOptions
Nothing
Instances
A type that can be converted to JSON.
Instances in general must specify toJSON
and should (but don't need
to) specify toEncoding
.
An example type and instance:
-- Allow ourselves to writeText
literals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceToJSON
Coord wheretoJSON
(Coord x y) =object
["x".=
x, "y".=
y]toEncoding
(Coord x y) =pairs
("x".=
x<>
"y".=
y)
Instead of manually writing your ToJSON
instance, there are two options
to do it automatically:
- Data.Aeson.TH provides Template Haskell functions which will derive an instance at compile time. The generated instance is optimized for your type so it will probably be more efficient than the following option.
- The compiler can provide a default generic implementation for
toJSON
.
To use the second, simply add a deriving
clause to your
datatype and declare a Generic
ToJSON
instance. If you require nothing other than
defaultOptions
, it is sufficient to write (and this is the only
alternative where the default toJSON
implementation is sufficient):
{-# LANGUAGE DeriveGeneric #-} import GHC.Generics data Coord = Coord { x :: Double, y :: Double } derivingGeneric
instanceToJSON
Coord wheretoEncoding
=genericToEncoding
defaultOptions
If on the other hand you wish to customize the generic decoding, you have to implement both methods:
customOptions =defaultOptions
{fieldLabelModifier
=map
toUpper
} instanceToJSON
Coord wheretoJSON
=genericToJSON
customOptionstoEncoding
=genericToEncoding
customOptions
Previous versions of this library only had the toJSON
method. Adding
toEncoding
had two reasons:
- toEncoding is more efficient for the common case that the output of
toJSON
is directly serialized to aByteString
. Further, expressing either method in terms of the other would be non-optimal. - The choice of defaults allows a smooth transition for existing users:
Existing instances that do not define
toEncoding
still compile and have the correct semantics. This is ensured by making the default implementation oftoEncoding
usetoJSON
. This produces correct results, but since it performs an intermediate conversion to aValue
, it will be less efficient than directly emitting anEncoding
. (this also means that specifying nothing more thaninstance ToJSON Coord
would be sufficient as a generically decoding instance, but there probably exists no good reason to not specifytoEncoding
in new instances.)
Nothing
Convert a Haskell value to a JSON-friendly intermediate type.
toEncoding :: a -> Encoding #
Encode a Haskell value as JSON.
The default implementation of this method creates an
intermediate Value
using toJSON
. This provides
source-level compatibility for people upgrading from older
versions of this library, but obviously offers no performance
advantage.
To benefit from direct encoding, you must provide an
implementation for this method. The easiest way to do so is by
having your types implement Generic
using the DeriveGeneric
extension, and then have GHC generate a method body as follows.
instanceToJSON
Coord wheretoEncoding
=genericToEncoding
defaultOptions
toJSONList :: [a] -> Value #
toEncodingList :: [a] -> Encoding #
Instances
eitherDecode :: FromJSON a => ByteString -> Either String a #
Like decode
but returns an error message when decoding fails.
withObject :: String -> (Object -> Parser a) -> Value -> Parser a #
applies withObject
name f valuef
to the Object
when value
is an Object
and fails otherwise.
Error message example
withObject "MyType" f (String "oops") -- Error: "parsing MyType failed, expected Object, but encountered String"
Exceptions
throwIO :: (MonadThrow m, Exception e) => e -> m a #
Synonym for throw
Since: safe-exceptions-0.1.0.0
OAuth2
Query Parameter Representation
data OAuth2Token #
The gained Access Token. Use Data.Aeson.decode
to
decode string to AccessToken
. The refreshToken
is
special in some cases,
e.g. https://developers.google.com/accounts/docs/OAuth2
OAuth2Token | |
|
Instances
newtype AccessToken #
Instances
Eq AccessToken | |
Defined in Network.OAuth.OAuth2.Internal (==) :: AccessToken -> AccessToken -> Bool # (/=) :: AccessToken -> AccessToken -> Bool # | |
Show AccessToken | |
Defined in Network.OAuth.OAuth2.Internal showsPrec :: Int -> AccessToken -> ShowS # show :: AccessToken -> String # showList :: [AccessToken] -> ShowS # | |
ToJSON AccessToken | |
Defined in Network.OAuth.OAuth2.Internal toJSON :: AccessToken -> Value # toEncoding :: AccessToken -> Encoding # toJSONList :: [AccessToken] -> Value # toEncodingList :: [AccessToken] -> Encoding # | |
FromJSON AccessToken | |
Defined in Network.OAuth.OAuth2.Internal parseJSON :: Value -> Parser AccessToken # parseJSONList :: Value -> Parser [AccessToken] # | |
Binary AccessToken | |
Defined in Network.OAuth.OAuth2.Internal |
newtype RefreshToken #
Instances
Eq RefreshToken | |
Defined in Network.OAuth.OAuth2.Internal (==) :: RefreshToken -> RefreshToken -> Bool # (/=) :: RefreshToken -> RefreshToken -> Bool # | |
Show RefreshToken | |
Defined in Network.OAuth.OAuth2.Internal showsPrec :: Int -> RefreshToken -> ShowS # show :: RefreshToken -> String # showList :: [RefreshToken] -> ShowS # | |
ToJSON RefreshToken | |
Defined in Network.OAuth.OAuth2.Internal toJSON :: RefreshToken -> Value # toEncoding :: RefreshToken -> Encoding # toJSONList :: [RefreshToken] -> Value # toEncodingList :: [RefreshToken] -> Encoding # | |
FromJSON RefreshToken | |
Defined in Network.OAuth.OAuth2.Internal parseJSON :: Value -> Parser RefreshToken # parseJSONList :: Value -> Parser [RefreshToken] # | |
Binary RefreshToken | |
Defined in Network.OAuth.OAuth2.Internal |
HTTP
Keeps track of open connections for keep-alive.
If possible, you should share a single Manager
between multiple threads and requests.
Since 0.1.0
Instances
HasHttpManager Manager | |
Defined in Network.HTTP.Client.Types getHttpManager :: Manager -> Manager # |
Yesod
class (Yesod master, PathPiece (AuthId master), RenderMessage master FormMessage) => YesodAuth master where #
authLayout :: (MonadHandler m, HandlerSite m ~ master) => WidgetFor master () -> m Html #
specify the layout. Uses defaultLayout by default
loginDest :: master -> Route master #
Default destination on successful login, if no other destination exists.
logoutDest :: master -> Route master #
Default destination on successful logout, if no other destination exists.
authenticate :: (MonadHandler m, HandlerSite m ~ master) => Creds master -> m (AuthenticationResult master) #
Perform authentication based on the given credentials.
Default implementation is in terms of getAuthId
@since: 1.4.4
getAuthId :: (MonadHandler m, HandlerSite m ~ master) => Creds master -> m (Maybe (AuthId master)) #
Determine the ID associated with the set of credentials.
Default implementation is in terms of authenticate
authPlugins :: master -> [AuthPlugin master] #
Which authentication backends to use.
loginHandler :: AuthHandler master Html #
What to show on the login page.
By default this calls defaultLoginHandler
, which concatenates
plugin widgets and wraps the result in authLayout
. Override if
you need fancy widget containers, additional functionality, or an
entirely custom page. For example, in some applications you may
want to prevent the login page being displayed for a user who is
already logged in, even if the URL is visited explicitly; this can
be done by overriding loginHandler
in your instance declaration
with something like:
instance YesodAuth App where ... loginHandler = do ma <- lift maybeAuthId when (isJust ma) $ lift $ redirect HomeR -- or any other Handler code you want defaultLoginHandler
:: master | |
-> [Text] | languages |
-> AuthMessage | |
-> Text |
Used for i18n of messages provided by this package.
redirectToReferer :: master -> Bool #
After login and logout, redirect to the referring page, instead of
loginDest
and logoutDest
. Default is False
.
redirectToCurrent :: master -> Bool #
When being redirected to the login page should the current page
be set to redirect back to. Default is True
.
Since: yesod-auth-1.4.21
authHttpManager :: (MonadHandler m, HandlerSite m ~ master) => m Manager #
Return an HTTP connection manager that is stored in the foundation
type. This allows backends to reuse persistent connections. If none of
the backends you're using use HTTP connections, you can safely return
error "authHttpManager"
here.
onLogin :: (MonadHandler m, master ~ HandlerSite m) => m () #
Called on a successful login. By default, calls
addMessageI "success" NowLoggedIn
.
onLogout :: (MonadHandler m, master ~ HandlerSite m) => m () #
Called on logout. By default, does nothing
maybeAuthId :: (MonadHandler m, master ~ HandlerSite m) => m (Maybe (AuthId master)) #
Retrieves user credentials, if user is authenticated.
By default, this calls defaultMaybeAuthId
to get the user ID from the
session. This can be overridden to allow authentication via other means,
such as checking for a special token in a request header. This is
especially useful for creating an API to be accessed via some means
other than a browser.
Since: yesod-auth-1.2.0
onErrorHtml :: (MonadHandler m, HandlerSite m ~ master) => Route master -> Text -> m Html #
Called on login error for HTTP requests. By default, calls
addMessage
with "error" as status and redirects to dest
.
runHttpRequest :: (MonadHandler m, HandlerSite m ~ master, MonadUnliftIO m) => Request -> (Response BodyReader -> m a) -> m a #
runHttpRequest gives you a chance to handle an HttpException and retry The default behavior is to simply execute the request which will throw an exception on failure
The HTTP Request
is given in case it is useful to change behavior based on inspecting the request.
This is an experimental API that is not broadly used throughout the yesod-auth code base
data AuthPlugin master #
AuthPlugin | |
|
User credentials
Creds | |
|
Bytestring URI types
Host | |
|
Instances
Eq Host | |
Ord Host | |
Show Host | |
IsString Host Source # | |
Defined in URI.ByteString.Extension fromString :: String -> Host # | |
Generic Host | |
Lift Host | |
type Rep Host | |
Defined in URI.ByteString.Types type Rep Host = D1 ('MetaData "Host" "URI.ByteString.Types" "uri-bytestring-0.3.3.0-4UPhePVWiGu7slEXJKin93" 'True) (C1 ('MetaCons "Host" 'PrefixI 'True) (S1 ('MetaSel ('Just "hostBS") 'NoSourceUnpackedness 'NoSourceStrictness 'DecidedLazy) (Rec0 ByteString))) |
Bytestring URI extensions
module URI.ByteString.Extension
Temporary, until I finish re-structuring modules
authOAuth2 :: YesodAuth m => Text -> OAuth2 -> FetchCreds m -> AuthPlugin m Source #
Create an
for the given OAuth2 providerAuthPlugin
Presents a generic "Login via #{name}"
link
authOAuth2Widget :: YesodAuth m => WidgetFor m () -> Text -> OAuth2 -> FetchCreds m -> AuthPlugin m Source #
Create an
for the given OAuth2 providerAuthPlugin
Allows passing a custom widget for the login link. See
for an
example.oauth2Eve