Beispiel #1
0
        private ApplicationIdentityUser CreateUser(string userName, string password)
        {
            var user = UserManager.FindByNameAsync(userName).Result;

            var identityResult = new IdentityResult();

            if (user == null)
            {
                user = new ApplicationIdentityUser {
                    UserName = userName, Email = userName
                };
                identityResult = UserManager.CreateAsync(user, password).Result;

                if (identityResult.Succeeded)
                {
                    identityResult = UserManager.SetLockoutEnabledAsync(user.Id, false).Result;
                }
            }

            UserManager.GeneratePasswordResetToken(user.Id);
            return(user);
        }
Beispiel #2
0
        public IdentityResult Register(RegisterViewModel user, bool isHost, bool isAdmin)
        {
            ApplicationIdentityUser identityUser =
                Mapper.Map <RegisterViewModel, ApplicationIdentityUser>(user);

            IdentityResult identityResult = TheUnitOfWork.Account.Register(identityUser);

            if (!isAdmin)
            {
                if (isHost)
                {
                    var host = Mapper.Map <ApplicationIdentityUser, HostUser>(identityUser);
                    TheUnitOfWork.Host.AddAsAHost(host);
                }
                else
                {
                    var client = Mapper.Map <ApplicationIdentityUser, ClientUser>(identityUser);
                    TheUnitOfWork.Client.AddAsAClient(client);
                }
            }
            return(identityResult);
        }
        public void InitializeIdentityForEf(ApplicationDbContext db)
        {
            // This is only for testing purpose
            const string name     = "*****@*****.**";
            const string password = "******";
            const string roleName = "Admin";
            var          applicationRoleManager = IdentityFactory.CreateRoleManager(db);
            var          applicationUserManager = IdentityFactory.CreateUserManager(db);
            //Create Role Admin if it does not exist
            var role = applicationRoleManager.FindByName(roleName);

            if (role == null)
            {
                role = new ApplicationIdentityRole {
                    Name = roleName
                };
                applicationRoleManager.Create(role);
            }

            var user = applicationUserManager.FindByName(name);

            if (user == null)
            {
                user = new ApplicationIdentityUser {
                    UserName = name, Email = name
                };
                applicationUserManager.Create(user, password);
                applicationUserManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = applicationUserManager.GetRoles(user.Id);

            if (!rolesForUser.Contains(role.Name))
            {
                applicationUserManager.AddToRole(user.Id, role.Name);
            }
            db.SaveChanges();
        }
        protected void InitRoleAndUser(ApplicationDbContext context)
        {
            var password = "******";

            var userManager = new ApplicationUserManager(new ApplicationUserStore(context));
            var roleManager = new ApplicationRoleManager(new ApplicationRoleStore(context));

            roleManager.Create(new ApplicationIdentityRole
            {
                Name           = SystemRole.SuperUser.ToString(),
                Description    = SystemRole.SuperUser.GetDescription(),
                IsSystemConfig = true,
                InsertedOnUtc  = DateTime.UtcNow
            });

            var superuser = new ApplicationIdentityUser()
            {
                Email          = _SuperUserEmail,
                EmailConfirmed = true,
                UserName       = _SuperUserEmail,
                FirstName      = "Super",
                MiddleName     = "",
                LastName       = "User",
                InsertedOnUtc  = DateTime.UtcNow,
            };

            var result = userManager.Create(superuser, password);

            if (result.Succeeded)
            {
                superuser.LastModifiedUserId = superuser.Id;
                result = userManager.Update(superuser);
                if (result.Succeeded)
                {
                    userManager.AddToRole(superuser.Id, SystemRole.SuperUser.ToString());
                }
            }
        }
Beispiel #5
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new ApplicationIdentityUser {
                    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);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { 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>.");

                    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());
        }
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new ApplicationIdentityUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

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

                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
