unit uDataModuleUsuarios;

interface

uses {vcl:} SysUtils, Classes, DB, DBClient,
     {RemObjects:} uDAClientDataModule, uDADataTable, uDABINAdapter,
  uROServiceComponent, uRORemoteService, uROClient, uROBinMessage,
  uROWinInetHttpChannel, uDAScriptingProvider, uDACDSDataTable,
  VARELA_Intf;

const
  ROL_ADMIN = 'Administrador';

type
  TdmUsuarios = class(TDAClientDataModule)
    ROLoginService: TRORemoteService;
    tbl_Usuarios: TDACDSDataTable;
    ds_Usuarios: TDADataSource;
    procedure DAClientDataModuleCreate(Sender: TObject);
    procedure DAClientDataModuleDestroy(Sender: TObject);
  private
    FLoginInfo: TLoginInfo;
    function CambiarPassword (const APassword : String) : boolean; overload;

  public
    function Login: Boolean; overload;
    function Login(Usuario: String; Password: String): Boolean; overload;
    procedure Logout;
    procedure CambiarPassword; overload;
    function EsAdmin : Boolean;
    property LoginInfo: TLoginInfo read FLoginInfo write FLoginInfo;
  end;

var
  dmUsuarios: TdmUsuarios;

implementation

{$R *.DFM}

uses
  Forms, Controls, uDataTableUtils, uDataModuleBase, uLoginForm,
  uCambiarPassword, Dialogs, Windows;

{ TDAClientDataModule1 }

procedure TdmUsuarios.DAClientDataModuleCreate(Sender: TObject);
begin
  ROLoginService.Channel := dmBase.Channel;
  ROLoginService.Message := dmBase.Message;
  Adapter := dmBase.Adapter;
end;

function TdmUsuarios.Login: Boolean;
begin
  with TfLoginForm.Create(NIL) do
    try
      if Assigned(FLoginInfo) then
        edtUser.Text := FLoginInfo.UserID;
      Result := (ShowModal = mrOK)
    finally
      Free;
    end;
end;

function TdmUsuarios.Login(Usuario: String; Password: String): Boolean;
begin
  Result := (ROLoginService as IsrvLogin).Login(Usuario, Password, FLoginInfo);
end;

procedure TdmUsuarios.Logout;
begin
  (ROLoginService as IsrvLogin).Logout;
end;

procedure TdmUsuarios.DAClientDataModuleDestroy(Sender: TObject);
begin
  FreeAndNIL(FLoginInfo);
end;

function TdmUsuarios.EsAdmin: Boolean;
begin
  Result := False;
  if LoginInfo.Roles.Count > 0 then
    Result := (Pos(ROL_ADMIN, LoginInfo.Roles.Items[0]) > 0);
end;

procedure TdmUsuarios.CambiarPassword;
begin
  with TfCambiarPassword.Create(NIL) do
    try
      if ShowModal = mrOk then
        if CambiarPassword(edtPassword.Text) then
          Application.MessageBox('La contraseña ha sido cambiada correctamente.', 'Información', MB_OK);
    finally
      Free;
    end;
end;

function TdmUsuarios.CambiarPassword(const APassword: String): boolean;
begin
  Result := False;
  if not (ROLoginService as IsrvLogin).SetUserPassword(LoginInfo.UserID, APassword) then
    raise Exception.Create('Error en el servidor. No se ha podido cambiar la contraseña');
  Result := True;    
end;

initialization
  dmUsuarios := TdmUsuarios.Create(nil);

finalization
  FreeAndNil(dmUsuarios);

end.
