Exemple #1
0
        private void AddErrors(IdentityResult result, RegisterAnonymousViewModel model = null)
        {
            foreach (var error in result.Errors)
            {
                string sizeError = "";

                if (model != null)
                {
                    sizeError = validateEspanish(error, model);
                }

                if (sizeError.Length <= 0)
                {
                    ModelState.AddModelError("", error);
                }
            }
        }
Exemple #2
0
        private string validateEspanish(string mensaje, RegisterAnonymousViewModel model = null)
        {
            string sizeError = "";

            if (mensaje == ("Name " + model.UserName + " is already taken."))
            {
                sizeError += "1";
                ModelState.AddModelError("", "El Usuario " + model.UserName + " ya existe.");
            }
            if (mensaje.Substring(0, mensaje.IndexOf(" ")) == "Email")
            {
                sizeError += "2";
                ModelState.AddModelError("", "El Email " + model.Email + " ya fue ingresado.");
            }

            if (mensaje == ("Passwords must have at least one lowercase ('a'-'z')."))
            {
                sizeError += "3";
                ModelState.AddModelError("", "La contraseña debe contener al menos un caracter en minúscula ('a'-'z').");
            }

            return(sizeError);
        }
Exemple #3
0
        public async Task <IHttpActionResult> RegisterAnonymous(RegisterAnonymousViewModel model, Guid?visitorId = null)
        {
            try
            {
                var account = await _auth.AccountAnonymousCreateAsync(model.Password);

                if (object.Equals(account, null))
                {
                    return(AccountNotFound());
                }

                var client = GetClient(model.client_id);
                if (object.Equals(client, null))
                {
                    return(ClientNotFound());
                }

                var identity   = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
                var session    = Guid.NewGuid();
                var properties = new Dictionary <string, string>
                {
                    { "session", session.ToString("N") }
                };

                identity.AddClaim(ClaimTypes.NameIdentifier, account.Id);
                identity.AddClaim(ClaimTypes.Name, account.Email);
                identity.AddClaims(account, client);

                var ticket = new AuthenticationTicket(identity, new AuthenticationProperties(properties));

                var issued  = DateTime.UtcNow;
                var expires = issued.Add(Startup.OAuthServerOptions.AccessTokenExpireTimeSpan);

                var token = new SessionToken
                {
                    Id            = session,
                    AccountId     = account.Id,
                    ClientId      = client.Id,
                    ClientVersion = model.client_version,
                    IssuedUtc     = issued,
                    ExpiresUtc    = expires
                };

                ticket.Properties.IssuedUtc  = issued;
                ticket.Properties.ExpiresUtc = expires;

                token.ProtectedTicket = Startup.OAuthServerOptions.AccessTokenFormat.Protect(ticket);

                var scopeWorker = SaaSScopeWorkerFactory.Create("webeditor", _auth, _authProduct);

                await scopeWorker.SessionTokenInsertAsync(token, null);

                await _auth.AccountVisitorIdSetAsync(account, visitorId);

                return(Ok(new
                {
                    access_token = token.ProtectedTicket,
                    token_type = ticket.Identity.AuthenticationType,
                    expires_in = (int)(ticket.Properties.ExpiresUtc - ticket.Properties.IssuedUtc).Value.TotalSeconds,
                    refresh_token = token.Id.ToString("N"),
                    issued = ticket.Properties.IssuedUtc,
                    expires = ticket.Properties.ExpiresUtc,
                    email = account.Email,
                    firstName = account.FirstName,
                    lastName = account.LastName,
                    status = account.GetStatus()
                }));
            }
            catch (Exception exc) { return(Request.HttpExceptionResult(exc)); }
        }
Exemple #4
0
        public async Task <ActionResult> Register(RegisterAnonymousViewModel model)
        {
            if (ModelState.IsValid && this.IsCaptchaValid("Captcha no válido."))
            {
                Empresa empresa = new Empresa();
                empresa.Nombre = model.NombreEmpresa;
                empresa.Codigo = model.Nit;
                empresa.Correo = model.CorreoEmpresa;
                empresa.Activo = true;


                var idEmpresa = 0;
                try
                {
                    dbActiveContext.Empresas.Add(empresa);
                    dbActiveContext.SaveChanges();
                    idEmpresa = empresa.EmpresaID;
                }
                catch (Exception ex) {
                    ModelState.AddModelError("Error crear empresa", new Exception("Error al crear empresa"));
                }


                //SE: agregar campos personalizados para creacion de usuario.
                var user = new ApplicationUser
                {
                    UserName    = model.UserName,
                    Email       = model.Email,
                    EmpresaID   = idEmpresa,
                    PhoneNumber = model.PhoneNumber,
                    State       = ESTADO_USUARIO,
                };

                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                    //SE: excluir roles
                    user.EmpresaID = idEmpresa;
                    await this.UserManager.AddToRoleAsync(user.Id, PERFIL_USUARIO);

                    await this.UserManager.UpdateAsync(user);

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    return(RedirectToAction("Index", "Home", new { area = "Usuario" }));
                }
                else
                {
                    if (idEmpresa != 0)
                    {
                        dbActiveContext.Empresas.Remove(empresa);
                        dbActiveContext.SaveChanges();
                    }
                }
                AddErrors(result, model);
            }
            //SE:agregar lista de roles
            ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains(PERFIL_EXCLUIDO_EN_CREACION))
                                          .ToList(), "Name", "Name");
            ViewBag.EmpresaID = new SelectList(dbActiveContext.Empresas, "EmpresaID", "Nombre");

            // If we got this far, something failed, redisplay form
            return(View(model));
        }