Compare commits
2 Commits
7928aa1cb6
...
sandbox/Ma
Author | SHA1 | Date | |
---|---|---|---|
225e44d1a2 | |||
00a7e3d524 |
4
.gitignore
vendored
4
.gitignore
vendored
@ -1,6 +1,2 @@
|
||||
dist/
|
||||
config/config.dhall
|
||||
/ctags
|
||||
/TAGS
|
||||
/result*
|
||||
/backend/config
|
||||
|
@ -1,5 +0,0 @@
|
||||
# Revision history for backend
|
||||
|
||||
## 0.1.0.0 -- YYYY-mm-dd
|
||||
|
||||
* First version. Released on an unsuspecting world.
|
@ -1,30 +0,0 @@
|
||||
Copyright (c) 2018, Mats Rauhala
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials provided
|
||||
with the distribution.
|
||||
|
||||
* Neither the name of Mats Rauhala nor the names of other
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
@ -1,2 +0,0 @@
|
||||
import Distribution.Simple
|
||||
main = defaultMain
|
@ -1,76 +0,0 @@
|
||||
{-# Language DataKinds #-}
|
||||
{-# Language TypeFamilies #-}
|
||||
{-# Language TypeOperators #-}
|
||||
{-# Language NoImplicitPrelude #-}
|
||||
{-# Language MultiParamTypeClasses #-}
|
||||
{-# Language OverloadedStrings #-}
|
||||
{-# Language TemplateHaskell #-}
|
||||
{-# Language QuasiQuotes #-}
|
||||
{-# Language RecordWildCards #-}
|
||||
{-# Language DeriveGeneric #-}
|
||||
{-# Language FlexibleInstances #-}
|
||||
{-# Language TypeApplications #-}
|
||||
{-# Language DataKinds #-}
|
||||
{-# Language DuplicateRecordFields #-}
|
||||
{-# Language NamedFieldPuns #-}
|
||||
module API.Channels (API, handler, JsonChannel(..)) where
|
||||
|
||||
import ClassyPrelude
|
||||
import Control.Lens
|
||||
import Control.Monad.Catch (throwM, MonadThrow)
|
||||
import Control.Monad.Logger
|
||||
import Data.Aeson
|
||||
import Data.Generics.Product
|
||||
import Database
|
||||
import Database.Channel
|
||||
import Servant
|
||||
import Servant.Auth as SA
|
||||
import Server.Auth
|
||||
import Types
|
||||
|
||||
data JsonChannel = JsonChannel { channel :: Text
|
||||
, visibility :: Visibility }
|
||||
deriving (Show, Generic)
|
||||
data UpdateChannel = UpdateChannel { identifier :: ChannelID
|
||||
, channel :: Text
|
||||
, visibility :: Visibility }
|
||||
deriving (Show, Generic)
|
||||
|
||||
instance ToJSON JsonChannel
|
||||
instance FromJSON JsonChannel
|
||||
instance ToJSON UpdateChannel
|
||||
instance FromJSON UpdateChannel
|
||||
|
||||
type API = Auth '[SA.BasicAuth, SA.Cookie, SA.JWT] SafeUser :> BaseAPI
|
||||
|
||||
type BaseAPI = "channels" :> ReqBody '[JSON] JsonChannel :> Post '[JSON] UpdateChannel
|
||||
:<|> "channels" :> Capture "channel_id" ChannelID :> ReqBody '[JSON] UpdateChannel :> Put '[JSON] UpdateChannel
|
||||
:<|> "channels" :> Get '[JSON] [JsonChannel]
|
||||
|
||||
handler :: ServerT API AppM
|
||||
handler user = newChannelHandler user :<|> updateChannelHandler user :<|> listChannelsHandler user
|
||||
|
||||
requireChannelOwner :: AuthResult SafeUser -> ChannelID -> (SafeUser -> AppM a) -> AppM a
|
||||
requireChannelOwner auth channelId f = flip requireLoggedIn auth $ \u@SafeUser{username} -> do
|
||||
unlessM (runDB . channelExists $ channelId) $ throwM err404
|
||||
runDB (isChannelOwner channelId username) >>= \o -> if o then f u else throwM err403
|
||||
|
||||
updateChannelHandler :: AuthResult SafeUser -> ChannelID -> UpdateChannel -> AppM UpdateChannel
|
||||
updateChannelHandler auth channelId UpdateChannel{visibility} = requireChannelOwner auth channelId $ \_ -> do
|
||||
mChannel <- fmap toChannel <$> runDB (updateChannelPrivacy channelId visibility)
|
||||
maybe (throwM err403) return mChannel
|
||||
|
||||
listChannelsHandler :: AuthResult SafeUser -> AppM [JsonChannel]
|
||||
listChannelsHandler = requireLoggedIn $ \user ->
|
||||
-- I could use the super thing from generic-lens, but then I would need to
|
||||
-- use the 'channel' accessor somehow or export it
|
||||
fmap (\Channel{..} -> JsonChannel{..}) <$> runDB (userChannels (view (field @"username") user))
|
||||
|
||||
newChannelHandler :: AuthResult SafeUser -> JsonChannel -> AppM UpdateChannel
|
||||
newChannelHandler auth JsonChannel{..} = flip requireLoggedIn auth $ \user -> do
|
||||
$logInfo $ "Creating channel for user " <> pack (show user)
|
||||
mChannel <- fmap toChannel <$> runDB (insertChannel (view (field @"username") user) channel visibility)
|
||||
maybe (throwM err403{errBody="Could not create the channel"}) return mChannel
|
||||
|
||||
toChannel :: Channel -> UpdateChannel
|
||||
toChannel Channel{..} = UpdateChannel{..}
|
@ -1,128 +0,0 @@
|
||||
{-# Language TypeApplications #-}
|
||||
{-# Language DataKinds #-}
|
||||
{-# Language NamedFieldPuns #-}
|
||||
module Database.Channel
|
||||
( userChannels
|
||||
, insertChannel
|
||||
, channelExists
|
||||
, isChannelOwner
|
||||
, updateChannelPrivacy
|
||||
, attachChannel
|
||||
, Visibility(..)
|
||||
, clearChannels
|
||||
, booksChannels
|
||||
, channelBooks
|
||||
, Channel(..)
|
||||
, ChannelID(..) )
|
||||
where
|
||||
|
||||
import ClassyPrelude
|
||||
import Control.Monad.Catch (MonadMask)
|
||||
import Database
|
||||
import Database.Schema
|
||||
import Database.Selda
|
||||
import Database.Selda.Generic
|
||||
|
||||
import Control.Monad.Trans.Maybe
|
||||
|
||||
getChannel :: (MonadSelda m, MonadIO m) => ChannelID -> m (Maybe Channel)
|
||||
getChannel identifier = listToMaybe . fromRels <$> query q
|
||||
where
|
||||
q = do
|
||||
ch@(channelId :*: _) <- select (gen channels)
|
||||
restrict (channelId .== literal identifier)
|
||||
return ch
|
||||
|
||||
channelExists :: (MonadSelda m, MonadIO m) => ChannelID -> m Bool
|
||||
channelExists identifier = not . null <$> getChannel identifier
|
||||
|
||||
isChannelOwner :: (MonadSelda m, MonadIO m) => ChannelID -> Username -> m Bool
|
||||
isChannelOwner identifier username = not . null <$> query q
|
||||
where
|
||||
q = do
|
||||
userId :*: _ :*: username' :*: _ <- select (gen users)
|
||||
channelId :*: _ :*: channelOwner :*: _ <- select (gen channels)
|
||||
restrict (userId .== channelOwner)
|
||||
restrict (username' .== literal username)
|
||||
restrict (channelId .== literal identifier)
|
||||
return channelId
|
||||
|
||||
userChannels :: (MonadMask m, MonadIO m) => Username -> SeldaT m [Channel]
|
||||
userChannels username = fromRels <$> query q
|
||||
where
|
||||
q = do
|
||||
userId :*: _ :*: username' :*: _ <- select (gen users)
|
||||
channel@(_ :*: _ :*: owner :*: _) <- select (gen channels)
|
||||
restrict (owner .== userId)
|
||||
restrict (username' .== literal username)
|
||||
return channel
|
||||
|
||||
updateChannelPrivacy :: (MonadIO m, MonadSelda m) => ChannelID -> Visibility -> m (Maybe Channel)
|
||||
updateChannelPrivacy channelId visibility = do
|
||||
void $ update (gen channels) predicate (\channel -> channel `with` [pVis := literal visibility])
|
||||
getChannel channelId
|
||||
where
|
||||
predicate (channelId' :*: _) = channelId' .== literal channelId
|
||||
_ :*: _ :*: _ :*: pVis = selectors (gen channels)
|
||||
|
||||
insertChannel :: (MonadMask m, MonadIO m, MonadSelda m) => Username -> Text -> Visibility -> m (Maybe Channel)
|
||||
insertChannel username channel visibility = runMaybeT $ do
|
||||
userId <- MaybeT (listToMaybe <$> getUser)
|
||||
channelId <- toChannelId <$> MaybeT (insertUnless (gen channels) (doesNotExist userId) [ def :*: channel :*: userId :*: visibility ])
|
||||
MaybeT (listToMaybe . fromRels <$> query (q channelId))
|
||||
where
|
||||
q channelId = do
|
||||
ch@(channelId' :*: _) <- select (gen channels)
|
||||
restrict (channelId' .== literal channelId)
|
||||
return ch
|
||||
toChannelId = ChannelID . fromRowId
|
||||
doesNotExist userId (_ :*: channel' :*: userId' :*: _) = channel' .== literal channel .&& userId' .== literal userId
|
||||
getUser = query $ do
|
||||
userId :*: _ :*: user :*: _ <- select (gen users)
|
||||
restrict (user .== literal username)
|
||||
return userId
|
||||
|
||||
channelBooks :: (MonadSelda m, MonadIO m) => Username -> ChannelID -> m [Book]
|
||||
channelBooks username identifier = fromRels <$> query q
|
||||
where
|
||||
q = do
|
||||
channelId :*: bookId' <- select (gen bookChannels)
|
||||
channelId' :*: _ :*: owner :*: _ <- select (gen channels)
|
||||
userId :*: _ :*: username' :*: _ <- select (gen users)
|
||||
book@(bookId :*: _) <- select (gen books)
|
||||
restrict (username' .== literal username .&& owner .== userId)
|
||||
restrict (channelId .== literal identifier .&& channelId .== channelId')
|
||||
restrict (bookId .== bookId')
|
||||
return book
|
||||
|
||||
booksChannels :: (MonadSelda m, MonadIO m) => BookID -> m [Channel]
|
||||
booksChannels bookId = fromRels <$> query q
|
||||
where
|
||||
q = do
|
||||
channelId :*: bookId' <- select (gen bookChannels)
|
||||
ch@(channelId' :*: _) <- select (gen channels)
|
||||
restrict (channelId .== channelId')
|
||||
restrict (bookId' .== literal bookId)
|
||||
return ch
|
||||
|
||||
attachChannel :: (MonadIO m, MonadSelda m) => Username -> BookID -> Text -> m ()
|
||||
attachChannel username bookId channel = do
|
||||
mCh <- fromRels <$> query channelQ
|
||||
forM_ mCh $ \Channel{identifier} ->
|
||||
whenM (null <$> query (attachQ identifier)) $
|
||||
void $ insertGen bookChannels [BookChannel identifier bookId]
|
||||
where
|
||||
attachQ channelId = do
|
||||
(channelId' :*: bookId') <- select (gen bookChannels)
|
||||
restrict (channelId' .== literal channelId .&& bookId' .== literal bookId)
|
||||
return channelId'
|
||||
channelQ = do
|
||||
userId :*: _ :*: username' :*: _ <- select (gen users)
|
||||
ch@(_ :*: channel' :*: owner :*: _) <- select (gen channels)
|
||||
restrict (username' .== literal username)
|
||||
restrict (owner .== userId)
|
||||
restrict (channel' .== literal channel)
|
||||
return ch
|
||||
|
||||
clearChannels :: (MonadIO m, MonadSelda m) => BookID -> m Int
|
||||
clearChannels bookId = deleteFrom (gen bookChannels) (\(_ :*: bookId') -> bookId' .== literal bookId)
|
@ -1,65 +0,0 @@
|
||||
{-# Language TypeApplications #-}
|
||||
module Main where
|
||||
|
||||
import API.Books
|
||||
import qualified Data.Aeson as A
|
||||
import Data.Char (isPrint)
|
||||
import Data.GenValidity.Text ()
|
||||
import qualified Data.Text as T
|
||||
import Database.Schema
|
||||
import Prelude
|
||||
import Test.Hspec
|
||||
import Test.Validity
|
||||
|
||||
instance GenUnchecked PlainPassword
|
||||
instance GenValid PlainPassword
|
||||
instance GenInvalid PlainPassword
|
||||
instance Validity PlainPassword
|
||||
instance GenUnchecked Email
|
||||
instance GenValid Email
|
||||
instance GenInvalid Email
|
||||
instance Validity Email
|
||||
instance GenUnchecked Username
|
||||
instance GenValid Username
|
||||
instance GenInvalid Username
|
||||
instance Validity Username
|
||||
instance GenUnchecked BookID
|
||||
instance GenValid BookID
|
||||
instance GenInvalid BookID
|
||||
instance Validity BookID
|
||||
instance GenUnchecked ChannelID
|
||||
instance GenValid ChannelID
|
||||
instance GenInvalid ChannelID
|
||||
instance Validity ChannelID
|
||||
instance GenUnchecked Role
|
||||
instance GenValid Role
|
||||
instance GenInvalid Role
|
||||
instance Validity Role
|
||||
instance GenUnchecked Visibility
|
||||
instance GenValid Visibility
|
||||
instance GenInvalid Visibility
|
||||
instance Validity Visibility
|
||||
instance GenUnchecked JsonBook
|
||||
instance GenValid JsonBook
|
||||
instance GenInvalid JsonBook
|
||||
instance Validity JsonBook
|
||||
instance GenUnchecked PostBook
|
||||
instance GenValid PostBook
|
||||
instance GenInvalid PostBook
|
||||
instance Validity PostBook
|
||||
|
||||
spec :: Spec
|
||||
spec = do
|
||||
describe "JSON encoding" $ do
|
||||
it "Works for PlainPassword" $ inverseFunctionsIfSecondSucceedsOnValid (A.encode @PlainPassword) A.decode
|
||||
it "Works for Email" $ inverseFunctionsIfSecondSucceedsOnValid (A.encode @Email) A.decode
|
||||
it "Username" $ inverseFunctionsIfSecondSucceedsOnValid (A.encode @Username) A.decode
|
||||
it "Works for BookID" $ inverseFunctionsIfSecondSucceedsOnValid (A.encode @BookID) A.decode
|
||||
it "Works for ChannelID" $ inverseFunctionsIfSecondSucceedsOnValid (A.encode @ChannelID) A.decode
|
||||
it "Works for Role" $ inverseFunctionsIfSecondSucceedsOnValid (A.encode @Role) A.decode
|
||||
it "Works for Visibility" $ inverseFunctionsIfSecondSucceedsOnValid (A.encode @Visibility) A.decode
|
||||
it "Works for JsonBook" $ inverseFunctionsIfSecondSucceedsOnValid (A.encode @JsonBook) A.decode
|
||||
it "Works for PostBook" $ inverseFunctionsIfSecondSucceedsOnValid (A.encode @PostBook) A.decode
|
||||
|
||||
main :: IO ()
|
||||
main = hspec spec
|
@ -1,30 +0,0 @@
|
||||
Copyright (c) 2018, Mats Rauhala
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials provided
|
||||
with the distribution.
|
||||
|
||||
* Neither the name of Mats Rauhala nor the names of other
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
@ -1,51 +0,0 @@
|
||||
name: common
|
||||
version: 0.1.0.0
|
||||
-- synopsis:
|
||||
-- description:
|
||||
license: BSD3
|
||||
license-file: LICENSE
|
||||
author: Mats Rauhala
|
||||
maintainer: mats.rauhala@iki.fi
|
||||
-- copyright:
|
||||
category: Web
|
||||
build-type: Simple
|
||||
extra-source-files: ChangeLog.md
|
||||
cabal-version: >=1.10
|
||||
|
||||
library
|
||||
exposed-modules: Configuration
|
||||
, Data.Versioned
|
||||
-- other-extensions:
|
||||
build-depends: base >=4.10
|
||||
, classy-prelude
|
||||
, dhall
|
||||
, foreign-store
|
||||
, generic-lens
|
||||
, lens
|
||||
, mtl
|
||||
, text
|
||||
, transformers
|
||||
hs-source-dirs: src
|
||||
default-extensions: DeriveGeneric
|
||||
, NoImplicitPrelude
|
||||
, OverloadedStrings
|
||||
, RecordWildCards
|
||||
default-language: Haskell2010
|
||||
|
||||
test-suite spec
|
||||
type: exitcode-stdio-1.0
|
||||
main-is: Spec.hs
|
||||
hs-source-dirs: src
|
||||
build-depends: base >=4.10
|
||||
, classy-prelude
|
||||
, dhall
|
||||
, foreign-store
|
||||
, generic-lens
|
||||
, lens
|
||||
, mtl
|
||||
, text
|
||||
, transformers
|
||||
, validity
|
||||
, genvalidity-hspec
|
||||
, genvalidity-property
|
||||
, hspec
|
@ -1,9 +0,0 @@
|
||||
module Main where
|
||||
|
||||
import Test.Hspec
|
||||
|
||||
spec :: Spec
|
||||
spec = describe "test" $ it "verifies tests work" $ True == True
|
||||
|
||||
main :: IO ()
|
||||
main = hspec spec
|
23
default.nix
23
default.nix
@ -1,15 +1,10 @@
|
||||
{ nixpkgs, haskellPackages }:
|
||||
|
||||
(import ./project.nix nixpkgs) {
|
||||
packages = {
|
||||
common = ./common;
|
||||
backend = ./backend;
|
||||
};
|
||||
overrides = self: super: {
|
||||
generic-lens = nixpkgs.haskell.lib.dontCheck super.generic-lens;
|
||||
};
|
||||
tools = with haskellPackages; [
|
||||
ghcid
|
||||
hasktags
|
||||
];
|
||||
{ mkDerivation, base, stdenv }:
|
||||
mkDerivation {
|
||||
pname = "ebook-manager";
|
||||
version = "0.1.0.0";
|
||||
src = ./.;
|
||||
isLibrary = false;
|
||||
isExecutable = true;
|
||||
executableHaskellDepends = [ base ];
|
||||
license = stdenv.lib.licenses.bsd3;
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
-- Initial backend.cabal generated by cabal init. For further
|
||||
-- Initial ebook-manager.cabal generated by cabal init. For further
|
||||
-- documentation, see http://haskell.org/cabal/users-guide/
|
||||
|
||||
name: backend
|
||||
name: ebook-manager
|
||||
version: 0.1.0.0
|
||||
-- synopsis:
|
||||
-- description:
|
||||
@ -15,7 +15,7 @@ build-type: Simple
|
||||
extra-source-files: ChangeLog.md
|
||||
cabal-version: >=1.10
|
||||
|
||||
executable backend
|
||||
executable ebook-manager
|
||||
main-is: Main.hs
|
||||
other-modules: Devel.Main
|
||||
, API
|
||||
@ -23,6 +23,8 @@ executable backend
|
||||
, API.Catalogue
|
||||
, API.Channels
|
||||
, API.Users
|
||||
, Configuration
|
||||
, Data.Versioned
|
||||
, Database
|
||||
, Database.Book
|
||||
, Database.Channel
|
||||
@ -36,10 +38,7 @@ executable backend
|
||||
, Types
|
||||
, View
|
||||
-- other-extensions:
|
||||
build-depends: base >=4.10
|
||||
, exceptions
|
||||
, monad-control
|
||||
, common
|
||||
build-depends: base >=4.10 && <4.11
|
||||
, aeson
|
||||
, asn1-data
|
||||
, asn1-types
|
||||
@ -81,66 +80,8 @@ executable backend
|
||||
, xml-conduit
|
||||
, xml-hamlet
|
||||
hs-source-dirs: src
|
||||
default-extensions: DeriveGeneric
|
||||
, NoImplicitPrelude
|
||||
, OverloadedStrings
|
||||
, RecordWildCards
|
||||
default-language: Haskell2010
|
||||
default-extensions: DeriveGeneric
|
||||
, NoImplicitPrelude
|
||||
, OverloadedStrings
|
||||
, RecordWildCards
|
||||
|
||||
test-suite spec
|
||||
type: exitcode-stdio-1.0
|
||||
main-is: Spec.hs
|
||||
hs-source-dirs: src
|
||||
build-depends: base >=4.10
|
||||
, exceptions
|
||||
, monad-control
|
||||
, common
|
||||
, aeson
|
||||
, asn1-data
|
||||
, asn1-types
|
||||
, bytestring
|
||||
, classy-prelude
|
||||
, cryptonite
|
||||
, dhall
|
||||
, directory
|
||||
, foreign-store
|
||||
, generic-lens
|
||||
, http-api-data
|
||||
, http-media
|
||||
, jose
|
||||
, lens
|
||||
, lucid
|
||||
, memory
|
||||
, monad-logger
|
||||
, mtl
|
||||
, pandoc
|
||||
, pandoc-types
|
||||
, pem
|
||||
, process
|
||||
, resource-pool
|
||||
, selda
|
||||
, selda-postgresql
|
||||
, servant
|
||||
, servant-auth
|
||||
, servant-auth-server
|
||||
, servant-docs
|
||||
, servant-lucid
|
||||
, servant-multipart
|
||||
, servant-server
|
||||
, text
|
||||
, transformers
|
||||
, wai
|
||||
, warp
|
||||
, x509
|
||||
, x509-store
|
||||
, xml-conduit
|
||||
, xml-hamlet
|
||||
, validity
|
||||
, genvalidity-hspec
|
||||
, genvalidity-property
|
||||
, genvalidity-text
|
||||
, hspec
|
||||
default-extensions: DeriveGeneric
|
||||
, NoImplicitPrelude
|
||||
, OverloadedStrings
|
||||
, RecordWildCards
|
@ -1,7 +1,7 @@
|
||||
{
|
||||
"url": "https://github.com/nixos/nixpkgs.git",
|
||||
"rev": "e0d250e5cf6d179e1ccc775472d89718f61fcfd1",
|
||||
"rev": "83a5765b1fea2472ec9cf9d179d3efd18b45c77e",
|
||||
"date": "2018-01-08T11:52:28+01:00",
|
||||
"sha256": "1iqpjz4czcpghbv924a5h4jvfmj6c8q6sl3b1z7blz3mi740aivs",
|
||||
"sha256": "01rb61dkbzjbwnb3p8lgs03a94f4584199dlr0cwdmqzaxnp506h",
|
||||
"fetchSubmodules": true
|
||||
}
|
||||
|
39
project.nix
39
project.nix
@ -1,39 +0,0 @@
|
||||
nixpkgs:
|
||||
|
||||
let
|
||||
|
||||
inherit (nixpkgs.lib) mapAttrs mapAttrsToList escapeShellArg optionalString concatStringsSep concatMapStringsSep;
|
||||
|
||||
in
|
||||
|
||||
{ packages
|
||||
, overrides ? _ : _ : {}
|
||||
, tools ? []
|
||||
}:
|
||||
|
||||
let
|
||||
|
||||
overrides' = nixpkgs.lib.foldr nixpkgs.lib.composeExtensions (_: _: {}) [
|
||||
(self: super: mapAttrs (name: path: self.callCabal2nix name path {}) packages)
|
||||
overrides
|
||||
];
|
||||
haskellPackages = nixpkgs.haskellPackages.override { overrides = overrides'; };
|
||||
packages' = mapAttrs (name: _: haskellPackages."${name}") packages;
|
||||
mkShell = name: pkg:
|
||||
let
|
||||
n = "${name}-shell";
|
||||
deps = haskellPackages.ghcWithHoogle (pkgs: pkg.buildInputs ++ pkg.propagatedBuildInputs);
|
||||
in
|
||||
{
|
||||
name = "${n}";
|
||||
value = nixpkgs.buildEnv {
|
||||
name = "${n}";
|
||||
paths = tools;
|
||||
buildInputs = tools ++ [deps];
|
||||
};
|
||||
};
|
||||
shells = nixpkgs.lib.listToAttrs (mapAttrsToList mkShell packages');
|
||||
|
||||
in
|
||||
|
||||
packages' // shells
|
15
release.nix
15
release.nix
@ -1,15 +0,0 @@
|
||||
{ nixpkgs ? import <nixpkgs> {} }:
|
||||
|
||||
let
|
||||
|
||||
pinnedVersion = nixpkgs.lib.importJSON ./nixpkgs-version.json;
|
||||
pinnedPkgs = import (nixpkgs.fetchFromGitHub {
|
||||
owner = "NixOS";
|
||||
repo = "nixpkgs";
|
||||
inherit (pinnedVersion) rev sha256;
|
||||
}) {};
|
||||
inherit (pinnedPkgs) pkgs;
|
||||
|
||||
in
|
||||
|
||||
import ./default.nix { nixpkgs = pinnedPkgs; haskellPackages = pinnedPkgs.haskellPackages; }
|
@ -27,8 +27,8 @@ data Index = Index
|
||||
|
||||
type API = Get '[HTML] (AppView Index)
|
||||
:<|> Users.API
|
||||
:<|> "api" :> "current" :> Channels.API
|
||||
:<|> "api" :> "current" :> Books.API
|
||||
:<|> "api" :> Channels.API
|
||||
:<|> "api" :> Books.API
|
||||
:<|> "api" :> "1" :> Catalogue.VersionedAPI 1
|
||||
:<|> "api" :> "current" :> Catalogue.VersionedAPI 1
|
||||
|
@ -15,19 +15,18 @@
|
||||
{-# Language NamedFieldPuns #-}
|
||||
module API.Books where
|
||||
|
||||
import Servant hiding (contentType)
|
||||
import Types
|
||||
import ClassyPrelude
|
||||
import Control.Lens
|
||||
import Control.Monad.Catch (throwM, MonadThrow)
|
||||
import Server.Auth
|
||||
import Servant.Auth as SA
|
||||
import Data.Aeson
|
||||
import Data.Generics.Product
|
||||
import Database
|
||||
import Database.Book
|
||||
import Database.Channel
|
||||
import Database.Tag
|
||||
import Servant hiding (contentType)
|
||||
import Servant.Auth as SA
|
||||
import Server.Auth
|
||||
import Types
|
||||
import Database
|
||||
import Control.Lens
|
||||
import Data.Generics.Product
|
||||
|
||||
import Control.Monad.Trans.Maybe
|
||||
|
||||
@ -37,18 +36,18 @@ import Crypto.Hash (digestFromByteString)
|
||||
|
||||
data JsonBook = JsonBook { identifier :: BookID
|
||||
, contentType :: Text
|
||||
, title :: Text
|
||||
, title :: Maybe Text
|
||||
, description :: Maybe Text
|
||||
, channels :: [Text]
|
||||
, tags :: [Text] }
|
||||
deriving (Generic, Show, Eq)
|
||||
deriving (Generic, Show)
|
||||
|
||||
data PostBook = PostBook { contentType :: Text
|
||||
, title :: Text
|
||||
, title :: Maybe Text
|
||||
, description :: Maybe Text
|
||||
, channels :: [Text]
|
||||
, tags :: [Text] }
|
||||
deriving (Generic, Show, Eq)
|
||||
deriving (Generic, Show)
|
||||
|
||||
|
||||
instance ToJSON JsonBook
|
||||
@ -62,9 +61,7 @@ type BaseAPI = "books" :> Get '[JSON] [JsonBook]
|
||||
:<|> "books" :> ReqBody '[JSON] PostBook :> Post '[JSON] JsonBook
|
||||
:<|> "books" :> Capture "book_id" BookID :> "meta" :> ReqBody '[JSON] JsonBook :> Put '[JSON] JsonBook
|
||||
:<|> "books" :> Capture "book_id" BookID :> ReqBody '[OctetStream] ByteString :> Put '[JSON] NoContent
|
||||
:<|> GetBook
|
||||
|
||||
type GetBook = "books" :> Capture "book_id" BookID :> Get '[OctetStream] ByteString
|
||||
:<|> "books" :> Capture "book_id" BookID :> Get '[OctetStream] ByteString
|
||||
|
||||
handler :: ServerT API AppM
|
||||
handler user = listBooksHandler user
|
@ -16,17 +16,15 @@
|
||||
{-# Language ScopedTypeVariables #-}
|
||||
module API.Catalogue (VersionedAPI, handler) where
|
||||
|
||||
import qualified API.Books
|
||||
import Types
|
||||
import Servant
|
||||
import ClassyPrelude
|
||||
import Database
|
||||
import Database.Book (Book(..))
|
||||
import qualified Database.Channel as Channel
|
||||
import GHC.TypeLits
|
||||
import Servant hiding (contentType)
|
||||
import Server.Auth
|
||||
import Servant.Auth as SA
|
||||
import Servant.XML
|
||||
import Server.Auth
|
||||
import Types
|
||||
import qualified Database.Channel as Channel
|
||||
import Database
|
||||
|
||||
-- This is my first try on going to versioned apis, things might change
|
||||
-- I think my rule of thumb is that you can add new things as you want, but
|
||||
@ -98,40 +96,15 @@ instance ToNode (Catalog 1) where
|
||||
|
||||
class Monad m => VersionedCatalog m (v :: Nat) where
|
||||
getChannels :: SafeUser -> m (Catalog v)
|
||||
getBooks :: Channel.ChannelID -> SafeUser -> m (Catalog v)
|
||||
|
||||
instance VersionedCatalog AppM 1 where
|
||||
getChannels = getChannelsV1
|
||||
getBooks = getBooksV1
|
||||
|
||||
relUrl :: Link -> Rel
|
||||
relUrl x = Rel ("/api/current/" <> (pack . uriPath . linkURI $ x))
|
||||
|
||||
getBooksV1 :: Channel.ChannelID -> SafeUser -> AppM (Catalog 1)
|
||||
getBooksV1 channelID SafeUser{username} = do
|
||||
getChannels SafeUser{username} = do
|
||||
updated <- liftIO getCurrentTime
|
||||
let self = relUrl selfUrl
|
||||
start = relUrl startUrl
|
||||
selfUrl = safeLink (Proxy @(BaseAPI 1)) (Proxy @(ChannelCatalog 1)) channelID
|
||||
startUrl = safeLink (Proxy @(BaseAPI 1)) (Proxy @(RootCatalog 1))
|
||||
pagination = Pagination Nothing Nothing
|
||||
entries <- map (toEntry updated) <$> runDB (Channel.channelBooks username channelID)
|
||||
pure CatalogV1{..}
|
||||
where
|
||||
toEntry updated Book{description,title,identifier=bookId} =
|
||||
let content = fromMaybe "no content" description
|
||||
identifier = pack . show $ bookId
|
||||
link = Right (Acquisition (relUrl (safeLink (Proxy @API.Books.BaseAPI) (Proxy @API.Books.GetBook) bookId)))
|
||||
in EntryV1{..}
|
||||
|
||||
getChannelsV1 :: SafeUser -> AppM (Catalog 1)
|
||||
getChannelsV1 SafeUser{username} = do
|
||||
updated <- liftIO getCurrentTime
|
||||
let self = relUrl selfUrl
|
||||
let self = Rel ("/api/current/" <> selfUrl)
|
||||
-- I'm not sure if this safe link approach is really useable with this
|
||||
-- api hierarchy since I can't access the topmost api from here. Also
|
||||
-- authentication would bring a little bit of extra effort as well
|
||||
selfUrl = safeLink (Proxy @(BaseAPI 1)) (Proxy @(RootCatalog 1))
|
||||
selfUrl = pack . uriPath . linkURI $ safeLink (Proxy @(BaseAPI 1)) (Proxy @(RootCatalog 1))
|
||||
start = self
|
||||
pagination = Pagination Nothing Nothing
|
||||
entries <- map (fromChannel updated) <$> runDB (Channel.userChannels username)
|
||||
@ -139,16 +112,14 @@ getChannelsV1 SafeUser{username} = do
|
||||
where
|
||||
fromChannel :: UTCTime -> Channel.Channel -> Entry 1
|
||||
fromChannel updated Channel.Channel{..} =
|
||||
let url = safeLink (Proxy @(BaseAPI 1)) (Proxy @(ChannelCatalog 1)) identifier
|
||||
self = relUrl url
|
||||
let url = pack . uriPath . linkURI $ safeLink (Proxy @(BaseAPI 1)) (Proxy @(ChannelCatalog 1)) identifier
|
||||
self = Rel ("/api/current/" <> url)
|
||||
in EntryV1 channel channel updated channel (Left $ SubSection self)
|
||||
|
||||
type VersionedAPI (v :: Nat) = Auth '[SA.BasicAuth, SA.JWT] SafeUser :> BaseAPI v
|
||||
|
||||
type CatalogContent = '[XML, OPDS]
|
||||
|
||||
type RootCatalog (v :: Nat) = "catalog" :> Get CatalogContent (Catalog v)
|
||||
type ChannelCatalog (v :: Nat) = "catalog" :> "channel" :> Capture "channel_id" Channel.ChannelID :> Get CatalogContent (Catalog v)
|
||||
type RootCatalog (v :: Nat) = "catalog" :> Get '[XML] (Catalog v)
|
||||
type ChannelCatalog (v :: Nat) = "catalog" :> "channel" :> Capture "channel_id" Channel.ChannelID :> Get '[XML] (Catalog v)
|
||||
type BaseAPI (v :: Nat) = RootCatalog v
|
||||
:<|> ChannelCatalog v
|
||||
|
||||
@ -156,8 +127,6 @@ handler :: forall v. VersionedCatalog AppM v => ServerT (VersionedAPI v) AppM
|
||||
handler auth = catalogRoot :<|> catalogChannels
|
||||
where
|
||||
catalogChannels :: Channel.ChannelID -> AppM (Catalog v)
|
||||
-- Channel specific catalog returns tags inside the catalog
|
||||
catalogChannels identifier = flip requireLoggedIn auth (getBooks identifier)
|
||||
catalogChannels _ = throwM err403{errBody="Not implemented"}
|
||||
catalogRoot :: AppM (Catalog v)
|
||||
-- catalog root returns channels
|
||||
catalogRoot = flip requireLoggedIn auth getChannels
|
53
src/API/Channels.hs
Normal file
53
src/API/Channels.hs
Normal file
@ -0,0 +1,53 @@
|
||||
{-# Language DataKinds #-}
|
||||
{-# Language TypeFamilies #-}
|
||||
{-# Language TypeOperators #-}
|
||||
{-# Language NoImplicitPrelude #-}
|
||||
{-# Language MultiParamTypeClasses #-}
|
||||
{-# Language OverloadedStrings #-}
|
||||
{-# Language TemplateHaskell #-}
|
||||
{-# Language QuasiQuotes #-}
|
||||
{-# Language RecordWildCards #-}
|
||||
{-# Language DeriveGeneric #-}
|
||||
{-# Language FlexibleInstances #-}
|
||||
{-# Language TypeApplications #-}
|
||||
{-# Language DataKinds #-}
|
||||
module API.Channels (API, handler, JsonChannel(..)) where
|
||||
|
||||
import Servant
|
||||
import Types
|
||||
import ClassyPrelude
|
||||
import Server.Auth
|
||||
import Servant.Auth as SA
|
||||
import Control.Monad.Logger
|
||||
import Database
|
||||
import Database.Channel
|
||||
import Data.Aeson
|
||||
import Control.Lens
|
||||
import Data.Generics.Product
|
||||
|
||||
data JsonChannel = JsonChannel { channel :: Text
|
||||
, visibility :: Visibility }
|
||||
deriving (Show, Generic)
|
||||
|
||||
instance ToJSON JsonChannel
|
||||
instance FromJSON JsonChannel
|
||||
|
||||
type API = Auth '[SA.BasicAuth, SA.Cookie, SA.JWT] SafeUser :> BaseAPI
|
||||
|
||||
type BaseAPI = "channels" :> ReqBody '[JSON] JsonChannel :> Post '[JSON] JsonChannel
|
||||
:<|> "channels" :> Get '[JSON] [JsonChannel]
|
||||
|
||||
handler :: ServerT API AppM
|
||||
handler user = newChannelHandler user :<|> listChannelsHandler user
|
||||
|
||||
listChannelsHandler :: AuthResult SafeUser -> AppM [JsonChannel]
|
||||
listChannelsHandler = requireLoggedIn $ \user ->
|
||||
-- I could use the super thing from generic-lens, but then I would need to
|
||||
-- use the 'channel' accessor somehow or export it
|
||||
fmap (\Channel{..} -> JsonChannel{..}) <$> runDB (userChannels (view (field @"username") user))
|
||||
|
||||
newChannelHandler :: AuthResult SafeUser -> JsonChannel -> AppM JsonChannel
|
||||
newChannelHandler auth ch@JsonChannel{..} = flip requireLoggedIn auth $ \user -> do
|
||||
$logInfo $ "Creating channel for user " <> pack (show user)
|
||||
runDB (insertChannel (view (field @"username") user) channel visibility)
|
||||
return ch
|
@ -7,18 +7,17 @@
|
||||
{-# Language TypeApplications #-}
|
||||
module API.Users where
|
||||
|
||||
import ClassyPrelude
|
||||
import Control.Monad.Catch (throwM, MonadThrow)
|
||||
import Data.Aeson
|
||||
import Database (runDB)
|
||||
import Database.Schema
|
||||
import Database.User
|
||||
import Servant
|
||||
import Servant.Auth as SA
|
||||
import Servant.Auth.Server as SAS
|
||||
import Server.Auth
|
||||
import ClassyPrelude
|
||||
import Types
|
||||
import Data.Aeson
|
||||
import Web.FormUrlEncoded
|
||||
import Database (runDB)
|
||||
import Database.User
|
||||
import Database.Schema
|
||||
import Server.Auth
|
||||
import Servant.Auth.Server as SAS
|
||||
import Servant.Auth as SA
|
||||
|
||||
|
||||
data RegisterForm = RegisterForm { username :: Username
|
@ -12,9 +12,7 @@ data Pg = Pg { username :: Text
|
||||
, database :: Text }
|
||||
deriving (Show, Generic)
|
||||
|
||||
data Store = Filestore { path :: Text }
|
||||
| IPFS { common :: Text }
|
||||
deriving (Show, Generic)
|
||||
newtype Store = Store { path :: Text } deriving (Show, Generic)
|
||||
|
||||
data Config = Config { database :: Pg
|
||||
, store :: Store }
|
@ -15,17 +15,15 @@ module Database
|
||||
, SeldaT )
|
||||
where
|
||||
|
||||
import ClassyPrelude
|
||||
import Control.Lens (view)
|
||||
import Control.Monad.Catch (MonadMask)
|
||||
import Control.Monad.Trans.Control (MonadBaseControl)
|
||||
import Data.Generics.Product
|
||||
import Control.Lens (view)
|
||||
import Data.Pool (Pool, withResource)
|
||||
import Database.Selda (query, select, transaction)
|
||||
import Database.Selda.Backend (SeldaConnection, runSeldaT, SeldaT)
|
||||
import Database.Selda (query, select, transaction)
|
||||
import Database.Selda.Generic (gen, fromRel, fromRels, toRel)
|
||||
import ClassyPrelude
|
||||
|
||||
type DBLike r m = (MonadBaseControl IO m, MonadIO m, MonadReader r m, HasField "database" r r (Pool SeldaConnection) (Pool SeldaConnection), MonadMask m)
|
||||
type DBLike r m = (MonadIO m, MonadReader r m, MonadBaseControl IO m, MonadMask m, HasField' "database" r (Pool SeldaConnection))
|
||||
|
||||
runDB :: DBLike r m => SeldaT m a -> m a
|
||||
runDB q = do
|
@ -18,17 +18,18 @@ module Database.Book
|
||||
, BookID) where
|
||||
|
||||
import ClassyPrelude
|
||||
import Control.Lens (view)
|
||||
import Control.Monad.Catch (MonadCatch)
|
||||
import Data.Generics.Product
|
||||
import Database
|
||||
import Database.Channel (booksChannels, attachChannel, clearChannels)
|
||||
import Database.Schema (books, users, Username, Book(..), BookID(..), UserID, HashDigest(..))
|
||||
import Database
|
||||
import Database.Selda
|
||||
import Database.Selda.Generic
|
||||
import Database.Tag (booksTags, attachTag, clearTags)
|
||||
|
||||
usersBooks :: (MonadSelda m, MonadIO m) => Username -> m [Book]
|
||||
import Control.Lens (view)
|
||||
import Data.Generics.Product
|
||||
|
||||
import Database.Tag (booksTags, attachTag, clearTags)
|
||||
import Database.Channel (booksChannels, attachChannel, clearChannels)
|
||||
|
||||
usersBooks :: (MonadSelda m, MonadMask m, MonadIO m) => Username -> m [Book]
|
||||
usersBooks username = fromRels <$> query q
|
||||
where
|
||||
q = do
|
||||
@ -40,7 +41,7 @@ usersBooks username = fromRels <$> query q
|
||||
return book
|
||||
|
||||
|
||||
getBook :: (MonadSelda m, MonadIO m) => BookID -> Username -> m (Maybe Book)
|
||||
getBook :: (MonadSelda m, MonadMask m, MonadIO m) => BookID -> Username -> m (Maybe Book)
|
||||
getBook identifier owner = listToMaybe . fromRels <$> query q
|
||||
where
|
||||
q = do
|
||||
@ -50,12 +51,12 @@ getBook identifier owner = listToMaybe . fromRels <$> query q
|
||||
return book
|
||||
|
||||
data InsertBook = InsertBook { contentType :: Text
|
||||
, title :: Text
|
||||
, title :: Maybe Text
|
||||
, description :: Maybe Text
|
||||
, owner :: Username }
|
||||
|
||||
-- Always inserts
|
||||
insertBook :: (MonadSelda m, MonadIO m) => InsertBook -> m (Maybe BookID)
|
||||
insertBook :: (MonadSelda m, MonadMask m, MonadIO m) => InsertBook -> m (Maybe BookID)
|
||||
insertBook InsertBook{..} = do
|
||||
mUserId <- query $ do
|
||||
userId :*: _ :*: username' :*: _ <- select (gen users)
|
||||
@ -67,14 +68,14 @@ insertBook InsertBook{..} = do
|
||||
|
||||
data UpdateBook = UpdateBook { identifier :: BookID
|
||||
, contentType :: Text
|
||||
, title :: Text
|
||||
, title :: Maybe Text
|
||||
, description :: Maybe Text
|
||||
, owner :: Username
|
||||
, tags :: [Text]
|
||||
, channels :: [Text] }
|
||||
deriving (Show, Generic)
|
||||
|
||||
bookExists :: (MonadSelda m, MonadIO m) => BookID -> m Bool
|
||||
bookExists :: (MonadSelda m, MonadMask m, MonadIO m) => BookID -> m Bool
|
||||
bookExists identifier = not . null <$> query q
|
||||
where
|
||||
q = do
|
||||
@ -82,7 +83,7 @@ bookExists identifier = not . null <$> query q
|
||||
restrict (bookId .== literal identifier)
|
||||
return bookId
|
||||
|
||||
isBookOwner :: (MonadSelda m, MonadIO m) => BookID -> Username -> m Bool
|
||||
isBookOwner :: (MonadSelda m, MonadIO m, MonadThrow m) => BookID -> Username -> m Bool
|
||||
isBookOwner identifier username = not . null <$> query (bookOwner' identifier username)
|
||||
|
||||
bookOwner' :: BookID -> Username -> Query s (Col s UserID :*: Col s BookID)
|
||||
@ -94,7 +95,7 @@ bookOwner' identifier username = do
|
||||
restrict (bookId .== literal identifier)
|
||||
return (userId :*: bookId)
|
||||
|
||||
updateBook :: (MonadCatch m, MonadSelda m, MonadIO m) => UpdateBook -> m (Maybe UpdateBook)
|
||||
updateBook :: (MonadSelda m, MonadMask m, MonadIO m) => UpdateBook -> m (Maybe UpdateBook)
|
||||
updateBook UpdateBook{..} = do
|
||||
clearTags identifier >> connectTags
|
||||
clearChannels identifier >> connectChannels
|
||||
@ -113,7 +114,7 @@ updateBook UpdateBook{..} = do
|
||||
predicate (bookId :*: _) = bookId .== literal identifier
|
||||
|
||||
|
||||
getUpdateBook :: (MonadIO m, MonadSelda m) => BookID -> Username -> m (Maybe UpdateBook)
|
||||
getUpdateBook :: (MonadMask m, MonadIO m, MonadSelda m) => BookID -> Username -> m (Maybe UpdateBook)
|
||||
getUpdateBook bookId username = do
|
||||
mBook <- getBook bookId username
|
||||
forM mBook $ \Book{..} -> do
|
||||
@ -121,7 +122,7 @@ getUpdateBook bookId username = do
|
||||
tags <- map (view (field @"tag")) <$> booksTags bookId
|
||||
return UpdateBook{owner=username,..}
|
||||
|
||||
setContent :: (MonadSelda m, MonadIO m) => BookID -> Username -> HashDigest -> m ()
|
||||
setContent :: (MonadSelda m, MonadMask m, MonadIO m) => BookID -> Username -> HashDigest -> m ()
|
||||
setContent identifier owner digest = do
|
||||
mOwner <- query (bookOwner' identifier owner)
|
||||
void $ forM (listToMaybe mOwner) $ \_ ->
|
73
src/Database/Channel.hs
Normal file
73
src/Database/Channel.hs
Normal file
@ -0,0 +1,73 @@
|
||||
{-# Language TypeApplications #-}
|
||||
{-# Language DataKinds #-}
|
||||
{-# Language NamedFieldPuns #-}
|
||||
module Database.Channel
|
||||
( userChannels
|
||||
, insertChannel
|
||||
, attachChannel
|
||||
, Visibility(..)
|
||||
, clearChannels
|
||||
, booksChannels
|
||||
, Channel(..)
|
||||
, ChannelID )
|
||||
where
|
||||
|
||||
import ClassyPrelude
|
||||
import Database.Schema
|
||||
import Database
|
||||
import Database.Selda
|
||||
import Database.Selda.Generic
|
||||
|
||||
userChannels :: (MonadMask m, MonadIO m) => Username -> SeldaT m [Channel]
|
||||
userChannels username = fromRels <$> query q
|
||||
where
|
||||
q = do
|
||||
userId :*: _ :*: username' :*: _ <- select (gen users)
|
||||
channel@(_ :*: _ :*: owner :*: _) <- select (gen channels)
|
||||
restrict (owner .== userId)
|
||||
restrict (username' .== literal username)
|
||||
return channel
|
||||
|
||||
insertChannel :: (MonadMask m, MonadIO m) => Username -> Text -> Visibility -> SeldaT m ()
|
||||
insertChannel username channel visibility = do
|
||||
mUserId <- listToMaybe <$> getUser
|
||||
void $ forM mUserId $ \userId ->
|
||||
insertUnless (gen channels) (doesNotExist userId) [ def :*: channel :*: userId :*: visibility ]
|
||||
where
|
||||
doesNotExist userId (_ :*: channel' :*: userId' :*: _) = channel' .== literal channel .&& userId' .== literal userId
|
||||
getUser = query $ do
|
||||
userId :*: _ :*: user :*: _ <- select (gen users)
|
||||
restrict (user .== literal username)
|
||||
return userId
|
||||
|
||||
booksChannels :: (MonadSelda m, MonadMask m, MonadIO m) => BookID -> m [Channel]
|
||||
booksChannels bookId = fromRels <$> query q
|
||||
where
|
||||
q = do
|
||||
channelId :*: bookId' <- select (gen bookChannels)
|
||||
ch@(channelId' :*: _) <- select (gen channels)
|
||||
restrict (channelId .== channelId')
|
||||
restrict (bookId' .== literal bookId)
|
||||
return ch
|
||||
|
||||
attachChannel :: (MonadMask m, MonadIO m, MonadSelda m) => Username -> BookID -> Text -> m ()
|
||||
attachChannel username bookId channel = do
|
||||
mCh <- fromRels <$> query channelQ
|
||||
forM_ mCh $ \Channel{identifier} ->
|
||||
whenM (null <$> query (attachQ identifier)) $
|
||||
void $ insertGen bookChannels [BookChannel identifier bookId]
|
||||
where
|
||||
attachQ channelId = do
|
||||
(channelId' :*: bookId') <- select (gen bookChannels)
|
||||
restrict (channelId' .== literal channelId .&& bookId' .== literal bookId)
|
||||
return channelId'
|
||||
channelQ = do
|
||||
userId :*: _ :*: username' :*: _ <- select (gen users)
|
||||
ch@(_ :*: channel' :*: owner :*: _) <- select (gen channels)
|
||||
restrict (username' .== literal username)
|
||||
restrict (owner .== userId)
|
||||
restrict (channel' .== literal channel)
|
||||
return ch
|
||||
|
||||
clearChannels :: (MonadMask m, MonadIO m, MonadSelda m) => BookID -> m Int
|
||||
clearChannels bookId = deleteFrom (gen bookChannels) (\(_ :*: bookId') -> bookId' .== literal bookId)
|
@ -14,13 +14,13 @@ import Data.Aeson
|
||||
import Web.HttpApiData
|
||||
|
||||
-- | User type
|
||||
newtype PlainPassword = PlainPassword Text deriving (Show, ToJSON, FromJSON, ToHttpApiData, FromHttpApiData, Eq, Generic)
|
||||
newtype PlainPassword = PlainPassword Text deriving (Show, ToJSON, FromJSON, ToHttpApiData, FromHttpApiData, Eq)
|
||||
newtype HashedPassword = HashedPassword {unHashed :: ByteString}
|
||||
data NoPassword = NoPassword
|
||||
|
||||
newtype Email = Email { unEmail :: Text } deriving (Show, ToJSON, FromJSON, ToHttpApiData, FromHttpApiData, Generic, Eq)
|
||||
newtype Email = Email { unEmail :: Text } deriving (Show, ToJSON, FromJSON, ToHttpApiData, FromHttpApiData)
|
||||
|
||||
newtype Username = Username { unUsername :: Text } deriving (Show, ToJSON, FromJSON, ToHttpApiData, FromHttpApiData, Eq, Generic)
|
||||
newtype Username = Username { unUsername :: Text } deriving (Show, ToJSON, FromJSON, ToHttpApiData, FromHttpApiData)
|
||||
|
||||
instance SqlType HashedPassword where
|
||||
mkLit = LCustom . LBlob . unHashed
|
||||
@ -42,9 +42,9 @@ instance SqlType Username where
|
||||
|
||||
newtype UserID = UserID {unUserID :: Int} deriving (Show)
|
||||
|
||||
newtype BookID = BookID {unBookID :: Int} deriving (Show, ToJSON, FromJSON, FromHttpApiData, Eq, Ord, ToHttpApiData, Generic)
|
||||
newtype BookID = BookID {unBookID :: Int} deriving (Show, ToJSON, FromJSON, FromHttpApiData, Eq, Ord)
|
||||
|
||||
newtype ChannelID = ChannelID {unChannelID :: Int} deriving (Show, ToHttpApiData, FromHttpApiData, ToJSON, FromJSON, Eq, Generic)
|
||||
newtype ChannelID = ChannelID {unChannelID :: Int} deriving (Show, ToHttpApiData, FromHttpApiData)
|
||||
|
||||
newtype TagID = TagID {unTagID :: Int} deriving (Show)
|
||||
|
||||
@ -77,7 +77,7 @@ data User pass = User { identifier :: UserID
|
||||
, password :: pass }
|
||||
deriving (Show, Generic)
|
||||
|
||||
data Role = UserRole | AdminRole deriving (Show, Read, Enum, Bounded, Typeable, Generic, Eq)
|
||||
data Role = UserRole | AdminRole deriving (Show, Read, Enum, Bounded, Typeable, Generic)
|
||||
|
||||
instance ToJSON Role
|
||||
instance FromJSON Role
|
||||
@ -101,7 +101,7 @@ newtype HashDigest = HashDigest { unHex :: ByteString } deriving Show
|
||||
data Book = Book { identifier :: BookID
|
||||
, contentHash :: Maybe HashDigest
|
||||
, contentType :: Text
|
||||
, title :: Text
|
||||
, title :: Maybe Text
|
||||
, description :: Maybe Text
|
||||
, owner :: UserID }
|
||||
deriving (Show, Generic)
|
||||
@ -125,7 +125,7 @@ data Tag = Tag { identifier :: TagID
|
||||
deriving (Show, Generic)
|
||||
|
||||
data Visibility = Public | Private | Followers
|
||||
deriving (Show, Read, Generic, Eq)
|
||||
deriving (Show, Read, Generic)
|
||||
|
||||
instance ToJSON Visibility
|
||||
instance FromJSON Visibility
|
@ -12,14 +12,13 @@ module Database.Tag
|
||||
, Tag(..) ) where
|
||||
|
||||
import ClassyPrelude
|
||||
import Control.Monad.Catch (MonadCatch)
|
||||
import Control.Monad.Trans.Maybe
|
||||
import Database
|
||||
import Database.Schema
|
||||
import Database
|
||||
import Database.Selda
|
||||
import Database.Selda.Generic
|
||||
import Control.Monad.Trans.Maybe
|
||||
|
||||
upsertTag :: (MonadCatch m, MonadIO m, MonadSelda m) => Username -> Text -> m (Maybe Tag)
|
||||
upsertTag :: (MonadMask m, MonadIO m, MonadSelda m) => Username -> Text -> m (Maybe Tag)
|
||||
upsertTag username tag = runMaybeT $ do
|
||||
userId <- MaybeT (listToMaybe <$> query userQ)
|
||||
void $ lift $ upsert (gen tags) (predicate userId) id [toRel (Tag def tag userId)]
|
||||
@ -35,7 +34,7 @@ upsertTag username tag = runMaybeT $ do
|
||||
restrict (username' .== literal username)
|
||||
return userId
|
||||
|
||||
booksTags :: (MonadIO m, MonadSelda m) => BookID -> m [Tag]
|
||||
booksTags :: (MonadMask m, MonadIO m, MonadSelda m) => BookID -> m [Tag]
|
||||
booksTags bookId = fromRels <$> query q
|
||||
where
|
||||
q = do
|
||||
@ -45,7 +44,7 @@ booksTags bookId = fromRels <$> query q
|
||||
restrict (bookId' .== literal bookId)
|
||||
return tag
|
||||
|
||||
attachTag :: (MonadCatch m, MonadIO m, MonadSelda m) => Username -> BookID -> Text -> m ()
|
||||
attachTag :: (MonadMask m, MonadIO m, MonadSelda m) => Username -> BookID -> Text -> m ()
|
||||
attachTag username bookId tag = do
|
||||
maybeT <- upsertTag username tag
|
||||
forM_ maybeT $ \Tag{identifier} -> do
|
||||
@ -57,6 +56,6 @@ attachTag username bookId tag = do
|
||||
restrict (tagId' .== literal tagId .&& bookId' .== literal bookId)
|
||||
return tagId'
|
||||
|
||||
clearTags :: (MonadIO m, MonadSelda m) => BookID -> m Int
|
||||
clearTags :: (MonadMask m, MonadIO m, MonadSelda m) => BookID -> m Int
|
||||
clearTags bookId = deleteFrom (gen bookTags) (\(_ :*: bookId') -> bookId' .== literal bookId)
|
||||
|
@ -5,21 +5,20 @@
|
||||
module Database.User where
|
||||
|
||||
import ClassyPrelude
|
||||
import Control.Lens (view, over, _Just)
|
||||
import Control.Monad (mfilter)
|
||||
import Control.Monad.Catch (MonadMask)
|
||||
import Control.Monad.Logger
|
||||
import Crypto.KDF.BCrypt
|
||||
import Crypto.Random.Types (MonadRandom)
|
||||
import Data.Generics.Product
|
||||
import Database
|
||||
import Database.Schema
|
||||
import Database.Selda
|
||||
import Control.Lens (view, over, _Just)
|
||||
import Data.Generics.Product
|
||||
import Crypto.KDF.BCrypt
|
||||
import Crypto.Random.Types (MonadRandom)
|
||||
import Control.Monad.Logger
|
||||
import Control.Monad (mfilter)
|
||||
|
||||
data UserExistsError = UserExistsError
|
||||
|
||||
|
||||
insertUser :: (MonadMask m, MonadLogger m, MonadIO m, MonadRandom m) => Username -> Email -> PlainPassword -> SeldaT m (Either UserExistsError (User NoPassword))
|
||||
insertUser :: (MonadLogger m, MonadIO m, MonadMask m, MonadRandom m) => Username -> Email -> PlainPassword -> SeldaT m (Either UserExistsError (User NoPassword))
|
||||
insertUser username email (PlainPassword password) =
|
||||
getUser' username >>= maybe insert' (const (return $ Left UserExistsError))
|
||||
where
|
@ -5,7 +5,6 @@
|
||||
{-# Language FlexibleContexts #-}
|
||||
{-# Language TypeSynonymInstances #-}
|
||||
{-# Language FlexibleInstances #-}
|
||||
{-# Language ScopedTypeVariables #-}
|
||||
module Datastore where
|
||||
|
||||
import ClassyPrelude
|
||||
@ -29,26 +28,26 @@ instance MonadDS AppM where
|
||||
get = getLocal
|
||||
|
||||
putLocal :: ( MonadIO m
|
||||
, HasField "config" r r config config
|
||||
, HasField "store" config config store store
|
||||
, HasType Text store
|
||||
, HasField' "config" r config
|
||||
, HasField' "store" config store
|
||||
, HasField' "path" store Text
|
||||
, MonadReader r m)
|
||||
=> ByteString -> m (Digest SHA256)
|
||||
putLocal bs = do
|
||||
store :: FilePath <- unpack <$> view (field @"config" . field @"store" . typed @Text)
|
||||
store <- unpack <$> view (field @"config" . field @"store" . field @"path")
|
||||
liftIO $ createDirectoryIfMissing True store
|
||||
let key = hashWith SHA256 bs
|
||||
writeFile (store </> show key) bs
|
||||
return key
|
||||
|
||||
getLocal :: ( MonadIO m
|
||||
, HasField "config" r r config config
|
||||
, HasField "store" config config store store
|
||||
, HasType Text store
|
||||
, HasField' "config" r config
|
||||
, HasField' "store" config store
|
||||
, HasField' "path" store Text
|
||||
, MonadReader r m)
|
||||
=> Digest SHA256 -> m (Maybe ByteString)
|
||||
getLocal key = do
|
||||
store <- unpack <$> view (field @"config" . field @"store" . typed @Text)
|
||||
store <- unpack <$> view (field @"config" . field @"store" . field @"path")
|
||||
liftIO $ createDirectoryIfMissing True store
|
||||
let file = store </> show key
|
||||
exists <- liftIO $ doesFileExist file
|
@ -3,18 +3,19 @@
|
||||
{-# Language FlexibleContexts #-}
|
||||
module Devel.Main where
|
||||
|
||||
import Prelude
|
||||
import Control.Monad.Trans.Reader (runReaderT)
|
||||
import Main (withApp, defaultMain)
|
||||
import Control.Concurrent
|
||||
import Control.Monad (void)
|
||||
import Control.Monad.Trans.Reader (runReaderT)
|
||||
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
|
||||
import Database
|
||||
import Database.Schema
|
||||
import Database.Selda (tryCreateTable)
|
||||
import Dhall (input, auto)
|
||||
import Foreign.Store (Store(..), lookupStore, readStore, storeAction, withStore)
|
||||
import GHC.Word (Word32)
|
||||
import Main (withApp, defaultMain)
|
||||
import Prelude
|
||||
import Dhall (input, auto)
|
||||
|
||||
import Database.Schema
|
||||
import Database.Selda (tryCreateTable)
|
||||
import Database
|
||||
|
||||
update :: IO ()
|
||||
update = do
|
||||
@ -36,7 +37,7 @@ update = do
|
||||
|
||||
develMain :: IO ()
|
||||
develMain = do
|
||||
conf <- input auto "../config/devel.dhall"
|
||||
conf <- input auto "./config/devel.dhall"
|
||||
withApp conf $ \app -> do
|
||||
void $ runReaderT (runDB migrate) app
|
||||
defaultMain app
|
@ -25,7 +25,6 @@ withApp :: Config -> (App -> IO ()) -> IO ()
|
||||
withApp config f = do
|
||||
let pgHost = view (field @"database" . field @"host") config
|
||||
pgPort = 5432
|
||||
pgSchema = Nothing
|
||||
pgDatabase = view (field @"database" . field @"database") config
|
||||
pgUsername = Just (view (field @"database" . field @"username") config)
|
||||
pgPassword = Just (view (field @"database" . field @"password") config)
|
@ -1,11 +1,9 @@
|
||||
{-# Language OverloadedStrings #-}
|
||||
{-# Language FlexibleInstances #-}
|
||||
{-# Language MultiParamTypeClasses #-}
|
||||
{-# Language TypeApplications #-}
|
||||
module Servant.XML
|
||||
( ToNode(..)
|
||||
, XML
|
||||
, OPDS
|
||||
, Text.Hamlet.XML.xml
|
||||
, iso8601 )
|
||||
where
|
||||
@ -18,22 +16,14 @@ import Network.HTTP.Media.MediaType
|
||||
|
||||
data XML
|
||||
|
||||
data OPDS
|
||||
|
||||
instance (ToNode a) => MimeRender XML a where
|
||||
mimeRender _ a =
|
||||
let [NodeElement root] = toNode a
|
||||
in renderLBS def (Document (Prologue [] Nothing []) root [])
|
||||
|
||||
instance (ToNode a) => MimeRender OPDS a where
|
||||
mimeRender _ a = mimeRender (Proxy @XML) a
|
||||
|
||||
instance Accept XML where
|
||||
contentType _ = "application" // "xml" /: ("charset", "utf-8")
|
||||
|
||||
instance Accept OPDS where
|
||||
contentType _ = "application" // "atom+xml" /: ("charset", "utf-8") /: ("profile", "opds-catalog")
|
||||
|
||||
iso8601 :: UTCTime -> Text
|
||||
iso8601 = pack . formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%SZ"
|
||||
|
@ -10,7 +10,6 @@
|
||||
{-# Language DeriveGeneric #-}
|
||||
{-# Language FlexibleInstances #-}
|
||||
{-# Language TypeApplications #-}
|
||||
{-# Language ScopedTypeVariables #-}
|
||||
module Server where
|
||||
|
||||
import qualified API as API
|
||||
@ -23,21 +22,19 @@ import Control.Monad.Except
|
||||
import Servant.Auth.Server as SAS
|
||||
import Control.Lens
|
||||
import Data.Generics.Product
|
||||
import Server.Auth (SafeUser)
|
||||
|
||||
type API = API.API :<|> "static" :> Raw
|
||||
|
||||
type Ctx = '[BasicAuthData -> IO (AuthResult SafeUser), CookieSettings, JWTSettings]
|
||||
|
||||
server :: App -> Application
|
||||
server app = serveWithContext api cfg (hoistServerWithContext (Proxy @ API.API) (Proxy @ Ctx) server' API.handler :<|> serveDirectoryFileServer "static")
|
||||
server app = serveWithContext api cfg (enter server' API.handler :<|> serveDirectoryFileServer "static")
|
||||
where
|
||||
myKey = view (field @"jwk") app
|
||||
jwtCfg = defaultJWTSettings myKey
|
||||
authCfg = authCheck app
|
||||
cookieSettings = SAS.defaultCookieSettings{cookieIsSecure=SAS.NotSecure}
|
||||
cfg = jwtCfg :. cookieSettings :. authCfg :. EmptyContext
|
||||
server' :: AppM a -> Servant.Handler a
|
||||
server' = Handler . ExceptT . try . (`runReaderT` app) . (runFileLoggingT "logs/server.log")
|
||||
server' :: AppM :~> Servant.Handler
|
||||
server' = NT (Handler . ExceptT . try . (`runReaderT` app) . (runFileLoggingT "logs/server.log"))
|
||||
api :: Proxy API
|
||||
api = Proxy
|
@ -14,17 +14,16 @@ module Server.Auth
|
||||
where
|
||||
|
||||
import ClassyPrelude
|
||||
import Control.Lens (view)
|
||||
import Control.Monad.Logger
|
||||
import Control.Monad.Catch (throwM, MonadThrow)
|
||||
import Servant.Auth.Server as SAS
|
||||
import Data.Aeson
|
||||
import Data.Generics.Product
|
||||
import Database
|
||||
import Database.Schema
|
||||
import Database.User
|
||||
import Servant (err401)
|
||||
import Servant.Auth.Server as SAS
|
||||
import Database
|
||||
import Types
|
||||
import Control.Lens (view)
|
||||
import Data.Generics.Product
|
||||
import Servant (err401)
|
||||
import Control.Monad.Logger
|
||||
|
||||
-- generic-lens can convert similar types to this
|
||||
-- I'm trying out servant-auth-server which uses a jwt style login. IIRC anyone
|
||||
@ -54,6 +53,6 @@ authCheck app (BasicAuthData username password) = flip runReaderT app $
|
||||
password' = PlainPassword $ decodeUtf8 password
|
||||
authenticated = SAS.Authenticated . view (super @SafeUser)
|
||||
|
||||
requireLoggedIn :: (MonadThrow m, MonadLogger m, Monad m) => (SafeUser -> m a) -> AuthResult SafeUser -> m a
|
||||
requireLoggedIn :: (MonadLogger m, MonadThrow m, Monad m) => (SafeUser -> m a) -> AuthResult SafeUser -> m a
|
||||
requireLoggedIn f (Authenticated user) = f user
|
||||
requireLoggedIn _ u = $logError (pack (show u)) >> throwM err401
|
Reference in New Issue
Block a user