Exemplo n.º 1
0
        public async Task <IActionResult> Edit(int id, [Bind("UserID,Name,Email,Password,Age,Timestamp")] MvcUser mvcUser)
        {
            if (id != mvcUser.UserID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(mvcUser);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!MvcUserExists(mvcUser.UserID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(mvcUser));
        }
Exemplo n.º 2
0
        public ActionResult Index
            (int pagina = 1, int idadeMin = 18, int idadeMax = 80, int tagsComum = 1, int colunas = 4, int qntPorPagina = 15)
        {
            if (pagina == 0)
            {
                pagina = 1;
            }
            //if (tagsComum == 0)
            //{
            //    tagsComum = 1;
            //}
            MvcUser        user  = (MvcUser)System.Web.HttpContext.Current.User;
            List <Usuario> users = new FiltroConhecerBLL().GetUsersComFiltro(idadeMin, idadeMax, tagsComum, user.ID);

            int numeroPaginas = GetNumeroPaginas(qntPorPagina, users);
            int skip          = (pagina - 1) * qntPorPagina;

            users = users.Skip(skip).Take(qntPorPagina).ToList();

            UsersConhecerPessoas modelo = new UsersConhecerPessoas()
            {
                Usuarios         = users,
                PaginaAtual      = pagina,
                NumeroTagsComum  = tagsComum,
                QtdPessoasPagina = qntPorPagina,
                IdadeMinima      = idadeMin,
                IdadeMaxima      = idadeMax,
                NumeroColunas    = colunas,
                NumeroPaginas    = numeroPaginas
            };

            return(View(modelo));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Create a new user
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task <string> AddUser(MvcUser user)
        {
            var dbUser = new ApplicationUser
            {
                UserName = user.UserName,
                Email    = user.Email
            };

            IdentityResult result;

            if (string.IsNullOrEmpty(user.Password))
            {
                result = await UserManager.CreateAsync(dbUser);
            }
            else
            {
                result = await UserManager.CreateAsync(dbUser, user.Password);
            }

            if (result.Succeeded)
            {
                dbUser = await UserManager.FindByEmailAsync(user.Email);

                if (dbUser != null)
                {
                    return(dbUser.Id);
                }
            }

            throw new Exception("Creating user failed. " + string.Join(",", result.Errors.ToArray()));
        }
Exemplo n.º 4
0
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (cookie != null)
            {
                FormsAuthenticationTicket ticket   = FormsAuthentication.Decrypt(cookie.Value);
                FormsIdentity             identity = new FormsIdentity(ticket);

                byte[]     buffer  = Convert.FromBase64String(ticket.UserData);
                UserLogado userLog = new UserLogado();
                using (Stream myStream = new MemoryStream(buffer))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    userLog = (UserLogado)formatter.Deserialize(myStream);
                }

                //MVCUser user = new MVCUser(identity, new string[] {"Adm","FInanceiro" });
                MvcUser user = new MvcUser(identity, null)
                {
                    ID             = userLog.ID,
                    Nome           = userLog.Nome,
                    PathFotoPerfil = userLog.PathFotoPerfil
                };

                HttpContext.Current.User = user;
            }
        }
Exemplo n.º 5
0
        public ActionResult SalvarCoordenadas(Coordenada coordenada)
        {
            MvcUser user = (MvcUser)System.Web.HttpContext.Current.User;
            BLLResponse <Coordenada> response = new CoordenadasBLL().SalvarCoordenadas(coordenada, user.ID);

            return(Json(new { sucesso = response.Sucesso, mensagem = response.Mensagem }));
        }
Exemplo n.º 6
0
        private string GetUserPicsFolder(MvcUser user, out string relativo)
        {
            string folder = Path.Combine(Server.MapPath("~/UserImages"), $"userperfil-{user.ID}");

            Directory.CreateDirectory(folder);
            relativo = $"/UserImages/userperfil-{user.ID}";
            return(folder);
        }
Exemplo n.º 7
0
        public ActionResult SalvarInformacoesPessoais(UsuarioViewModel userVM)
        {
            MvcUser user = (MvcUser)System.Web.HttpContext.Current.User;

            userVM.ID = user.ID;

            BLLResponse <Usuario> response = new UsuarioBLL().Update(userVM);

            return(Json(new { sucesso = response.Sucesso, mensagem = response.Mensagem }));
        }
