Ejemplo n.º 1
0
        public async Task <ActionResult <IVMSBackUser> > Post(IVMSBackUser iVMSBackUser)
        {
            try
            {
                if (IVMSBackUserExists(iVMSBackUser.Email))
                {
                    return(BadRequest(new DefaultData
                    {
                        success = false,
                        message = "Su rol ya se encuentra dado de alta"
                    }));
                }

                CurrentUserId = User.FindFirst(ClaimTypes.NameIdentifier).Value;

                var user = new IVMSBackUser();
                user.Name     = iVMSBackUser.Name;
                user.UserName = iVMSBackUser.Email;
                user.Email    = iVMSBackUser.Email;
                //await _userManager.CreateAsync(user, iVMSBackUser.Password);
                var result = await _userManager.CreateAsync(user, "Sysware2016@");

                string errors = string.Empty;

                if (!result.Succeeded)
                {
                    foreach (var error in result.Errors)
                    {
                        errors += error.Description + ", ";
                    }
                }

                if (!string.IsNullOrEmpty(errors))
                {
                    return(BadRequest(new DefaultData
                    {
                        success = false,
                        message = errors
                    }));
                }

                var role = await _roleManager.FindByIdAsync(iVMSBackUser.RoleID);

                await _userManager.AddToRoleAsync(user, role.Name);


                return(Ok(new DefaultData
                {
                    success = true
                }));
            }
            catch (Exception ex)
            {
                return(BadRequest(new DefaultData
                {
                    success = false,
                    message = ex.Message,
                }));
            }
        }
Ejemplo n.º 2
0
        public static async Task SeedCountriesAsync(IVMSBackContext context,
                                                    RoleManager <IVMSBackRole> roleManager,
                                                    UserManager <IVMSBackUser> userManager)
        {
            var roleAdmin = new IVMSBackRole();

            roleAdmin.Name = "Super Administrador";
            await roleManager.CreateAsync(roleAdmin);

            var role = new IVMSBackRole();

            role.Name = "Administrador";
            await roleManager.CreateAsync(role);

            role      = new IVMSBackRole();
            role.Name = "Monitorista";
            await roleManager.CreateAsync(role);

            role      = new IVMSBackRole();
            role.Name = "Conductor";
            await roleManager.CreateAsync(role);

            var user = new IVMSBackUser();

            user.Name     = "Gad Arenas";
            user.UserName = "******";
            user.Email    = "*****@*****.**";
            await userManager.CreateAsync(user, "Sysware2016");
        }
