public static void SeedUsers(ApplicationDbContext context, Microsoft.AspNetCore.Identity.UserManager <AppUser> userManager)
        {
            if (context.Users.Any())
            {
                return;
            }

            var user1 = (new AppUser {
                UserName = "******", Email = "*****@*****.**", FirstName = "Kot", LastName = "Popugaev"
            });

            userManager.CreateAsync(user1, "#FoRk1337").Wait();

            var user2 = (new AppUser {
                UserName = "******", Email = "*****@*****.**", FirstName = "Pes", LastName = "Sharik"
            });

            userManager.CreateAsync(user2, "#FoRk1337").Wait();

            var user3 = (new AppUser {
                UserName = "******", Email = "*****@*****.**", FirstName = "Tim", LastName = "Kooc"
            });

            userManager.CreateAsync(user3, "#FoRk1337").Wait();

            var user4 = (new AppUser {
                UserName = "******", Email = "*****@*****.**", FirstName = "Senior", LastName = "Developer"
            });

            userManager.CreateAsync(user4, "#FoRk1337").Wait();
        }
Exemplo n.º 2
0
        internal static void Initialize(AppDbContext context, Microsoft.AspNetCore.Identity.RoleManager <Microsoft.AspNetCore.Identity.IdentityRole> roleManager, Microsoft.AspNetCore.Identity.UserManager <Microsoft.AspNetCore.Identity.IdentityUser> userManager)
        {
            if (!roleManager.RoleExistsAsync("Admin").Result)
            {
                IdentityRole role = new IdentityRole("Admin");

                roleManager.CreateAsync(role).Wait();
            }

            if (!roleManager.RoleExistsAsync("NormalUser").Result)
            {
                IdentityRole role = new IdentityRole("NormalUser");

                roleManager.CreateAsync(role).Wait();
            }

            //-------------------------------------------------------------------

            if (userManager.FindByNameAsync("Guru").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.Email    = "*****@*****.**";
                user.UserName = "******";

                IdentityResult result = userManager.CreateAsync(user, "Password!123").Result;

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

            if (userManager.FindByNameAsync("Sven").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.Email    = "*****@*****.**";
                user.UserName = "******";

                IdentityResult result = userManager.CreateAsync(user, "Password!123").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user, "NormalUser").Wait();
                }
            }

            //-----------------------------------------------------------------------

            // Don´t forget to save
            //context.SaveChanges();
        }
Exemplo n.º 3
0
        internal static void Initialize(DbContext context, Microsoft.AspNetCore.Identity.RoleManager <Microsoft.AspNetCore.Identity.IdentityRole> roleManager, Microsoft.AspNetCore.Identity.UserManager <Microsoft.AspNetCore.Identity.IdentityUser> userManager)
        {
            if (!roleManager.RoleExistsAsync("Admin").Result)
            {
                IdentityRole role = new IdentityRole("Admin");

                roleManager.CreateAsync(role).Wait();
            }

            if (!roleManager.RoleExistsAsync("NormalUser").Result)
            {
                IdentityRole role = new IdentityRole("NormalUser");

                roleManager.CreateAsync(role).Wait();
            }

            //------------------------------------------------------------------------------------//

            if (userManager.FindByNameAsync("Abduallah").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.Email    = "*****@*****.**";
                user.UserName = "******";

                IdentityResult result = userManager.CreateAsync(user, "Abduallah1996-").Result;

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

            if (userManager.FindByNameAsync("Abdullah").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.Email    = "*****@*****.**";
                user.UserName = "******";


                var result = userManager.CreateAsync(user, "Abduallah1996-");

                if (result.IsCompletedSuccessfully)
                {
                    userManager.AddToRoleAsync(user, "NormalUser").Wait();
                }
            }
            //------------------------------------------------------------------------------------------

            //Glöm inte att spara
            //context.SaveChanges();
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Register([FromBody] EmailPasswordModel model)
        {
            if (!model.Email.IsValidEmail())
            {
                return(BadRequest());
            }

            var user = new ApplicationUser {
                UserName = model.Email, Email = model.Email
            };
            var result = await _userManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                var errorMessages = result.Errors.Select(e => e.Description).Aggregate((en, enn) => en + ", " + enn);
                return(Conflict(new { Status = "Error", Message = errorMessages }));
            }

            //await SendEmailConfirmationAsync(model, user); TODO send email confirmation
            var refreshToken = AesCryptor.EncryptStringAes(user.Id, RefreshtokenKey.Value, RefreshtokenKey.IV);
            var jwtToken     = JwtTokenizer.GenerateJwtToken(user.Id, user.Email);

            //CreateAuthenticatedCookie(jwtToken);
            return(Ok(new { userId = user.Id, Token = jwtToken, refreshtoken = refreshToken }));
        }
Exemplo n.º 5
0
        public async Task <IActionResult> Register([FromBody] RegisterModel registerModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var user = new ApplicationUser
            {
                Email         = registerModel.Email,
                SecurityStamp = Guid.NewGuid().ToString(),
                UserName      = registerModel.Email,
                PhoneNumber   = registerModel.PhoneNumber,
                DateCreated   = DateTime.Now
            };
            var task = userManager?.CreateAsync(user, registerModel.Password);

            if (task == null)
            {
                return(BadRequest());
            }
            await task;

            if (!task.Result.Succeeded)
            {
                return(Ok(new { success = task.Result.Succeeded, message = task.Result.Errors }));
            }
            await userManager.AddToRoleAsync(user, registerModel.RegisterType.ToString());

            new EmailNotification(context, Configuration).SendRegistrationEmail(userManager, user);
            return(Ok(new { success = task.Result.Succeeded, message = task.Result.Errors, userId = user.Id }));
        }
Exemplo n.º 6
0
        protected override async Task <Response <CreateResult> > HandleCore(RegisterUserRequest request)
        {
            var user   = new Database.Collections.User(request.UserName, request.Email);
            var result = await _userManager.CreateAsync(user, request.Password);

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

                return(new Response <CreateResult>(CreateResult.Created));
            }

            return(new Response <CreateResult>(CreateResult.NotCreated));
        }
