2011-02-02 16:57:58 -06:00
|
|
|
-module(ts_user).
|
2011-02-03 17:23:40 -06:00
|
|
|
-export([create_table/1, new/1, update/1, lookup/1, list/2]).
|
2011-02-02 16:57:58 -06:00
|
|
|
|
|
|
|
-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}]).
|
|
|
|
|
2011-02-03 17:23:40 -06:00
|
|
|
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]).
|