-
Notifications
You must be signed in to change notification settings - Fork 38
/
PostgresqlSimple.hs
355 lines (315 loc) · 12.9 KB
/
PostgresqlSimple.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-|
This module allows you to use the auth snaplet with your user database stored
in a PostgreSQL database. When you run your application with this snaplet, a
config file will be copied into the the @snaplets/postgresql-auth@ directory.
This file contains all of the configurable options for the snaplet and allows
you to change them without recompiling your application.
To use this snaplet in your application enable the session, postgres, and auth
snaplets as follows:
> data App = App
> { ... -- your own application state here
> , _sess :: Snaplet SessionManager
> , _db :: Snaplet Postgres
> , _auth :: Snaplet (AuthManager App)
> }
Then in your initializer you'll have something like this:
> d <- nestSnaplet "db" db pgsInit
> a <- nestSnaplet "auth" auth $ initPostgresAuth sess d
If you have not already created the database table for users, it will
automatically be created for you the first time you run your application.
-}
module Snap.Snaplet.Auth.Backends.PostgresqlSimple
( initPostgresAuth
) where
------------------------------------------------------------------------------
import Control.Applicative
import Control.Error
import qualified Control.Exception as E
import Control.Lens ((^#))
import Control.Monad.IO.Class (liftIO)
import Control.Monad (liftM, when, void)
import qualified Data.Configurator as C
import qualified Data.Text as T
import Data.Text (Text)
import qualified Data.Text.Encoding as T
import qualified Database.PostgreSQL.Simple as P
import qualified Database.PostgreSQL.Simple.ToField as P
import Database.PostgreSQL.Simple.FromField
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.Types
import Snap
import Snap.Snaplet.Auth
import Snap.Snaplet.PostgresqlSimple
import Snap.Snaplet.PostgresqlSimple.Internal
import Snap.Snaplet.Session
import Web.ClientSession
import Paths_snaplet_postgresql_simple
------------------------------------------------------------------------------
data PostgresAuthManager = PostgresAuthManager
{ pamTable :: AuthTable
, pamConn :: Postgres
}
------------------------------------------------------------------------------
-- | Initializer for the postgres backend to the auth snaplet.
--
initPostgresAuth
:: SnapletLens b SessionManager -- ^ Lens to the session snaplet
-> Snaplet Postgres -- ^ The postgres snaplet
-> SnapletInit b (AuthManager b)
initPostgresAuth sess db = makeSnaplet "postgresql-auth" desc datadir $ do
config <- getSnapletUserConfig
authTable <- liftIO $ C.lookupDefault "snap_auth_user" config "authTable"
authSettings <- authSettingsFromConfig
key <- liftIO $ getKey (asSiteKey authSettings)
let tableDesc = defAuthTable { tblName = authTable }
let manager = PostgresAuthManager tableDesc $ db ^# snapletValue
liftIO $ createTableIfMissing manager
rng <- liftIO mkRNG
return AuthManager
{ backend = manager
, session = sess
, activeUser = Nothing
, minPasswdLen = asMinPasswdLen authSettings
, rememberCookieName = asRememberCookieName authSettings
, rememberCookieDomain = asRememberCookieDomain authSettings
, rememberPeriod = asRememberPeriod authSettings
, siteKey = key
, lockout = asLockout authSettings
, randomNumberGenerator = rng
}
where
desc = "A PostgreSQL backend for user authentication"
datadir = Just $ liftM (++"/resources/auth") getDataDir
------------------------------------------------------------------------------
-- | Create the user table if it doesn't exist.
createTableIfMissing :: PostgresAuthManager -> IO ()
createTableIfMissing PostgresAuthManager{..} = do
withConnection pamConn $ \conn -> do
res <- P.query_ conn $ Query $ T.encodeUtf8 $
"select relname from pg_class where relname='"
`T.append` schemaless (tblName pamTable) `T.append` "'"
when (null (res :: [Only T.Text])) $
void (P.execute_ conn (Query $ T.encodeUtf8 q))
return ()
where
schemaless = T.reverse . T.takeWhile (/='.') . T.reverse
q = T.concat
[ "CREATE TABLE \""
, tblName pamTable
, "\" ("
, T.intercalate "," (map (fDesc . ($pamTable) . fst) colDef)
, ")"
]
buildUid :: Int -> UserId
buildUid = UserId . T.pack . show
instance FromField UserId where
fromField f v = buildUid <$> fromField f v
instance FromField HashedPassword where
fromField f v = HashedPassword <$> fromField f v
instance FromRow AuthUser where
fromRow =
AuthUser
<$> _userId
<*> _userLogin
<*> _userEmail
<*> _userPassword
<*> _userActivatedAt
<*> _userSuspendedAt
<*> _userRememberToken
<*> _userLoginCount
<*> _userFailedLoginCount
<*> _userLockedOutUntil
<*> _userCurrentLoginAt
<*> _userLastLoginAt
<*> _userCurrentLoginIp
<*> _userLastLoginIp
<*> _userCreatedAt
<*> _userUpdatedAt
<*> _userResetToken
<*> _userResetRequestedAt
where
!_userId = field
!_userLogin = field
!_userEmail = field
!_userPassword = field
!_userActivatedAt = field
!_userSuspendedAt = field
!_userRememberToken = field
!_userLoginCount = field
!_userFailedLoginCount = field
!_userLockedOutUntil = field
!_userCurrentLoginAt = field
!_userLastLoginAt = field
!_userCurrentLoginIp = field
!_userLastLoginIp = field
!_userCreatedAt = field
!_userUpdatedAt = field
!_userResetToken = field
!_userResetRequestedAt = field
querySingle :: (ToRow q, FromRow a)
=> Postgres -> Query -> q -> IO (Maybe a)
querySingle pc q ps = withConnection pc $ \conn -> return . listToMaybe =<<
P.query conn q ps
authExecute :: ToRow q
=> Postgres -> Query -> q -> IO ()
authExecute pc q ps = do
withConnection pc $ \conn -> P.execute conn q ps
return ()
instance P.ToField HashedPassword where
toField pw = P.toField $ hashedByteString pw
-- | Datatype containing the names of the columns for the authentication table.
data AuthTable
= AuthTable
{ tblName :: Text
, colId :: (Text, Text)
, colLogin :: (Text, Text)
, colEmail :: (Text, Text)
, colPassword :: (Text, Text)
, colActivatedAt :: (Text, Text)
, colSuspendedAt :: (Text, Text)
, colRememberToken :: (Text, Text)
, colLoginCount :: (Text, Text)
, colFailedLoginCount :: (Text, Text)
, colLockedOutUntil :: (Text, Text)
, colCurrentLoginAt :: (Text, Text)
, colLastLoginAt :: (Text, Text)
, colCurrentLoginIp :: (Text, Text)
, colLastLoginIp :: (Text, Text)
, colCreatedAt :: (Text, Text)
, colUpdatedAt :: (Text, Text)
, colResetToken :: (Text, Text)
, colResetRequestedAt :: (Text, Text)
, rolesTable :: Text
}
-- | Default authentication table layout
defAuthTable :: AuthTable
defAuthTable
= AuthTable
{ tblName = "snap_auth_user"
, colId = ("uid", "SERIAL PRIMARY KEY")
, colLogin = ("login", "text UNIQUE NOT NULL")
, colEmail = ("email", "text")
, colPassword = ("password", "text")
, colActivatedAt = ("activated_at", "timestamptz")
, colSuspendedAt = ("suspended_at", "timestamptz")
, colRememberToken = ("remember_token", "text")
, colLoginCount = ("login_count", "integer NOT NULL")
, colFailedLoginCount = ("failed_login_count", "integer NOT NULL")
, colLockedOutUntil = ("locked_out_until", "timestamptz")
, colCurrentLoginAt = ("current_login_at", "timestamptz")
, colLastLoginAt = ("last_login_at", "timestamptz")
, colCurrentLoginIp = ("current_login_ip", "text")
, colLastLoginIp = ("last_login_ip", "text")
, colCreatedAt = ("created_at", "timestamptz")
, colUpdatedAt = ("updated_at", "timestamptz")
, colResetToken = ("reset_token", "text")
, colResetRequestedAt = ("reset_requested_at", "timestamptz")
, rolesTable = "user_roles"
}
fDesc :: (Text, Text) -> Text
fDesc f = fst f `T.append` " " `T.append` snd f
-- | List of deconstructors so it's easier to extract column names from an
-- 'AuthTable'.
colDef :: [(AuthTable -> (Text, Text), AuthUser -> P.Action)]
colDef =
[ (colId , P.toField . fmap unUid . userId)
, (colLogin , P.toField . userLogin)
, (colEmail , P.toField . userEmail)
, (colPassword , P.toField . userPassword)
, (colActivatedAt , P.toField . userActivatedAt)
, (colSuspendedAt , P.toField . userSuspendedAt)
, (colRememberToken , P.toField . userRememberToken)
, (colLoginCount , P.toField . userLoginCount)
, (colFailedLoginCount, P.toField . userFailedLoginCount)
, (colLockedOutUntil , P.toField . userLockedOutUntil)
, (colCurrentLoginAt , P.toField . userCurrentLoginAt)
, (colLastLoginAt , P.toField . userLastLoginAt)
, (colCurrentLoginIp , P.toField . userCurrentLoginIp)
, (colLastLoginIp , P.toField . userLastLoginIp)
, (colCreatedAt , P.toField . userCreatedAt)
, (colUpdatedAt , P.toField . userUpdatedAt)
, (colResetToken , P.toField . userResetToken)
, (colResetRequestedAt, P.toField . userResetRequestedAt)
]
saveQuery :: AuthTable -> AuthUser -> (Text, [P.Action])
saveQuery at u@AuthUser{..} = maybe insertQuery updateQuery userId
where
insertQuery = (T.concat [ "INSERT INTO "
, tblName at
, " ("
, T.intercalate "," cols
, ") VALUES ("
, T.intercalate "," vals
, ") RETURNING "
, T.intercalate "," (map (fst . ($at) . fst) colDef)
]
, params)
qval f = fst (f at) `T.append` " = ?"
updateQuery uid =
(T.concat [ "UPDATE "
, tblName at
, " SET "
, T.intercalate "," (map (qval . fst) $ tail colDef)
, " WHERE "
, fst (colId at)
, " = ? RETURNING "
, T.intercalate "," (map (fst . ($at) . fst) colDef)
]
, params ++ [P.toField $ unUid uid])
cols = map (fst . ($at) . fst) $ tail colDef
vals = map (const "?") cols
params = map (($u) . snd) $ tail colDef
onFailure :: Monad m => E.SomeException -> m (Either AuthFailure a)
onFailure e = return $ Left $ AuthError $ show e
------------------------------------------------------------------------------
-- |
instance IAuthBackend PostgresAuthManager where
save PostgresAuthManager{..} u@AuthUser{..} = do
let (qstr, params) = saveQuery pamTable u
let q = Query $ T.encodeUtf8 qstr
let action = withConnection pamConn $ \conn -> do
res <- P.query conn q params
return $ Right $ fromMaybe u $ listToMaybe res
E.catch action onFailure
lookupByUserId PostgresAuthManager{..} uid = do
let q = Query $ T.encodeUtf8 $ T.concat
[ "select ", T.intercalate "," cols, " from "
, tblName pamTable
, " where "
, fst (colId pamTable)
, " = ?"
]
querySingle pamConn q [unUid uid]
where cols = map (fst . ($pamTable) . fst) colDef
lookupByLogin PostgresAuthManager{..} login = do
let q = Query $ T.encodeUtf8 $ T.concat
[ "select ", T.intercalate "," cols, " from "
, tblName pamTable
, " where "
, fst (colLogin pamTable)
, " = ?"
]
querySingle pamConn q [login]
where cols = map (fst . ($pamTable) . fst) colDef
lookupByRememberToken PostgresAuthManager{..} token = do
let q = Query $ T.encodeUtf8 $ T.concat
[ "select ", T.intercalate "," cols, " from "
, tblName pamTable
, " where "
, fst (colRememberToken pamTable)
, " = ?"
]
querySingle pamConn q [token]
where cols = map (fst . ($pamTable) . fst) colDef
destroy PostgresAuthManager{..} AuthUser{..} = do
let q = Query $ T.encodeUtf8 $ T.concat
[ "delete from "
, tblName pamTable
, " where "
, fst (colLogin pamTable)
, " = ?"
]
authExecute pamConn q [userLogin]