2011-02-02 16:57:58 -06:00
|
|
|
-module(ts_user).
|
2011-02-04 17:19:53 -06:00
|
|
|
%-export([create_table/1, new/1, update/1, lookup/1, list/2]).
|
|
|
|
-compile(export_all).
|
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{}) ->
|
|
|
|
% create a new User record
|
2011-02-07 08:56:07 -06:00
|
|
|
Salt = generate_salt(),
|
|
|
|
HashedPwd = hash_pwd(User#ts_user.pwd, Salt),
|
2011-02-03 17:23:40 -06:00
|
|
|
User#ts_user{pwd = HashedPwd, pwd_salt = Salt}.
|
|
|
|
|
2011-02-04 17:19:53 -06:00
|
|
|
generate_salt() -> crypto:rand_bytes(36).
|
2011-02-03 17:23:40 -06:00
|
|
|
|
2011-02-07 08:56:07 -06:00
|
|
|
hash_pwd(Password, Salt) -> crypto:sha(Password ++ Salt).
|
|
|
|
|
|
|
|
check_credentials(Username, Password) ->
|
|
|
|
User = lookup(Username),
|
|
|
|
HashedInput = hash_pwd(Password, User#ts_user.pwd_salt),
|
|
|
|
|
|
|
|
HashedInput == User#ts_user.pwd.
|