Beispiel #7
0
        public async Task <ActionResult <LoginResponse> > Login([FromBody] LoginRequest loginModel)
        {
            _logger.LogInformation("User with email {Email} attempting to login", loginModel.Email);

            // Check whether the user who wants to log in exists
            ApplicationIdentityUser identityUser = await _userManager
                                                   .FindByEmailAsync(loginModel.Email).ConfigureAwait(false);

            if (identityUser != null) // if exists
            {
                // validate password
                bool correctPassword = await _userManager
                                       .CheckPasswordAsync(identityUser, loginModel.Password)
                                       .ConfigureAwait(false);

                if (correctPassword)
                {
                    User user = (await _userRepository
                                 .GetAllByAsync(u => u.IdentityId.Equals(identityUser.Id, StringComparison.OrdinalIgnoreCase))
                                 .ConfigureAwait(false))
                                .First();

                    // Create access token for successfully validated user
                    AccessToken accessToken = await GenerateAccessToken(user);

                    return(Ok(new LoginResponse(accessToken)));
                }

                _logger.
                LogInformation("User with email {Email} attempted to login with the wrong credentials",
                               loginModel.Email);
            }

            _logger.LogInformation("Login failed for user with email {0} ", loginModel.Email);

            // The user does not exist in our system so the request is unauthorized
            return(Unauthorized());
        }
        public static Claim[] GetUserClaims(ApplicationIdentityUser user, List <string> roles = null)
        {
            var claims = new List <Claim>
            {
                new Claim("user_id", user.Id ?? ""),
                new Claim(JwtClaimTypes.Name, (!string.IsNullOrEmpty(user.UserName) && !string.IsNullOrEmpty(user.UserName)) ? (user.FirstName + " " + user.LastName) : ""),
                new Claim(JwtClaimTypes.GivenName, user.FirstName ?? ""),
                new Claim(JwtClaimTypes.FamilyName, user.LastName ?? ""),
                new Claim(JwtClaimTypes.Email, user.Email ?? ""),
            };

            if (roles != null && roles.Count > 0)
            {
                foreach (var role in roles)
                {
                    claims.Add(new Claim(ClaimsIdentity.DefaultRoleClaimType, role));
                    claims.Add(new Claim(JwtClaimTypes.Role, role));
                    claims.Add(new Claim(ClaimTypes.Role, role));
                }
            }

            return(claims.ToArray());
        }
        public string GenerateJwtToken(string email, ApplicationIdentityUser user)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
            };

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

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

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Beispiel #10
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationIdentityUser user = await _userManager.FindByNameAsync(model.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user.Id)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await _userManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await _userManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Beispiel #11
0
        public async Task <IActionResult> DownloadFileStream(Models.FileModel fileModel)
        {
            if (System.IO.File.Exists(fileModel.Path))
            {
                FileStream              sourceStream            = new FileStream(fileModel.Path, FileMode.Open, FileAccess.Read, System.IO.FileShare.Read, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan);
                ThrottledStream         destinationStreamStream = null;
                ApplicationIdentityUser user = null;
                if (HttpContext.User != null)
                {
                    user = await _userManager.GetUserAsync(HttpContext.User);

                    if (user != null)
                    {
                        destinationStreamStream = new ThrottledStream(sourceStream, kbpsLogged);
                    }
                }

                if (destinationStreamStream == null)
                {
                    destinationStreamStream = new ThrottledStream(sourceStream, kbps);
                }

                await LoggerDownload(user, fileModel);

                FileStreamResult fileStreamResult = new FileStreamResult(destinationStreamStream, FindMimeHelpers.GetMimeFromFile(fileModel.Path));
                fileStreamResult.FileDownloadName = fileModel.TrustedName;
                fileStreamResult.LastModified     = fileModel.UploadDT;

                return(fileStreamResult);
            }
            else
            {
                ModelState.AddModelError("Error", $"The request couldn't be processed (Error 0).");
                return(NotFound(ModelState));
            }
        }
Beispiel #12
0
        public ActionResult Register(RegisterViewModel newUser, bool isHost = false)
        {
            if (!ModelState.IsValid)
            {
                return(View(newUser));
            }
            IdentityResult result = accountAppService.Register(newUser, isHost, User.IsInRole("Admin"));

            if (result.Succeeded)
            {
                ApplicationIdentityUser registeredUser = accountAppService.Find(newUser.UserName, newUser.PasswordHash);

                if (User.IsInRole("Admin"))
                {
                    accountAppService.AssignToRole(registeredUser.Id, "Admin");
                }
                else
                {
                    if (isHost)
                    {
                        accountAppService.AssignToRole(registeredUser.Id, "Host");
                    }
                    else
                    {
                        accountAppService.AssignToRole(registeredUser.Id, "User");
                        ShoppingCartAppService.Insert(registeredUser.Id);
                    }
                }
                return(RedirectToAction("Login"));
            }
            else
            {
                ModelState.AddModelError("", result.Errors.FirstOrDefault());
                return(View(newUser));
            }
        }
