Exemplo n.º 1
0
        public User Create(string login, string password, string nickname)
        {
            try
            {
                if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(nickname))
                {
                    throw new ArgumentException("Invalid parameters");
                }

                User user = new User
                {
                    Login    = login,
                    Nickname = nickname,
                    Password = Criptography.GetSHA1(password)
                };

                UserRepository.Save(user);

                return(user);
            }
            catch (ArgumentException ex)
            {
                Logger.LogWarning("Error while saving user to database", ex);
                throw;
            }
            catch (Exception ex)
            {
                Logger.LogError("Unknown error while saving user to database", ex);
                throw new Exception("Unknown error while saving user to database");
            }
        }
Exemplo n.º 2
0
        public static List <ResultPesquisaModel> ObterPesquisa(string texto)
        {
            List <ResultPesquisaModel> ListEntity = null;

            using (PrivacyContext context = new PrivacyContext())
            {
                ListEntity = context.Usuario
                             .Include(y => y.IdEtniaNavigation)
                             .Include(y => y.IdGeneroNavigation)
                             .Where(x => /*x.Ativo &&*/ x.PerfilPublico &&
                                    (
                                        x.Nome.ToLower().Contains(texto.ToLower()) ||
                                        x.IdEtniaNavigation.Descricao.ToLower().Contains(texto.ToLower()) ||
                                        x.IdGeneroNavigation.Descricao.ToLower().Contains(texto.ToLower()) ||
                                        x.Cidade.ToLower().Contains(texto.ToLower()) ||
                                        x.Pais.ToLower().Contains(texto.ToLower()) ||
                                        x.Estado.ToLower().Contains(texto.ToLower())
                                    )).ToList()
                             .Select(k => new ResultPesquisaModel {
                    IdUsuario = k.IdUsuario,
                    IdUsuarioCriptografado = WebUtility.UrlDecode(Criptography.Encrypt(k.IdUsuario.ToString())),
                    Nome       = k.Nome,
                    Cidade     = k.Cidade,
                    Pais       = k.Pais,
                    FotoPerfil = (k.FotoPerfil.IsNullOrEmpty() ? "/FotoPerfil/default.jpg" : k.FotoPerfil),
                    Etnia      = k.IdEtniaNavigation.Descricao,
                    Genero     = k.IdGeneroNavigation.Descricao
                }).ToList();
            }
            return(ListEntity);
        }