Exemplo n.º 7
0
        public async Task <IActionResult> SignUp([FromBody] RegisterViewModel value)
        {
            var user = new AppUser
            {
                Email         = value.Email,
                UserName      = value.Email,
                SecurityStamp = Guid.NewGuid().ToString()
            };
            var result = await _userManager.CreateAsync(user, value.Password);

            if (result.Succeeded)
            {
                await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Role, value.UserType));
            }
            return(Ok(new { Email = user.Email }));
        }
Exemplo n.º 8
0
        public void Initialize()
        {
            _context.Database.EnsureCreated();

            if (_context.PostModels.Any())
            {
                return;
            }
            var user1 = new User();

            user1.Email = "*****@*****.**";
            _userManager.CreateAsync(user1, "Aa123!");
            //var user2 = new User();
            //user2.Email = "*****@*****.**";
            //_userManager.CreateAsync(user2, "Bb123!");
            //var user3 = new User();
            //user3.Email = "*****@*****.**";
            //_userManager.CreateAsync(user3, "Cc123!");

            var posts = new Post[]
            {
                new Post("Some title", "text", user1, DateTime.Now),
                //new PostModel("<b>Bolt</b>"),
                //new PostModel("<h2>H2</h2>")
            };

            var comments = new PostComment[]
            {
                PostComment.Create("Comment", user1),
            };

            posts[0].Comments = comments;


            foreach (var post in posts)
            {
                _context.PostModels.Add(post);
            }



            _context.SaveChanges();
        }