Beispiel #13
0
        public async Task <Int32> InitPlayerAsync(ApplicationIdentityUser user)
        {
            int AspNetUserId = user.Id;

            SqlParameter[] @params =
            {
                new SqlParameter("@returnVal",    SqlDbType.Int)
                {
                    Direction = ParameterDirection.Output
                },
                new SqlParameter("@AspNetUserId", SqlDbType.Int)
                {
                    Direction = ParameterDirection.Input,Value         = AspNetUserId
                },
            };

            await context.Database.ExecuteSqlRawAsync("EXEC @returnVal=[dbo].[InitializeNewRegistrationPlayer] @AspNetUserId", @params);

            int result = Convert.ToInt32(@params[0].Value);

            await Task.FromResult(result);

            return(result);
        }
Beispiel #14
0
        public ApplicationIdentityUser Find(string username, string password)
        {
            ApplicationIdentityUser result = manager.Find(username, password);

            return(result);
        }
Beispiel #15
0
        public async Task <ActionResult <ResultData> > AddUser([FromBody] UserAddDto userDto)
        {
            if (userDto.UserName == null || userDto.Password == null)
            {
                return(BadRequest());
            }
            {
                var user = await _userManager.FindByNameAsync(userDto.UserName);

                if (user != null)
                {
                    return(new ResultData(ReturnCode.Error, -1, "用户已存在", null));
                }
                string today       = DateTime.Now.ToString("yyyyMMdd");
                var    lastTeacher = _teacherRepository
                                     .LoadEntities(o => o.TeacherId.ToString().StartsWith(today))
                                     .LastOrDefault();
                int teacherId;

                if (lastTeacher == null)
                {
                    teacherId = Convert.ToInt32(today + "00");
                }
                else
                {
                    string lastTwoChar = lastTeacher.TeacherId.ToString().Substring(lastTeacher.TeacherId.ToString().Length - 2, 2);
                    int    index       = Convert.ToInt32(lastTwoChar.StartsWith("0") ? lastTwoChar.Substring(1, 1) : lastTwoChar);
                    if (index < 99)
                    {
                        index++;
                        if (index.ToString().Length == 1)
                        {
                            teacherId = Convert.ToInt32(today + "0" + index.ToString());
                        }
                        else
                        {
                            teacherId = Convert.ToInt32(today + index.ToString());
                        }
                    }
                    else
                    {
                        return(new ResultData(ReturnCode.Error, -1, "每天只能添加100个用户", null));
                    }
                }
                user = new ApplicationIdentityUser
                {
                    UserName = userDto.UserName,
                    Teacher  = new Teacher
                    {
                        TeacherId = teacherId,
                    }
                };
                var result = await _userManager.CreateAsync(user, userDto.Password);

                if (result.Succeeded)
                {
                    return(new ResultData(ReturnCode.Succeed, -1, "添加成功", teacherId));
                }
                return(new ResultData(ReturnCode.Error, -1, "添加失败", null));
            }
        }
