private void generateNewToken(DTOAuthentication user)
 {
     using (var context = new AuthenticationModel())
     {
         user.Token = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
         var tab = context.Users.FirstOrDefault(x => x.UserName.Equals(user.UserName, StringComparison.InvariantCultureIgnoreCase) && x.Password == user.EncryptedPassword);
         // if (tab == null) throw new Exception();//Todo
         tab.Token               = user.Token;
         tab.ActivationDate      = DateTime.UtcNow;
         tab.LastRequestDateTime = DateTime.UtcNow;
         context.SaveChanges();
     }
 }
        public DTOAuthenticationResponse DoLogin(DTOAuthenticationRequest request)
        {
            var pwd = encrypt(request.Password);

            //--REM
            using (var context = new AuthenticationModel())
            {
                if (!context.Users.Any())
                {
                    var tab = new Users();
                    tab.ActivationDate       = DateTime.UtcNow;
                    tab.Active               = true;
                    tab.ID                   = Guid.NewGuid();
                    tab.Mail                 = "mauro@mauro";
                    tab.Password             = encrypt("mauro");
                    tab.UserName             = "******";
                    context.Entry(tab).State = EntityState.Added;
                    context.SaveChanges();
                }
            }
            //
            var user =
                GetByCondition(
                    x =>
                    (x.UserName.Equals(request.UserName, StringComparison.InvariantCultureIgnoreCase) || x.Mail.Equals(request.UserName, StringComparison.InvariantCultureIgnoreCase)) &&
                    x.Password.Equals(pwd));

            if (user == null)
            {
                return new DTOAuthenticationResponse
                       {
                           Error = new DTOAuthenticationResponseError
                           {
                               Error =
                                   "Username o Password non validi.",
                               ErrorCode = eAuthenticationResponseErrorCode.UserNotFound
                           }
                       }
            }
            ;
            if (!user.IsActive)
            {
                return new DTOAuthenticationResponse
                       {
                           Error = new DTOAuthenticationResponseError
                           {
                               Error =
                                   "Profilo non Attivo.",
                               ErrorCode = eAuthenticationResponseErrorCode.UserNotActive
                           }
                       }
            }
            ;

            getToken(user);
            return(new DTOAuthenticationResponse
            {
                Error = null,
                Token = user.Token
            });
        }