Exemplo n.º 9
0
        //here it will be binded automatically (the input model i think)
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = "/Identity/Account/Login";

            //how to get the specific types of user via role
            //var users = await _userManager.GetUsersInRoleAsync("User");

            if (ModelState.IsValid)
            {
                //unnecessary for now
                //var isAdmin = !this._userManager.Users.Any();
                var user = new ACTOUser {
                    UserName = this.Input.Username, Email = this.Input.Email
                };

                //creates and hashses the password
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    //assignes the selected role
                    await this._userManager.AddToRoleAsync(user, this.Input.Role);

                    //we won`t be needing the logger for now...
                    //_logger.LogInformation("User created a new account with password.");

                    return(LocalRedirect(returnUrl));
                }


                //for error checkups
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            //returns to the page with the loaded erors from the above foreach.
            return(Page());
        }
        /// <summary>
        /// Populate MongoDB with a List of Dummy users to enable tests - e.g. Alice, Bob
        ///   see Config.GetSampleUsers() for details.
        /// </summary>
        /// <param name="userManager"></param>
        private static void  AddSampleUsersToMongo(Microsoft.AspNetCore.Identity.UserManager <Microsoft.AspNetCore.Identity.MongoDB.IdentityUser> userManager)
        {
            var dummyUsers = Config.GetSampleUsers();

            foreach (var usrDummy in dummyUsers)
            {
                var userDummyEmail = usrDummy.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Email);

                if (userDummyEmail == null)
                {
                    throw new Exception("Could not locate user email from  claims!");
                }


                var user = new Microsoft.AspNetCore.Identity.MongoDB.IdentityUser()
                {
                    UserName        = usrDummy.Username,
                    LockoutEnabled  = false,
                    EmailConfirmed  = true,
                    Email           = userDummyEmail.Value,
                    NormalizedEmail = userDummyEmail.Value
                };



                foreach (var claim in usrDummy.Claims)
                {
                    user.AddClaim(claim);
                }
                var result = userManager.CreateAsync(user, usrDummy.Password);
                if (!result.Result.Succeeded)
                {
                    // If we got an error, Make sure to drop all collections from Mongo before trying again. Otherwise sample users will NOT be populated
                    var errorList = result.Result.Errors.ToArray();
                    throw new Exception($"Error Adding sample users to MongoDB! Make sure to drop all collections from Mongo before trying again!");
                }
            }
            return;
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Register(RegisterModel model)
        {
            ApplicationUser user = new ApplicationUser()
            {
                UserName = model.Email,
                Email    = model.Email,
            };

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

            if (result.Succeeded)
            {
                var signInResult = await signInManager.PasswordSignInAsync(user, model.Password, true, false);

                if (signInResult.Succeeded)
                {
                    var jwtResponse = jwtAuthenticator.GenerateJwtToken(user);
                    return(Ok(jwtResponse));
                }
            }


            return(BadRequest("Invalid Auth Credentials"));
        }
Exemplo n.º 12
0
        public static void Seed(AwardData.AwardContext ctx, Microsoft.AspNetCore.Identity.UserManager <ApplicationUser> userManager)
        {
            var routes = getRoutes();

            ctx.Routes.AddRange(routes);
            ctx.SaveChanges();
            var client = new HttpClient();

            using (HttpResponseMessage response = client.GetAsync("https://awardhacks.se/export/flights").Result)
            {
                using (HttpContent content = response.Content)
                {
                    var json   = content.ReadAsStringAsync().Result;
                    var export = Newtonsoft.Json.JsonConvert.DeserializeObject <List <AwardExport> >(json);
                    foreach (var e in export)
                    {
                        var tmp = new Crawl
                        {
                            Id         = e.Id,
                            Departure  = e.Departure,
                            Arrival    = e.Arrival,
                            Business   = e.Business,
                            Plus       = e.Plus,
                            Go         = e.Go,
                            Flight     = e.Flight,
                            TravelDate = e.Departure.Date,
                            CrawlDate  = DateTime.Now,
                            Equipment  = e.Equipment,
                            Success    = true
                        };
                        tmp.RouteId = routes.Where(r => r.To == e.Destination && r.From == e.Origin).Select(r => r.Id).FirstOrDefault();
                        if (tmp.RouteId == 0)
                        {
                            tmp.RouteId = routes.Where(r => r.To == e.Origin && r.From == e.Destination).Select(r => r.Id).FirstOrDefault();
                            tmp.Return  = true;
                        }
                        ctx.Crawls.Add(tmp);
                    }
                }
            }
            ctx.SaveChanges();
            var ofData = new OpenFlightsData.OFData();

            ofData.LoadData();
            int id = 0;

            foreach (var iata in ctx.Routes.Select(r => r.To).Union(ctx.Routes.Select(r => r.From)).Distinct())
            {
                var ap = ofData.Airports.FirstOrDefault(ap => iata.Equals(ap.IATA, StringComparison.OrdinalIgnoreCase));
                if (ap != null)
                {
                    ctx.Airports.Add(new Airport

                    {
                        Id      = ++id,
                        City    = ap.City,
                        IATA    = ap.IATA,
                        Country = ap.Country,
                        //This is not correct for Africa etc but will do for the current routes.
                        Zone = ap.Country == "United States" ? "North & Central America" : ap.Timezone > -4 && ap.Timezone < 5 ? "Europe" : "Central Asia & Far East Asia"
                    }
                                     );
                }
                ;
            }
            ctx.SaveChanges();
            userManager.CreateAsync(new ApplicationUser {
                Email = "*****@*****.**", EmailConfirmed = true, UserName = "******"
            }, "someweaktestpwd");
            ctx.SaveChanges();
        }