module Session where

import Process
import DB
import Now

create_rand_sessid bitlength = do
    random <- run $ "openssl rand " ++ show bitlength
    return random

new_session_id username = do
    -- create a 2^10 long random string and get the SHA-256 digest of it
    sessId <- run $ "openssl rand " ++ show (2^10) ++ "|openssl dgst -sha256"
    let session_id = chomp sessId
    -- sessions expire after 30 minutes
    expiry_date <- now_plus_min 30
    db_insert $ "INSERT INTO sessions VALUES ('" ++ username ++ "', '" ++ session_id ++ "', '" ++ expiry_date ++ "')"
    return session_id

check_session_id session_id = do
    checkdate <- now
    res <- db_select $ "SELECT * FROM sessions WHERE sessionid LIKE '" ++ session_id ++ "' AND '" ++ checkdate ++ "' < expiry_date"
    return (length res > 0)

get_session_user :: String -> IO String
get_session_user session_id = do
    res <- db_firstvalue $ "SELECT username FROM sessions WHERE sessionid LIKE '" ++ session_id ++ "'"
    return res

-- cf. perldoc -f chomp
chomp :: String -> String
chomp a =     
    if last a == '\n'
        then init a
        else a