Ejemplo n.º 3
0
        private string GenerateTokenJwt(IVMSBackUser user)
        {
            user.SecurityStamp    = null;
            user.PasswordHash     = null;
            user.ConcurrencyStamp = null;
            user.PhoneNumber      = null;

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Role, user.Role.Name)
            };

            IdentityModelEventSource.ShowPII = true;

            var key     = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:JwtKey"]));
            var creds   = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expires = DateTime.Now.AddDays(Convert.ToDouble(Configuration["JWT:JwtExpireDays"]));

            var token = new JwtSecurityToken(
                Configuration["JWT:JwtIssuer"],
                Configuration["JWT:JwtIssuer"],
                claims,
                expires: expires,
                signingCredentials: creds
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new IVMSBackUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Ejemplo n.º 5
0
        private async Task LoadAsync(IVMSBackUser user)
        {
            var email = await _userManager.GetEmailAsync(user);

            Email = email;

            Input = new InputModel
            {
                NewEmail = email,
            };

            IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
        }
Ejemplo n.º 6
0
        private async Task LoadAsync(IVMSBackUser user)
        {
            var userName = await _userManager.GetUserNameAsync(user);

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;

            Input = new InputModel
            {
                PhoneNumber = phoneNumber
            };
        }
Ejemplo n.º 7
0
        public async Task <ActionResult <DefaultData> > Post(IVMSBackUser login)
        {
            try
            {
                if (login == null)
                {
                    return(BadRequest(new DefaultData
                    {
                        success = false,
                        message = "Por favor ingrese su email y contraseña"
                    }));
                }

                var result = await _signInManager.PasswordSignInAsync(login.UserName, login.Password, false, lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    var user = await _userManager.FindByEmailAsync(login.UserName);

                    var role = await _userManager.GetRolesAsync(user);

                    user.Role = await _roleManager.FindByNameAsync(role[0].ToString());

                    var token = GenerateTokenJwt(user);

                    return(Ok(new LoginResponse {
                        Token = token,
                        User = user,
                        success = true
                    }));
                }
                else
                {
                    return(Unauthorized(new LoginResponse
                    {
                        success = false,
                        message = "Por favor verifique su usuario y password"
                    }));
                }
            }
            catch (Exception ex) {
                return(Unauthorized(new LoginResponse
                {
                    success = false,
                    message = ex.Message
                }));
            }
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new IVMSBackUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Ejemplo n.º 9
0
        private async Task LoadSharedKeyAndQrCodeUriAsync(IVMSBackUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
Ejemplo n.º 10
0
        public async Task <ActionResult <IEnumerable <IVMSBackUser> > > GetAsync(int page, int start, int limit)
        {
            ResponseDefaultDataList response = new ResponseDefaultDataList();

            try
            {
                var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value;
                CurrentUser = await _userManager.FindByIdAsync(userId);

                var CurrentUserRole = await _userManager.GetRolesAsync(CurrentUser);

                List <Filter> filtros;
                var           filters = HttpContext.Request.Query["filter"].ToString();

                response.success = true;
                response.data    = new List <IVMSBackUser>();
                List <IVMSBackUser> records = new List <IVMSBackUser>();

                foreach (var role in await _roleManager.Roles.Where(x => x.Name == "Conductor" && x.DateEnd == null).ToListAsync())
                {
                    List <IVMSBackUser> users = new List <IVMSBackUser>();

                    if (CurrentUserRole[0] == "Super Administrador")
                    {
                        users = ((List <IVMSBackUser>) await _userManager.GetUsersInRoleAsync(role.Name)).Where(x => x.DateEnd == null).ToList();
                    }
                    else
                    {
                        var lines = await _context.IVMSBackUserLines
                                    .Include(x => x.Line)
                                    .Where(x => x.IVMSBackUserID.Contains(userId) && x.DateEnd == null && x.Line.DateEnd == null)
                                    .Select(x => x.Line).ToListAsync();

                        var usersFilter = await _context.IVMSBackUserLines
                                          .Include(x => x.IVMSBackUser)
                                          .Include(x => x.Line)
                                          .Where(x => x.DateEnd == null && lines.Contains(x.Line) && x.IVMSBackUser.DateEnd == null)
                                          .Select(x => x.IVMSBackUser).ToListAsync();

                        if (lines.Count > 0)
                        {
                            users = ((List <IVMSBackUser>) await _userManager.GetUsersInRoleAsync(role.Name))
                                    .Where(x => x.DateEnd == null && usersFilter.Contains(x))
                                    .ToList();
                        }
                    }
                }

                if (!string.IsNullOrEmpty(filters))
                {
                    filtros = JsonConvert.DeserializeObject <List <Filter> >(filters);

                    foreach (var filtro in filtros)
                    {
                        if (!string.IsNullOrEmpty(filtro.valor))
                        {
                            if (filtro.propiedad == "name")
                            {
                                records = records.Where(x => x.Name.ToUpper().Contains(filtro.valor.ToUpper())).ToList();
                            }
                        }
                    }
                }

                response.total = records.Count();
                response.data.AddRange(records.Skip((page - 1) * limit).Take(limit));
                return(Ok(response));
            }
            catch (Exception ex)
            {
                response.success = false;
                response.message = ex.Message;
                return(BadRequest(response));
            }
        }