Exemplo n.º 3
0
        public void CreateWithNoHome_ReturnsCreatedUserWithId()
        {
            var          userRepositoryMock = new Mock <IUserRepository>();
            var          homeRepositoryMock = new Mock <IHomeRepository>();
            var          loggingStub        = new Mock <ILogger <UsersService> >();
            UsersService userService        = new UsersService(userRepositoryMock.Object, homeRepositoryMock.Object, loggingStub.Object);

            userRepositoryMock.Setup(o => o.Save(It.IsAny <User>()))
            .Callback((User u) => { u.UserId = 1; })
            .Verifiable();

            User userExpected = new User
            {
                UserId   = 1,
                Login    = "******",
                Password = Criptography.GetSHA1("a"),
                Nickname = "a"
            };

            string login    = "******";
            string password = "******";
            string nickname = "a";

            User userSaved = userService.Create(login, password, nickname);

            string userExpectedString = JsonConvert.SerializeObject(userExpected);
            string userSavedString    = JsonConvert.SerializeObject(userSaved);

            Assert.Equal(userExpectedString, userSavedString);
        }
        public IActionResult OnGet(string Id)
        {
            //Carregar Perfil de Usuário
            Entity = UsuarioModel.ObterUsuario(long.Parse(WebUtility.HtmlEncode(Criptography.Decrypt(Id))));

            return(Page());
        }
        //public Valor Valor { get; set; }
        #endregion

        #region Construtores
        #endregion



        #region Métodos
        public IActionResult OnGet(string Id)
        {
            if (HttpContext.Session.GetObjectFromJson <Usuario>("USUARIO") == null)
            {
                return(RedirectToPage("/Login"));
            }

            #region Verifica se o usuário logado já comprou a mina rs
            using (PrivacyContext context = new PrivacyContext())
            {
                Entity = UsuarioModel.ObterUsuario(long.Parse(WebUtility.HtmlEncode(Criptography.Decrypt(Id))));
                var UsuarioLogado = HttpContext.Session.GetObjectFromJson <Usuario>("USUARIO");

                var assinado = context.Transacao.Where(a => a.IdUsuario == UsuarioLogado.IdUsuario && a.IdPerfil == Entity.IdUsuario).FirstOrDefault();

                if (assinado != null)
                {
                    return(RedirectToPage("/ProfilePhotos", new { Id = Id }));
                }
            }
            #endregion

            //Carregar Perfil de Usuário
            Entity = UsuarioModel.ObterUsuario(long.Parse(WebUtility.HtmlEncode(Criptography.Decrypt(Id))));
            //Valor = Entity.Valor.Where(a => a.IdUsuario == Entity.IdUsuario).FirstOrDefault();
            return(Page());
        }
 public int Registrar(Usuarios usuario, string Password)
 {
     byte[] HassPassword, SaltPassword;
     Criptography.CrearPasswordEncriptado(Password, out HassPassword, out SaltPassword);
     usuario.HashPassword = HassPassword;
     usuario.SaltPass     = SaltPassword;
     _dbBib.Usuarios.Add(usuario);
     _dbBib.SaveChanges();
     return(usuario.IdUsuario);
 }
Exemplo n.º 7
0
        public IActionResult OnGet(string Id)
        {
            if (HttpContext.Session.GetObjectFromJson <Usuario>("USUARIO") == null)
            {
                return(RedirectToPage("/Login"));
            }

            //Carregar Perfil de Usuário
            Entity = UsuarioModel.ObterUsuario(long.Parse(WebUtility.HtmlEncode(Criptography.Decrypt(Id))));

            return(Page());
        }
Exemplo n.º 8
0
        private void ValidarInformacoesLogin(Usuario UsuarioBanco, Usuario Usuario)
        {
            if (UsuarioBanco == null)
            {
                throw new ValidationException(Usuario, "Usuário inexistente no sistema!");
            }

            if (Criptography.GetHash(Usuario.Senha, UsuarioBanco.Salt) != UsuarioBanco.Senha)
            {
                throw new ValidationException(Usuario, "Senha inválida!");
            }
        }
Exemplo n.º 9
0
        private Dictionary <string, string> GetToken()
        {
            this.authorizationToken         = $"Bearer {ConfigurationManager.AppSettings.Get("CLIENT_APPLICATION_KEY")}";
            this.authorizationData          = Criptography.GenerateKey();
            this.authorizationEncryptedData = Criptography.GenerateHMACSHA512(this.authorizationData, ConfigurationManager.AppSettings.Get("CLIENT_APPLICATION_SECRET_KEY"));

            return(new Dictionary <string, string>()
            {
                { "authorization", this.authorizationToken },
                { "x-authorization-raw-data", this.authorizationData },
                { "x-authorization-encrypted-data", this.authorizationEncryptedData },
            });
        }
        public Usuarios Login(string correo, string Password)
        {
            var usuarioCredencial = _dbBib.Usuarios.Where(x => x.Correo == correo).FirstOrDefault();

            if (usuarioCredencial == null)
            {
                return(null);
            }
            if (!Criptography.ValidacionPassword(Password, usuarioCredencial.HashPassword, usuarioCredencial.SaltPass))
            {
                return(null);
            }
            return(usuarioCredencial);
        }
        public IActionResult OnGetPasso4(string Senha, string Celular, string QuantoQuer = null)
        {
            Usuario usuario = HttpContext.Session.GetObjectFromJson <Usuario>("USUARIO");

            usuario.Senha      = Criptography.Encrypt(Senha);
            usuario.Celular    = Celular;
            usuario.QuantoQuer = QuantoQuer.IsNullOrEmpty() ? (decimal?)null : decimal.Parse(QuantoQuer);

            HttpContext.Session.SetObjectAsJson("USUARIO", usuario);

            return(new JsonResult(new { OK = true, Mensagem = Mensagem }, new Newtonsoft.Json.JsonSerializerSettings()
            {
            }));
        }
