timestamper/src/ts_user.erl

47 lines
1.4 KiB
Erlang
Raw Normal View History

-module(ts_user).
-export([create_table/1, new/1, update/1, lookup/1, list/2]).
-include("ts_db_records.hrl").
-include_lib("stdlib/include/qlc.hrl").
create_table(TableOpts) ->
mnesia:create_table(ts_user,
TableOpts ++ [{attributes, record_info(fields, ts_user)},
{type, ordered_set}]).
new(UR = #ts_user{}) ->
case mnesia:dirty_read(ts_user, UR#ts_user.username) of
[ExistingRecord] -> {error, {record_exists, ExistingRecord}};
[] -> mnesia:dirty_write(hash_input_record(UR))
end.
update(UR = #ts_user{}) ->
case mnesia:dirty_read(ts_user, UR#ts_user.username) of
[] -> no_record;
[_Record] -> mnesia:dirty_write(hash_input_record(UR))
end.
lookup(Username) ->
case mnesia:dirty_read(ts_user, Username) of
[] -> no_record;
[User] -> User
end.
list(Start, Length) -> ts_common:list(ts_user, Start, Length).
hash_input_record(User=#ts_user{}) ->
% generate the password salt
Salt = generate_salt(),
% hash the password
HashedPwd = hash_pwd(User#ts_user.username, Salt),
% create a new User record
User#ts_user{pwd = HashedPwd, pwd_salt = Salt}.
generate_salt() ->
"This is a worthless salt value only suitable for testing.".
hash_pwd(Password, Salt) -> do_hash(Password ++ Salt, []).
do_hash([], Hashed) -> Hashed;
do_hash([Char|Pwd], Hashed) -> do_hash(Pwd, [Char + 13 | Hashed]).