Beispiel #16
0
 public void ShoppingCartSetup()
 {
     accountAppService      = new AccountAppService();
     shoppingCartAppService = new ShoppingCartAppService();
     user = accountAppService.Find("TestUser", "TestUser");
 }
 public static AppUser CopyApplicationIdentityUserProperties(this AppUser appUser, ApplicationIdentityUser applicationIdentityUser)
 {
     if (appUser == null)
     {
         return(null);
     }
     if (applicationIdentityUser == null)
     {
         return(null);
     }
     appUser.UserName             = applicationIdentityUser.UserName;
     appUser.Id                   = applicationIdentityUser.Id;
     appUser.AccessFailedCount    = applicationIdentityUser.AccessFailedCount;
     appUser.Email                = applicationIdentityUser.Email;
     appUser.EmailConfirmed       = applicationIdentityUser.EmailConfirmed;
     appUser.LockoutEnabled       = applicationIdentityUser.LockoutEnabled;
     appUser.LockoutEndDateUtc    = applicationIdentityUser.LockoutEndDateUtc;
     appUser.PasswordHash         = applicationIdentityUser.PasswordHash;
     appUser.PhoneNumber          = applicationIdentityUser.PhoneNumber;
     appUser.PhoneNumberConfirmed = applicationIdentityUser.PhoneNumberConfirmed;
     appUser.SecurityStamp        = applicationIdentityUser.SecurityStamp;
     appUser.TwoFactorEnabled     = applicationIdentityUser.TwoFactorEnabled;
     foreach (var claim in applicationIdentityUser.Claims)
     {
         appUser.Claims.Add(new ApplicationUserClaim
         {
             ClaimType  = claim.ClaimType,
             ClaimValue = claim.ClaimValue,
             Id         = claim.Id,
             UserId     = claim.UserId
         });
     }
     foreach (var role in applicationIdentityUser.Roles)
     {
         appUser.Roles.Add(role.ToApplicationUserRole());
     }
     foreach (var login in applicationIdentityUser.Logins)
     {
         appUser.Logins.Add(new ApplicationUserLogin
         {
             LoginProvider = login.LoginProvider,
             ProviderKey   = login.ProviderKey,
             UserId        = login.UserId
         });
     }
     return(appUser);
 }
        //Create [email protected] with password=Admin@123456 in the Admin role
        public void InitializeIdentityForEF(AspnetIdentityWithOnionContext db)
        {
            // This is only for testing purpose
            const string name     = "*****@*****.**";
            const string password = "******";

            string[] roleName = new string[] { "Admin", "Anonim", "Manager", "User" };
            var      applicationRoleManager = IdentityFactory.CreateRoleManager(db);
            var      applicationUserManager = IdentityFactory.CreateUserManager(db);
            //Create Role Admin if it does not exist

            ApplicationIdentityRole role;

            foreach (var item in roleName)
            {
                role = new ApplicationIdentityRole {
                    Name = item
                };
                applicationRoleManager.Create(role);
                role = null;
            }
            //var role = applicationRoleManager.FindByName(roleName);
            //if (role == null)
            //{
            //    role = new ApplicationIdentityRole { Name = roleName };
            //    applicationRoleManager.Create(role);
            //}

            var user = applicationUserManager.FindByName(name);

            if (user == null)
            {
                user = new ApplicationIdentityUser {
                    UserName = name, Email = name
                };
                applicationUserManager.Create(user, password);
                applicationUserManager.SetLockoutEnabled(user.Id, false);
            }

            // Add user admin to Role Admin if not already added
            var rolesForUser = applicationUserManager.GetRoles(user.Id);

            foreach (var item in roleName)
            {
                if (!rolesForUser.Contains(item))
                {
                    applicationUserManager.AddToRole(user.Id, item);
                }
            }

            var context = new AspnetIdentityWithOnionContext("name=AppContext", new DebugLogger());
            //var image = new Image { Path = "http://lorempixel.com/400/200/" };
            //context.Set<Image>().Add(image);

            //context.Set<Category>().Add(new Category { Name = "Cameras", IsActive = true, Path = "6a81942d-d825-4c18-97ca-4a5a906c68ad.jpg" });
            //context.Set<Category>().Add(new Category { Name = "BagsCase", IsActive = true, Path = "49307dd0-7ada-4e12-b1e9-e5040269288f.jpg" });
            //context.Set<Category>().Add(new Category { Name = "Accessuare", IsActive = true, Path = "1c68860a-3b9a-4278-90ce-0b0237ec4898.jpg" });

            //context.Set<SubCategory>().Add(new SubCategory { Name = "SLR Cameras", })
            //for (var i = 0; i < 10; i++)
            //{
            //    context.Set<Product>().Add(new Product { Name = "My Product", Price = 35});

            //}
            //context.Set<Category>().Add(new Category { Name = "ForExample", IsActive = true });
            //context.SaveChanges();
        }
 private IList <Claim> SetClaims(ApplicationIdentityUser user, TokenType tokenType)
 {
     throw new NotImplementedException();
 }
Beispiel #20
0
        public async Task <ActionResult> Users_Create([DataSourceRequest] DataSourceRequest request, ApplicationIdentityUser user)
        {
            if (ModelState.IsValid)
            {
                var user_created = await _userManager.CreateAsync(user);

                if (user_created.Succeeded)
                {
                    return(Json(new[] { user }.ToDataSourceResult(request, ModelState)));
                }
            }
            return(null);
        }