Exemplo n.º 12
0
        public ActionResult CreateUser(UsuarioModel usuario)
        {
            if (ModelState.IsValid)
            {
                // Informações do objeto
                usuario.Cpf   = Methods.ValidarCpf(usuario.Cpf) ? Methods.RemoveSpecialsCaracts(usuario.Cpf) : throw new Exception("CPF Invalido!!");
                usuario.Senha = Criptography.GenerateHashString(usuario.Senha);

                if (_usuarioService.Insert(usuario))
                {
                    return(RedirectToAction("SignIn", "Login"));
                }
            }
            return(View(usuario));
        }
Exemplo n.º 13
0
        public ActionResult ChangePass(IFormCollection collection)
        {
            var user = _usuarioService.GetById(Convert.ToInt32(collection["IdUsuario"]));

            if (user != null)
            {
                user.Senha = Criptography.GenerateHashString(collection["senha"]);
                if (_usuarioService.Update(user))
                {
                    _recuperarSenhaService.SetTokenInvalid(user.IdUsuario);
                    return(RedirectToActionPermanent("Index", "Login", new { msg = "sucessChange" }));
                }
            }

            return(RedirectToActionPermanent("Index", "Login", new { msg = "errorChange" }));
        }
Exemplo n.º 14
0
        public void Login_InvalidPassword_ReturnsApplicationException()
        {
            var          userRepositoryMock = new Mock <IUserRepository>();
            var          homeRepositoryStub = new Mock <IHomeRepository>();
            var          loggingStub        = new Mock <ILogger <UsersService> >();
            UsersService userService        = new UsersService(userRepositoryMock.Object, homeRepositoryStub.Object, loggingStub.Object);

            userRepositoryMock.Setup(o => o.GetUserByLogin(It.IsAny <string>())).Returns(new User
            {
                Login    = "******",
                Password = Criptography.GetSHA1("b")
            });

            string login    = "******";
            string password = "******";

            Assert.Throws <ApplicationException>(() => userService.Login(login, password));
        }
Exemplo n.º 15
0
        public ActionResult Create(UsuarioViewModel usuarioViewModel)
        {
            ViewBag.TiposUsuario = new SelectList(_tipoUsuarioService.GetAll(), "Id", "Descricao");
            ViewBag.Organizacoes = new SelectList(_organizacaoService.GetAll(), "Id", "RazaoSocial");

            usuarioViewModel.OrganizacaoModel = _organizacaoService.GetById(usuarioViewModel.OrganizacaoModel.Id);

            if (ModelState.IsValid)
            {
                if (!Methods.ValidarCpf(usuarioViewModel.UsuarioModel.Cpf))
                {
                    return(RedirectToAction("Create", "Usuario", new { msg = "invalidCpf" }));
                }

                // Criando usuario que será passado para a autenticação.
                var sucesso = new LoginViewModel {
                    Login = usuarioViewModel.UsuarioModel.Cpf, Senha = usuarioViewModel.UsuarioModel.Senha
                };

                // Informações do objeto
                usuarioViewModel.UsuarioModel.Cpf   = Methods.CleanString(usuarioViewModel.UsuarioModel.Cpf);
                usuarioViewModel.UsuarioModel.Senha = Criptography.GeneratePasswordHash(usuarioViewModel.UsuarioModel.Senha);

                try
                {
                    _usuarioService.Insert(usuarioViewModel);
                    TempData["mensagemSucesso"] = "Usuário criado com sucesso!";
                }
                catch (ServiceException se)
                {
                    TempData["mensagemErro"] = se.Message;
                    return(View(usuarioViewModel));
                }

                return(RedirectToAction("Authenticate", "Login", sucesso));
            }
            // Se nao inserir, vem pra cá e sai.

            /*var erros = ModelState.Values.SelectMany(m => m.Errors)
             *                    .Select(e => e.ErrorMessage)
             *                    .ToList();
             */
            return(View(usuarioViewModel));
        }