Exemplo n.º 8
0
        public ActionResult Index()
        {
            MvcUser user = (MvcUser)System.Web.HttpContext.Current.User;
            BLLResponse <Usuario> response = new UsuarioBLL().LerPorId(user.ID);

            if (TempData["AcabouDeRegistrar"] != null)
            {
                ViewData["AcabouDeRegistrar"] = true;
            }
            return(View(response.Data));
        }
Exemplo n.º 9
0
        public async Task <IActionResult> Register([Bind("UserID,Name,Email,Password,Age,Timestamp")] MvcUser mvcUser)
        {
            if (ModelState.IsValid)
            {
                _context.Add(mvcUser);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(mvcUser));
        }
Exemplo n.º 10
0
        public async Task AddRolesToUser(MvcUser user)
        {
            await ClearUserRoles(user.Id);

            if (user.Roles?.Count() > 0)
            {
                string[] rolesName = user.Roles.Select(r => r.Name).ToArray();

                await this.UserManager.AddToRolesAsync(user.Id, rolesName);
            }
        }
Exemplo n.º 11
0
 public ActionResult SalvarFoto(string imgbase64)
 {
     if (!String.IsNullOrWhiteSpace(imgbase64))
     {
         MvcUser user     = (MvcUser)System.Web.HttpContext.Current.User;
         string  relativo = "";
         string  folder   = GetUserPicsFolder(user, out relativo);
         byte[]  imagem   = Convert.FromBase64String(imgbase64.Split(',')[1]);
         var     result   = new FotosUsuarioBLL().UpdateProfilePic(user.ID, folder, imagem, relativo);
     }
     return(RedirectToAction("Index"));
 }
Exemplo n.º 12
0
        private string GetPathFoto(HttpPostedFileBase foto, MvcUser user)
        {
            string folder = Path.Combine(Server.MapPath("~/UserImages"), $"userperfil-{user.ID}");

            Directory.CreateDirectory(folder);
            string path = Path.Combine(folder, Path.GetFileName(foto.FileName));

            foto.SaveAs(path);
            string pathRelativo = $"/UserImages/userperfil-{user.ID}/{Path.GetFileName(foto.FileName)}";

            return(pathRelativo);
        }