Beispiel #21
0
        private async Task <Models.FileModel> SaveInDb(string remoteIpAddress, string fileNameFinaliy, string fileNameForDisplay, string fileNameForFileStorage, long contentType, string mimeType)
        {
            var ipInfo = await new IpDataServlet(remoteIpAddress).GetIpInfo();

            var fileUploaded = new FileModel
            {
                CreationDateTime = DateTime.UtcNow,
                Id          = Guid.NewGuid(),
                Size        = contentType,
                Name        = fileNameForDisplay,
                StorageName = fileNameForFileStorage,
                Type        = mimeType,
                Hash        = CreateHashFile(fileNameForDisplay, fileNameForFileStorage, remoteIpAddress, contentType),

                Asn           = ipInfo.Asn,
                AsnDomain     = ipInfo.AsnDomain,
                AsnName       = ipInfo.AsnName,
                AsnRoute      = ipInfo.AsnRoute,
                AsnType       = ipInfo.AsnType,
                CallingCode   = ipInfo.CallingCode,
                City          = ipInfo.City,
                ContinentCode = ipInfo.ContinentCode,
                ContinentName = ipInfo.ContinentName,
                CountryCode   = ipInfo.CountryCode,
                CountryName   = ipInfo.CountryName,
                Ip            = ipInfo.Ip,
                Latitude      = ipInfo.Latitude,
                Longitude     = ipInfo.Longitude,
                Organisation  = ipInfo.Organisation,
                Postal        = ipInfo.Postal,
                Region        = ipInfo.Region,
                RegionCode    = ipInfo.RegionCode,
                TimeZone      = ipInfo.TimeZone,
                Languages     = ipInfo.Languages
            };

            try
            {
                if (mimeType == "application/octet-stream" || string.IsNullOrEmpty(mimeType))
                {
                    mimeType = FindMimeHelpers.GetMimeFromFile(fileNameFinaliy);
                }

                if (mimeType == "application/octet-stream" || string.IsNullOrEmpty(mimeType))
                {
                    if (FindMimeHelpers.ListOfMimeType == null || FindMimeHelpers.ListOfMimeType.Count <= 0)
                    {
                        FindMimeHelpers.ListOfMimeType = _context.PermittedExtension
                                                         .Select(x => new { x.Extension, x.Description })
                                                         .ToDictionary(x => x.Extension, x => x.Description);
                    }

                    fileUploaded.Type = FindMimeHelpers.GetMimeFromExtensions(Path.GetExtension(fileNameForDisplay).ToLowerInvariant());
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Erro para recuperar o MineType : " + ex.Message);

                if (FindMimeHelpers.ListOfMimeType == null || FindMimeHelpers.ListOfMimeType.Count <= 0)
                {
                    FindMimeHelpers.ListOfMimeType = _context.PermittedExtension
                                                     .Select(x => new { x.Extension, x.Description })
                                                     .ToDictionary(x => x.Extension, x => x.Description);
                }

                fileUploaded.Type = FindMimeHelpers.GetMimeFromExtensions(Path.GetExtension(fileNameForDisplay).ToLowerInvariant());
            }

            if (string.IsNullOrEmpty(fileUploaded.Type))
            {
                fileUploaded.Type = "application/octet-stream";
            }

            //Salvar no Banco de Dados
            await _context.Files.AddAsync(fileUploaded);

            await _context.SaveChangesAsync();

            ApplicationIdentityUser user = null;

            try
            {
                if (HttpContext.User != null)
                {
                    user = await _userManager.GetUserAsync(HttpContext.User);

                    if (user != null)
                    {
                        await _context.FilesUsers.AddAsync(new FileUserModel
                        {
                            Id               = Guid.NewGuid(),
                            FileId           = fileUploaded.Id,
                            UserId           = user.Id,
                            CreationDateTime = DateTime.Now
                        });

                        await _context.SaveChangesAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Erro para associar o arquivo {fileUploaded.Id} ao usuário {user?.Id} - {ex}");
            }

            return(new Models.FileModel
            {
                Hash = fileUploaded.Hash,
                Id = fileUploaded.Id,
                Size = fileUploaded.Size,
                UntrustedName = fileUploaded.Name,
                UploadDT = fileUploaded.CreationDateTime
            });
        }
Beispiel #22
0
        public static void Initialise(IServiceProvider serviceProvider)
        {
            using (IServiceScope scope = serviceProvider.CreateScope())
            {
                ApplicationIdentityDbContext applicationIdentityDbContext =
                    scope.ServiceProvider.GetRequiredService <ApplicationIdentityDbContext>();
                ApplicationDbContext applicationDbContext =
                    scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();

                applicationDbContext.Database.Migrate();
                applicationIdentityDbContext.Database.Migrate();

                UserManager <ApplicationIdentityUser> userManager =
                    scope.ServiceProvider
                    .GetRequiredService <UserManager <ApplicationIdentityUser> >();

                ApplicationIdentityUser identityUser = userManager
                                                       .FindByEmailAsync("*****@*****.**")
                                                       .GetAwaiter()
                                                       .GetResult();

                if (identityUser == null)
                {
                    identityUser = new ApplicationIdentityUser
                    {
                        Email     = "*****@*****.**",
                        UserName  = "******",
                        FirstName = "Jane",
                        LastName  = "Doe"
                    };

                    IdentityResult result = userManager
                                            .CreateAsync(identityUser, "P@ssw0rd")
                                            .GetAwaiter()
                                            .GetResult();

                    if (result.Succeeded)
                    {
                        IMapper mapper = scope.ServiceProvider.GetRequiredService <IMapper>();
                        User    user   = mapper.Map <User>(identityUser);
                        user.Id         = new Guid("25320c5e-f58a-4b1f-b63a-8ee07a840bdf");
                        user.PhoneBooks = new List <PhoneBook>
                        {
                            new PhoneBook
                            {
                                Id               = new Guid("c7ba6add-09c4-45f8-8dd0-eaca221e5d93"),
                                Title            = "The Family",
                                Description      = "This phone book contains the contact details for my family",
                                PhoneBookEntries = new List <PhoneBookEntry>
                                {
                                    new PhoneBookEntry
                                    {
                                        Id           = new Guid("a3749477-f823-4124-aa4a-fc9ad5e79cd6"),
                                        FirstName    = "Jack",
                                        LastName     = "Tenrec",
                                        PhoneNumber  = "+27219038278",
                                        EmailAddress = "*****@*****.**",
                                        Address      = "8 Zebra Close, Kuils River"
                                    },
                                    new PhoneBookEntry
                                    {
                                        Id           = new Guid("70a1f9b9-0a37-4c1a-99b1-c7709fc64167"),
                                        FirstName    = "Hannah",
                                        LastName     = "Dundee",
                                        PhoneNumber  = "+27219038279",
                                        EmailAddress = "*****@*****.**",
                                        Address      = "13 Skyvue Drive, Kuils River"
                                    },
                                    new PhoneBookEntry
                                    {
                                        Id           = new Guid("60188a2b-2784-4fc4-8df8-8919ff838b0b"),
                                        FirstName    = "Mess",
                                        LastName     = "O",
                                        PhoneNumber  = "+27219038280",
                                        EmailAddress = "*****@*****.**",
                                        Address      = "221 Main Road, West Bank"
                                    },
                                    new PhoneBookEntry
                                    {
                                        Id           = new Guid("76053df4-6687-4353-8937-b45556748abe"),
                                        FirstName    = "Mustapha",
                                        LastName     = "P",
                                        PhoneNumber  = "+27219038281",
                                        EmailAddress = "*****@*****.**",
                                        Address      = "54 Robert Street, Blackheath"
                                    },
                                    new PhoneBookEntry
                                    {
                                        Id           = new Guid("447eb762-95e9-4c31-95e1-b20053fbe215"),
                                        FirstName    = "Ginzo",
                                        LastName     = "Ninja",
                                        PhoneNumber  = "+27219038282",
                                        EmailAddress = "*****@*****.**",
                                        Address      = "19 Fernkloof Crescent, West Bank"
                                    }
                                }
                            }
                        };
                        applicationDbContext.Users.Add(user);
                        applicationDbContext.SaveChanges();
                    }
                }
            }
        }
Beispiel #23
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 ApplicationIdentityUser {
                    UserName = Input.Email, Email = Input.Email
                };

                if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Name))
                {
                    user.ContactName = info.Principal.FindFirstValue(ClaimTypes.Name);
                }

                var result = await _userManager.CreateAsync(user);

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

                    if (result.Succeeded)
                    {
                        _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>.");

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }));
                        }

                        await _signInManager.SignInAsync(user, isPersistent : false, info.LoginProvider);

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

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Beispiel #24
0
        public void SeedAdmin(UserManager <ApplicationIdentityUser> userManager)
        {
            // ADD SUPERUSER
            if (userManager.FindByEmailAsync(SuperAdminUserName).Result == null)
            {
                ApplicationIdentityUser user = new ApplicationIdentityUser();
                user.UserName       = SuperAdminUserName;
                user.Email          = SuperAdminUserName;
                user.ContactName    = "Super Admin User";
                user.EmailConfirmed = true;

                IdentityResult result = userManager.CreateAsync(user, SuperAdminPassword).Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, RoleType.SuperAdmin.ToString()).Wait();
                }
            }

            // ADD ADMINUSER
            if (userManager.FindByEmailAsync(AdminUserName).Result == null)
            {
                ApplicationIdentityUser user = new ApplicationIdentityUser();
                user.UserName       = AdminUserName;
                user.Email          = AdminUserName;
                user.ContactName    = "Admin User";
                user.EmailConfirmed = true;

                IdentityResult result = userManager.CreateAsync(user, AdminPassword).Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, RoleType.Admin.ToString()).Wait();
                }
            }

            // ADD RESTIDENT
            if (userManager.FindByEmailAsync(ResidentUserName).Result == null)
            {
                ApplicationIdentityUser user = new ApplicationIdentityUser();
                user.UserName       = ResidentUserName;
                user.Email          = ResidentUserName;
                user.ContactName    = "Resident User";
                user.EmailConfirmed = true;

                IdentityResult result = userManager.CreateAsync(user, ResidentPassword).Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, RoleType.Resident.ToString()).Wait();
                }
            }

            // ADD READONLYUSER (has access to all non personal info but can't edit anything)
            if (userManager.FindByEmailAsync(ReadOnlyUserName).Result == null)
            {
                ApplicationIdentityUser user = new ApplicationIdentityUser();
                user.UserName       = ReadOnlyUserName;
                user.Email          = ReadOnlyUserName;
                user.ContactName    = "Read Only User";
                user.EmailConfirmed = true;

                IdentityResult result = userManager.CreateAsync(user, ReadOnlyPassword).Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, RoleType.ReadOnlyUser.ToString()).Wait();
                }
            }
        }