Exemplo n.º 16
0
        public User Login(string login, string password)
        {
            try
            {
                if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
                {
                    throw new ArgumentException("Login or Password is null or empty");
                }

                User user = UserRepository.GetUserByLogin(login);

                if (user != null)
                {
                    string passwordCrip = Criptography.GetSHA1(password);

                    if (login != user.Login || passwordCrip != user.Password)
                    {
                        throw new ApplicationException("Invalid login or password");
                    }
                }
                else
                {
                    throw new ApplicationException("User not found");
                }

                return(user);
            }
            catch (ArgumentException ex)
            {
                Logger.LogWarning("Error while loggin in user", ex);
                throw;
            }
            catch (ApplicationException ex)
            {
                Logger.LogWarning("Error while loggin in user", ex);
                throw;
            }
            catch (Exception ex)
            {
                Logger.LogError("Unknown error while loggin in user", ex);
                throw new Exception("Unknown error while loggin in user");
            }
        }
Exemplo n.º 17
0
        public void Login_ValidCredentials_ReturnsUser()
        {
            var          userRepositoryMock = new Mock <IUserRepository>();
            var          homeRepositoryStub = new Mock <IHomeRepository>();
            var          loggingStub        = new Mock <ILogger <UsersService> >();
            UsersService userService        = new UsersService(userRepositoryMock.Object, homeRepositoryStub.Object, loggingStub.Object);

            userRepositoryMock.Setup(o => o.GetUserByLogin(It.IsAny <string>())).Returns(new User
            {
                UserId   = 1,
                Login    = "******",
                Password = Criptography.GetSHA1("a")
            });

            string login    = "******";
            string password = "******";
            User   user     = userService.Login(login, password);

            Assert.Equal(1, user.UserId);
        }
Exemplo n.º 18
0
        public IActionResult OnGet(string q = null)
        {
            if (!q.IsNullOrEmpty())
            {
                long IdUsuario = Criptography.Decrypt(q).ExtractLong();

                using (PrivacyContext context = new PrivacyContext())
                {
                    Usuario user = context.Usuario.Where(x => x.IdUsuario == IdUsuario).FirstOrDefault();
                    user.Ativo        = true;
                    user.DataCadastro = DateTime.Now;
                    context.SaveChanges();
                }

                return(Page());
            }
            else
            {
                return(RedirectToAction("/Login"));
            }
        }
Exemplo n.º 19
0
        public async Task <Result <UsuarioViewModel> > AlterarSenha(AlterarSenhaViewModel Usuario)
        {
            return(await ProcessmentCommand.Execute <UsuarioViewModel>(async() =>
            {
                var Id = Convert.ToInt32(Principal.GetClaim("Id"));
                var UsuarioBanco = await Repository.GetById(new Usuario {
                    Id = Id
                });

                if (Usuario.NovaSenha != Usuario.ConfirmacaoNovaSenha)
                {
                    throw new ValidationException(Usuario, "Senhas informadas não são iguais!");
                }

                ValidarInformacoesLogin(UsuarioBanco, new Usuario {
                    Senha = Usuario.Senha
                });

                UsuarioBanco.Senha = Criptography.GetHash(Usuario.NovaSenha, UsuarioBanco.Salt);
                await Repository.Update(UsuarioBanco);
                return null;
            }));
        }
