aboutsummaryrefslogtreecommitdiff
path: root/cli/Main.hs
blob: 40c3da25b2a12a515526bcbb421a9fe0b101c8a1 (plain) (blame)
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
{-# LANGUAGE OverloadedStrings #-}

module Main(main) where

import System.Environment (getArgs)
import Database (runDb, runMigrations)
import Data.User
import Database.Persist
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Crypto.BCrypt (hashPasswordUsingPolicy, fastBcryptHashingPolicy)
import qualified Data.ByteString.Base16 as Base16

----------------------------------------------------------------------------------------------------
main :: IO ()
main = do
  args <- getArgs

  case args of
    ["migrate"] -> do
      _ <- runMigrations
      putStrLn "Migrated"
    [name, pass] -> do
      hashed_password <- hashPassword (T.pack pass)

      _ <- runDb $ insert $ User (T.pack name) hashed_password Nothing Nothing
      putStrLn $ "User " ++ name ++ " created"
    [name, pass, display_name] -> do
      hashed_password <- hashPassword (T.pack pass)

      _ <- runDb $ insert $ User (T.pack name) hashed_password (Just $ T.pack display_name) Nothing
      putStrLn $ "User " ++ name ++ " created with display name '" ++ display_name ++ "'"
    _ -> putStrLn "Usage: add-user <username> <password> [display_name]"
  where
    hashPassword :: T.Text -> IO T.Text
    hashPassword pass = do
      maybe_hashed <- hashPasswordUsingPolicy fastBcryptHashingPolicy (T.encodeUtf8 pass)

      case maybe_hashed of
        Just hashed -> return $ T.decodeUtf8 $ Base16.encode hashed
        Nothing -> error "Password hashing failed"