Beispiel #25
0
        protected override void Seed(DAL.ApplicationDBContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

            ApplicationRoleManager roleManager = new ApplicationRoleManager(context);

            roleManager.Create(new IdentityRole("Admin"));
            roleManager.Create(new IdentityRole("User"));
            roleManager.Create(new IdentityRole("Host"));


            ApplicationUserManager manager = new ApplicationUserManager(context);

            var admin = manager.Find("admin", "admin");

            if (admin == null)
            {
                ApplicationIdentityUser user =
                    new ApplicationIdentityUser()
                {
                    UserName     = "******",
                    PasswordHash = "admin",
                };

                user.PasswordHash = manager.PasswordHasher.HashPassword(user.PasswordHash);
                manager.Create(user);
                manager.AddToRole(user.Id, "Admin");
            }

            //User For Unit Testing
            var testUser = manager.Find("TestUser", "TestUser");

            if (testUser == null)
            {
                ApplicationIdentityUser user =
                    new ApplicationIdentityUser()
                {
                    UserName     = "******",
                    PasswordHash = "TestUser",
                };

                user.PasswordHash = manager.PasswordHasher.HashPassword(user.PasswordHash);
                manager.Create(user);
                manager.AddToRole(user.Id, "User");

                ApplicationIdentityUser registeredUser = manager.Find("TestUser", "TestUser");
                context.ClientUsers.Add(new User.ClientUser {
                    Id = registeredUser.Id
                });
                context.ShoppingCarts.Add(new ShoppingCart {
                    ClientId = registeredUser.Id
                });
                context.SaveChanges();
            }

            //Host For Unit Testing
            var testHost = manager.Find("TestHost", "TestHost");

            if (testHost == null)
            {
                ApplicationIdentityUser user =
                    new ApplicationIdentityUser()
                {
                    UserName     = "******",
                    PasswordHash = "TestHost",
                };

                user.PasswordHash = manager.PasswordHasher.HashPassword(user.PasswordHash);
                manager.Create(user);
                manager.AddToRole(user.Id, "Host");
                ApplicationIdentityUser registeredUser = manager.Find("TestHost", "TestHost");

                context.HostUsers.Add(new User.HostUser {
                    Id = registeredUser.Id
                });
                context.SaveChanges();
            }



            //AccountAppService accountAppService = new AccountAppService();
            //shoppingCartAppService = new ShoppingCartAppService();


            //RegisterViewModel newUser = new RegisterViewModel
            //{
            //    UserName = "******",
            //    Email = "*****@*****.**",
            //    PasswordHash = "123456",
            //    ConfirmPassword = "******",
            //    age = Enum_Age.Under16,
            //    SSN = "123456789"
            //};

            //IdentityResult result = accountAppService.Register(newUser, false, false);
            //ApplicationIdentityUser registeredUser = accountAppService.Find(newUser.UserName, newUser.PasswordHash);
            //accountAppService.AssignToRole(registeredUser.Id, "User");
            //shoppingCartAppService.Insert(registeredUser.Id);
        }
 public ArticleViewModel()
 {
     Author = new ApplicationIdentityUser();
 }