Exemplo n.º 20
0
 public CriptographyTest()
 {
     Criptography = new Criptography(Guid.NewGuid().ToString());
 }
Exemplo n.º 21
0
        public async Task <IActionResult> SignIn(LoginViewModel login)
        {
            if (ModelState.IsValid)
            {
                var cpf   = Methods.ValidarCpf(login.Cpf) ? Methods.RemoveSpecialsCaracts(login.Cpf) : throw new Exception("CPF Invalido!!");
                var senha = Criptography.GenerateHashString(login.Senha);

                var user = _usuarioService.GetByLogin(cpf, senha);

                if (user != null)
                {
                    // informaçoes pessoais do usuario | adicionar as claims o dado que mais precisar
                    var person   = _pessoaService.GetById(user.IdPessoa);
                    var role     = Methods.ReturnRole(user.TipoUsuario);
                    var trabalha = "";
                    var empresa  = "";

                    if (role != "ADM" || role != "USUARIO")
                    {
                        var trabalhaEstado = _pessoaTrabalhaEstado.GetByIdPessoa(person.Idpessoa);
                        if (trabalhaEstado != null)
                        {
                            trabalha = _estadoService.GetById(trabalhaEstado.IdEstado).Nome;
                            empresa  = _empresaExameService.GetById(trabalhaEstado.IdEmpresaExame).Nome;
                        }
                        else
                        {
                            var trabalhaMunicipio = _pessoaTrabalhaMunicipio.GetByIdPessoa(person.Idpessoa);
                            trabalha = _municipioService.GetById(trabalhaMunicipio.IdMunicipio).Nome;
                        }
                    }

                    var claims = new List <Claim>
                    {
                        new Claim(ClaimTypes.SerialNumber, user.IdUsuario.ToString()),
                        new Claim(ClaimTypes.Name, person.Nome),
                        new Claim(ClaimTypes.StateOrProvince, person.Estado),
                        new Claim(ClaimTypes.Locality, person.Cidade),
                        new Claim(ClaimTypes.UserData, user.Cpf),
                        new Claim(ClaimTypes.Email, user.Email),
                        new Claim(ClaimTypes.NameIdentifier, user.IdPessoa.ToString()),
                        new Claim(ClaimTypes.Role, role),
                        new Claim(ClaimTypes.Dns, trabalha),
                        new Claim(ClaimTypes.Sid, empresa)
                    };

                    // Adicionando uma identidade as claims.
                    var identidade = new ClaimsIdentity(claims, "login");

                    // Propriedades da autenticação.
                    var propriedadesClaim = new AuthenticationProperties
                    {
                        ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1) // Expira em 1 dia
                    };

                    // Logando efetivamente.
                    await HttpContext.SignInAsync(new ClaimsPrincipal(identidade), propriedadesClaim);

                    return(RedirectToAction("Index", "Home"));
                }
            }

            return(RedirectToAction("Index", "Login", new { msg = "error" }));
        }
 public CriptographyTest()
 {
     DependencyInjector.RegisterServices();
     Criptography = DependencyInjector.GetService <ICriptography>();
     Criptography.SetKey("8800A390DCF24C9087F8AAE870FCFE02");
 }
        public IActionResult RequestToken([FromBody] LoginViewModel request)
        {
            var user = _service.GetByLoginAndPass(Methods.CleanString(request.Login), Criptography.GeneratePasswordHash(request.Senha));

            if (user != null)
            {
                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.SerialNumber, user.Id.ToString()),
                    new Claim(ClaimTypes.UserData, user.Cpf),
                    new Claim(ClaimTypes.NameIdentifier, user.Nome),
                    new Claim(ClaimTypes.DateOfBirth, user.DataNascimento.ToString()),
                    new Claim(ClaimTypes.Role, user.TipoUsuarioId.ToString())
                };


                // Recebe uma instancia da classe SymmetricSecurityKey e armazena a key de segurança settada no appsettings.
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"]));

                // Recebe uma instancia de SigningCredentials contendo a chave de critpgrafia e o algoritmo q fará a encr/descriptogafia
                var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);


                // Criando o token efetivamente
                var token = new JwtSecurityToken(
                    issuer: "ProjetoSalasUFS", // Emissor
                    audience: "ProjetoSalasUFS",
                    claims: claims,
                    expires: DateTime.Now.AddDays(1), // Expiração do token
                    signingCredentials: credentials
                    );

                return(Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token)
                }));
            }

            return(BadRequest("Credenciais Invalidas"));
        }
