| Safe Haskell | Safe-Inferred |
|---|---|
| Language | Haskell2010 |
Yesod.Auth.OAuth2.Prelude
Description
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 -> Key -> Parser a
- (.:?) :: FromJSON a => Object -> Key -> Parser (Maybe a)
- (.=) :: (KeyValue e kv, ToJSON v) => Key -> v -> kv
- (<>) :: Semigroup a => a -> a -> a
- class FromJSON a where
- parseJSON :: Value -> Parser a
- parseJSONList :: Value -> Parser [a]
- omittedField :: Maybe a
- class ToJSON a where
- toJSON :: a -> Value
- toEncoding :: a -> Encoding
- toJSONList :: [a] -> Value
- toEncodingList :: [a] -> Encoding
- omitField :: a -> Bool
- eitherDecode :: FromJSON a => ByteString -> Either String a
- withObject :: String -> (Object -> Parser a) -> Value -> Parser a
- throwIO :: (HasCallStack, 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
Documentation
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.
This is a partial function: it checks that input is a well-formed UTF-8 sequence and copies buffer or throws an error otherwise.
encodeUtf8 :: Text -> ByteString #
Encode text using UTF-8 encoding.
JSON
(.:) :: FromJSON a => Object -> Key -> 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 -> Key -> 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:
failyields 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(;<|>)typeMismatchcan be used to report a failure when the encountered value is not of the expected JSON type;unexpectedis 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 writeTextliterals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceFromJSONCoord whereparseJSON(Objectv) = Coord<$>v.:"x"<*>v.:"y" -- We do not expect a non-Objectvalue here. -- We could useemptyto fail, buttypeMismatch-- gives a much more informative error message.parseJSONinvalid =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:
instanceFromJSONCoord 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 GenericFromJSON 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 } deriving Generic instance FromJSON Coord or using the DerivingVia extension
deriving viaGenericallyCoord instanceFromJSONCoord
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=maptoUpper} instanceFromJSONCoord whereparseJSON=genericParseJSONcustomOptions
Minimal complete definition
Nothing
Methods
parseJSON :: Value -> Parser a #
parseJSONList :: Value -> Parser [a] #
omittedField :: Maybe a #
Default value for optional fields. Used by ( operator, and Generics and TH deriving with .:?=) (default).allowOmittedFields = True
Since: aeson-2.2.0.0
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 writeTextliterals. {-# LANGUAGE OverloadedStrings #-} data Coord = Coord { x :: Double, y :: Double } instanceToJSONCoord 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 GenericToJSON 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 } deriving Generic instance ToJSON Coord where toEncoding = genericToEncoding defaultOptions or more conveniently using the DerivingVia extension
deriving viaGenericallyCoord instanceToJSONCoord
If on the other hand you wish to customize the generic decoding, you have to implement both methods:
customOptions =defaultOptions{fieldLabelModifier=maptoUpper} instanceToJSONCoord wheretoJSON=genericToJSONcustomOptionstoEncoding=genericToEncodingcustomOptions
Previous versions of this library only had the toJSON method. Adding toEncoding had two reasons:
toEncodingis more efficient for the common case that the output oftoJSONis 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
toEncodingstill compile and have the correct semantics. This is ensured by making the default implementation oftoEncodingusetoJSON. 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 Coordwould be sufficient as a generically decoding instance, but there probably exists no good reason to not specifytoEncodingin new instances.)
Minimal complete definition
Nothing
Methods
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.
instanceToJSONCoord wheretoEncoding=genericToEncodingdefaultOptions
toJSONList :: [a] -> Value #
toEncodingList :: [a] -> Encoding #
Defines when it is acceptable to omit a field of this type from a record. Used by ( operator, and Generics and TH deriving with .?=).omitNothingFields = True
Since: aeson-2.2.0.0
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 :: (HasCallStack, MonadThrow m, Exception e) => e -> m a #
Synonym for throw
Since: safe-exceptions-0.1.0.0
OAuth2
Constructors
| OAuth2 | |
data OAuth2Token #
Constructors
| OAuth2Token | |
Fields
| |
Instances
newtype AccessToken #
Constructors
| AccessToken | |
Instances
| FromJSON AccessToken | |
Defined in Network.OAuth.OAuth2.Internal | |
| ToJSON AccessToken | |
Defined in Network.OAuth.OAuth2.Internal Methods toJSON :: AccessToken -> Value # toEncoding :: AccessToken -> Encoding # toJSONList :: [AccessToken] -> Value # toEncodingList :: [AccessToken] -> Encoding # omitField :: AccessToken -> Bool # | |
| Show AccessToken | |
Defined in Network.OAuth.OAuth2.Internal Methods showsPrec :: Int -> AccessToken -> ShowS # show :: AccessToken -> String # showList :: [AccessToken] -> ShowS # | |
| Binary AccessToken | |
Defined in Network.OAuth.OAuth2.Internal | |
| Eq AccessToken | |
Defined in Network.OAuth.OAuth2.Internal | |
newtype RefreshToken #
Constructors
| RefreshToken | |
Instances
| FromJSON RefreshToken | |
Defined in Network.OAuth.OAuth2.Internal | |
| ToJSON RefreshToken | |
Defined in Network.OAuth.OAuth2.Internal Methods toJSON :: RefreshToken -> Value # toEncoding :: RefreshToken -> Encoding # toJSONList :: [RefreshToken] -> Value # toEncodingList :: [RefreshToken] -> Encoding # omitField :: RefreshToken -> Bool # | |
| Show RefreshToken | |
Defined in Network.OAuth.OAuth2.Internal Methods showsPrec :: Int -> RefreshToken -> ShowS # show :: RefreshToken -> String # showList :: [RefreshToken] -> ShowS # | |
| Binary RefreshToken | |
Defined in Network.OAuth.OAuth2.Internal | |
| Eq 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 Methods getHttpManager :: Manager -> Manager # | |
Yesod
class (Yesod master, PathPiece (AuthId master), RenderMessage master FormMessage) => YesodAuth master where #
Minimal complete definition
loginDest, logoutDest, (authenticate | getAuthId), authPlugins
Methods
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
Arguments
| :: 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 #
Constructors
| AuthPlugin | |
Fields
| |
User credentials
Constructors
| Creds | |
Fields
| |
Bytestring URI types
Constructors
| Host | |
Fields
| |
Instances
| IsString Host Source # | |
Defined in URI.ByteString.Extension Methods fromString :: String -> Host # | |
| Generic Host | |
| Show Host | |
| Eq Host | |
| Ord 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.1-3Pggwbm0rGdJ4VqwbYZUJs" '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