Beispiel #27
0
        public IdentityResult Register(ApplicationIdentityUser user)
        {
            IdentityResult result = manager.Create(user, user.PasswordHash);

            return(result);
        }
Beispiel #28
0
 public AddArticleViewModel()
 {
     Author        = new ApplicationIdentityUser();
     CategoryViews = new List <CategoryViewModel>();
 }
Beispiel #29
0
        private async Task <ApplicationIdentityUser> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable <Claim> claims)
        {
            // create a list of claims that we want to transfer into our store
            var filtered = new List <Claim>();

            // user's display name
            var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ??
                       claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;

            if (name != null)
            {
                filtered.Add(new Claim(JwtClaimTypes.Name, name));
            }
            else
            {
                var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ??
                            claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
                var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ??
                           claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
                if (first != null && last != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last));
                }
                else if (first != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, first));
                }
                else if (last != null)
                {
                    filtered.Add(new Claim(JwtClaimTypes.Name, last));
                }
            }

            // email
            var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
                        claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;

            if (email != null)
            {
                filtered.Add(new Claim(JwtClaimTypes.Email, email));
            }

            var user = new ApplicationIdentityUser
            {
                UserName = Guid.NewGuid().ToString(),
            };
            var identityResult = await _userManager.CreateAsync(user);

            if (!identityResult.Succeeded)
            {
                throw new Exception(identityResult.Errors.First().Description);
            }

            if (filtered.Any())
            {
                identityResult = await _userManager.AddClaimsAsync(user, filtered);

                if (!identityResult.Succeeded)
                {
                    throw new Exception(identityResult.Errors.First().Description);
                }
            }

            identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider));

            if (!identityResult.Succeeded)
            {
                throw new Exception(identityResult.Errors.First().Description);
            }

            return(user);
        }