Exemplo n.º 24
0
 public CriptographyTest()
 {
     Criptography = DependencyInjector.GetService <ICriptography>();
     Criptography.SetKey(Guid.NewGuid().ToString());
 }
Exemplo n.º 25
0
 public void ResetarSenha()
 {
     AlterarSenha = true;
     Senha        = Criptography.GetHash($"PortalChamados{DateTime.Now.Year}", Salt);
 }
        public async Task <IActionResult> Authenticate(LoginViewModel loginViewModel)
        {
            if (ModelState.IsValid)
            {
                if (ValidaCpf(loginViewModel.Login))
                {
                    // Obtendo o usuario baseado nas informações passadas.
                    var user = _usuarioService.GetByLoginAndPass(Methods.CleanString(loginViewModel.Login), Criptography.GeneratePasswordHash(loginViewModel.Senha));
                    if (user != null)
                    {
                        var claims = new List <Claim>
                        {
                            new Claim(ClaimTypes.SerialNumber, user.Id.ToString()),
                            new Claim(ClaimTypes.UserData, user.Cpf),
                            new Claim(ClaimTypes.NameIdentifier, user.Nome),
                            new Claim(ClaimTypes.DateOfBirth, user.DataNascimento.ToString()),
                            new Claim(ClaimTypes.Role, _tipoUsuarioService.GetById(user.TipoUsuarioId).Descricao)
                        };

                        // Adicionando uma identidade as claims.
                        var identity = new ClaimsIdentity(claims, "login");

                        // Propriedades da autenticação.
                        var claimProperty = new AuthenticationProperties
                        {
                            ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1) // Expira em 1 dia
                        };

                        // Logando efetivamente.
                        await HttpContext.SignInAsync(new ClaimsPrincipal(identity), claimProperty);

                        // Redirecionando, com usuario logado.
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            // usuario invalido.
            return(RedirectToAction("Index", "Login", new { msg = "error" }));
        }
Exemplo n.º 27
0
        public IActionResult OnPost()
        {
            if ((Usuario.IsNullOrEmpty() || Senha.IsNullOrEmpty()))
            {
                Mensagem = "Login/Senha obrigatórios em branco!";
            }
            else
            {
                using (PrivacyContext context = new PrivacyContext())
                {
                    var usuario = context.Usuario.Where(x => x.Login.ToLower() == Usuario.ToLower() && x.Senha == Criptography.Encrypt(Senha)).FirstOrDefault();

                    if (usuario != null)
                    {
                        HttpContext.Session.SetObjectAsJson("USUARIO", usuario);
                        if (!usuario.Ativo)
                        {
                            return(RedirectToPage("/Welcome"));
                        }
                        //Mensagem = "Usuário inativo! Verifique a caixa de entrada de seu email!";
                        else
                        {
                            return(RedirectToPage("/Index"));
                        }
                    }
                    else
                    {
                        Mensagem = "Login/Senha inválidos!";
                    }
                }
            }

            return(Page());
        }
        public IActionResult OnPostSalvarDados()
        {
            Usuario usuario = HttpContext.Session.GetObjectFromJson <Usuario>("USUARIO");

            if (usuario != null)
            {
                using (PrivacyContext context = new PrivacyContext())
                {
                    usuario.Ativo        = false;
                    usuario.DataCadastro = DateTime.Now;
                    usuario.Login        = usuario.Email;
                    context.Usuario.Add(usuario);
                    context.SaveChanges();
                }

                string html = MailModel.ReturnBodyTemplate();

                MailModel.Server    = _configuration["Smtp:Server"];
                MailModel.User      = _configuration["Smtp:User"];
                MailModel.Pass      = _configuration["Smtp:Pass"];
                MailModel.Port      = _configuration["Smtp:Port"];
                MailModel.EnableSSL = _configuration["Smtp:EnableSSL"];

                html = html.Replace("{Titulo}", "Privacy - Ativação de conta");
                html = html.Replace("{Subtitulo}", string.Format("Olá, {0} para concluir seu cadastro clique no link abaixo:", usuario.Nome));
                html = html.Replace("{Texto}", "<a href=\"" + _configuration["Url"].ToString() + "/ActivateAccount?q=" + HttpUtility.UrlEncode(Criptography.Encrypt(usuario.IdUsuario.ToString())) + "\">Ativar Conta</a>");

                MailModel.SendMail(_configuration["Smtp:User"].ToString(), usuario.Email, "Privacy | Ativação de Conta", html);

                usuario = null;

                return(new JsonResult(new { OK = true, Mensagem = Mensagem }, new Newtonsoft.Json.JsonSerializerSettings()
                {
                }));
            }
            else
            {
                return(new JsonResult(new { OK = false, Mensagem = "Falha ao salvar os dados!" }, new Newtonsoft.Json.JsonSerializerSettings()
                {
                }));
            }
        }
Exemplo n.º 29
0
        public IActionResult OnGet(string TokenTransacao, string IdPerfil)
        {
            if (HttpContext.Session.GetObjectFromJson <Usuario>("USUARIO") == null)
            {
                return(RedirectToPage("/Login"));
            }

            UsuarioLogado = HttpContext.Session.GetObjectFromJson <Usuario>("USUARIO");

            PagarMeService.DefaultApiKey        = "ak_test_1V9G2oIoRaRSMUD6rQZKI9XQgJzYMg";
            PagarMeService.DefaultEncryptionKey = "ek_test_YTEFhGJ5f814Q75R3xMKPmTmNKAtK7";

            Transaction transaction = PagarMeService.GetDefaultService().Transactions.Find(TokenTransacao);

            //transaction.Capture(transaction.Amount);


            using (PrivacyContext context = new PrivacyContext())
            {
                var usuarioPerfil = UsuarioModel.ObterUsuario(long.Parse(WebUtility.HtmlEncode(Criptography.Decrypt(IdPerfil))));

                Transacao objetoTransacao = new Transacao();

                objetoTransacao.Valor               = transaction.Amount;
                objetoTransacao.TokenPayPal         = TokenTransacao;
                objetoTransacao.TransactionIdPayPal = transaction.Tid;
                objetoTransacao.Ip = transaction.IP;
                objetoTransacao.PaymentStatusPayPal = transaction.Status.ToString();
                objetoTransacao.DataTransacao       = DateTime.Now;
                objetoTransacao.PayerIdPayPal       = transaction.Billing.Id;
                objetoTransacao.IdUsuario           = UsuarioLogado.IdUsuario;
                objetoTransacao.IdPerfil            = usuarioPerfil.IdUsuario;

                context.Transacao.Add(objetoTransacao);

                int salvou = context.SaveChanges();

                if (salvou == 1)
                {
                    //return RedirectToPage("/ProfilePhotos", new { Id = IdPerfil }); //Redirecionar para as fotos
                    return(new JsonResult(new { OK = true }, new Newtonsoft.Json.JsonSerializerSettings()
                    {
                    }));
                }
            }

            return(null);
        }