Exemplo n.º 13
0
        public ActionResult SalvarFotoDiretorio(HttpPostedFileBase foto)
        {
            MvcUser user = (MvcUser)System.Web.HttpContext.Current.User;

            if (foto != null && IsImagemValida(foto))
            {
                string pathRelativo = GetPathFoto(foto, user);
                var    result       = new FotosUsuarioBLL().AtualizarFotosAlbum(user.ID, pathRelativo);
                return(RedirectToAction("Index"));
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 14
0
        public async Task <IHttpActionResult> AddRolesToUser(MvcUser user)
        {
            try
            {
                await UserManagerBso.AddRolesToUser(user);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Exemplo n.º 15
0
        public async Task <IHttpActionResult> DeleteUser(MvcUser user)
        {
            try
            {
                await UserManagerBso.DeleteUser(user);

                return(Ok <string>(user.Id));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
Exemplo n.º 16
0
        public ActionResult AtualizarSenha(string senhaNova, string senhaAntiga)
        {
            MvcUser user    = (MvcUser)System.Web.HttpContext.Current.User;
            Usuario usuario = new Usuario
            {
                ID    = user.ID,
                Senha = senhaNova
            };

            BLLResponse <Usuario> response = new UsuarioBLL().UpdatePassword(usuario, senhaAntiga);

            return(Json(new { sucesso = response.Sucesso, mensagem = response.Mensagem }));
        }
Exemplo n.º 17
0
        //Método do WebServer que executa SEMPRE antes de qualquer Controller
        protected void Authenticate_Request()
        {
            HttpCookie cookie = Request.Cookies["putsCookie"];

            if (cookie != null)
            {
                FormsAuthenticationTicket ticket =
                    FormsAuthentication.Decrypt(cookie.Value);
                FormsIdentity identity = new FormsIdentity(ticket);
                MvcUser       user     = new MvcUser(identity, null);
                user.UserName = cookie.Name;
                string[] userData = ticket.UserData.Split(',');
                user.ID      = Convert.ToInt32(userData[0]);
                user.IsAdm   = Convert.ToBoolean(userData[1]);
                Context.User = user;
            }
        }
Exemplo n.º 18
0
        void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies["putsCookie"];

            if (cookie != null)
            {
                FormsAuthenticationTicket ticket =
                    FormsAuthentication.Decrypt(cookie.Value);
                FormsIdentity identity = new FormsIdentity(ticket);
                MvcUser       user     = new MvcUser(identity, new string[] { "Financeiro" });
                user.UserName = cookie.Name;
                string[] userData = ticket.UserData.Split(',');
                user.ID      = Convert.ToInt32(userData[0]);
                user.IsAdm   = Convert.ToBoolean(userData[1]);
                Context.User = user;
            }
        }
Exemplo n.º 19
0
        public async Task <IHttpActionResult> UpdateUser(MvcUser user)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    await UserManagerBso.UpdateUser(user);

                    return(Ok());
                }
                catch (Exception ex)
                {
                    return(InternalServerError(ex));
                }
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Exemplo n.º 20
0
        public async Task <IHttpActionResult> AddUser(MvcUser user)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    string userId = await UserManagerBso.AddUser(user);

                    return(Ok <string>(userId));
                }
                catch (Exception ex)
                {
                    return(InternalServerError(ex));
                }
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
Exemplo n.º 21
0
        public async Task <IActionResult> ExternalLoginCallback()
        {
            var result = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);

            var externalUserId = result.Principal.FindFirstValue("sub")
                                 ?? result.Principal.FindFirstValue(ClaimTypes.NameIdentifier)
                                 ?? throw new Exception("Cannot find external user id");

            var provider = result.Properties.Items["scheme"];

            var user = await userManager.FindByLoginAsync(provider, externalUserId);

            if (user == null)
            {
                var email = result.Principal.FindFirstValue("email")
                            ?? result.Principal.FindFirstValue(ClaimTypes.Email);

                if (email != null)
                {
                    user = new MvcUser {
                        UserName = email, Email = email
                    };
                    await userManager.CreateAsync(user);
                }

                await userManager.AddLoginAsync(user, new UserLoginInfo(provider, externalUserId, provider));
            }

            if (user == null)
            {
                return(View("Error"));
            }

            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            var claimsPrincipal = await claimsPrincipalFactory.CreateAsync(user);

            await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, claimsPrincipal);

            return(RedirectToAction("Index"));
        }
Exemplo n.º 22
0
        /// <summary>
        /// Update user
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task UpdateUser(MvcUser user)
        {
            var dbUser = await UserManager.FindByIdAsync(user.Id);

            if (dbUser == null)
            {
                return;
            }

            dbUser.Email    = user.Email;
            dbUser.UserName = user.UserName;
            UserManager.Update(dbUser);

            if (!string.IsNullOrEmpty(user.Password))
            {
                //reset password instead of changing it
                string token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                await UserManager.ResetPasswordAsync(user.Id, token, user.Password);
            }
        }
Exemplo n.º 23
0
        public async Task <IActionResult> Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByNameAsync(model.UserName);

                if (user == null)
                {
                    user = new MvcUser
                    {
                        Id       = Guid.NewGuid().ToString(),
                        UserName = model.UserName,
                        Email    = model.UserName
                    };
                    var result = await userManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        var token = await userManager.GenerateEmailConfirmationTokenAsync(user);

                        var confirmationEmail = Url.Action("ConfirmEmailAddress", "Home",
                                                           new { token = token, email = user.Email, Request.Scheme });

                        System.IO.File.WriteAllText("confirmationLink.txt", confirmationEmail);
                        return(View("Success"));
                    }
                    else
                    {
                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError("", error.Description);
                        }
                    }
                }
            }
            return(View());
        }
Exemplo n.º 24
0
 public ClienteController(MvcUser user) : base(user)
 {
 }
Exemplo n.º 25
0
        public async Task DeleteUser(MvcUser user)
        {
            var dbUser = await this.UserManager.FindByIdAsync(user.Id);

            await this.UserManager.DeleteAsync(dbUser);
        }
Exemplo n.º 26
0
 public QuartoController(MvcUser user) : base(user)
 {
 }
 public BaseAuthorizationController(MvcUser user)
 {
     this.CurrentUser = user;
 }