Beispiel #30
0
        public async Task <ActionResult> Users_Update([DataSourceRequest] DataSourceRequest request, ApplicationIdentityUser user)
        {
            if (ModelState.IsValid)
            {
                var finduser = await _userManager.FindByIdAsync(user.Id.ToString());

                finduser.FirstName            = user.FirstName;
                finduser.LastName             = user.LastName;
                finduser.Address              = user.Address;
                finduser.Email                = user.Email;
                finduser.AccessFailedCount    = finduser.AccessFailedCount;
                finduser.ConcurrencyStamp     = finduser.ConcurrencyStamp;
                finduser.EmailConfirmed       = finduser.EmailConfirmed;
                finduser.LockoutEnabled       = finduser.LockoutEnabled;
                finduser.LockoutEnd           = finduser.LockoutEnd;
                finduser.NormalizedEmail      = finduser.NormalizedEmail;
                finduser.NormalizedUserName   = finduser.NormalizedUserName;
                finduser.PasswordHash         = finduser.PasswordHash;
                finduser.PhoneNumber          = finduser.PasswordHash;
                finduser.PhoneNumberConfirmed = finduser.PhoneNumberConfirmed;
                finduser.SecurityStamp        = finduser.SecurityStamp;
                finduser.TwoFactorEnabled     = finduser.TwoFactorEnabled;
                finduser.UserName             = user.UserName;

                var user_created = await _userManager.UpdateAsync(finduser);

                return(Json(new[] { finduser }.ToDataSourceResult(request, ModelState)));
            }
            return(null);
        }