Esempio n. 1
0
        public void CreateRolesandUsers()
        {
            var roleManager  = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>());
            var appDbContext = new ApplicationDbContext();
            var appUserStore = new ApplicationUserStore(appDbContext);
            var userManager  = new ApplicationUserManager(appUserStore);

            //Create Admin roles
            if (!roleManager.RoleExists("Admin"))
            {
                var role = new IdentityRole();
                role.Name = "Admin";
                roleManager.Create(role);
            }

            //Create Admin User
            if (userManager.FindByName("admin") == null)
            {
                var user = new ApplicationUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";
                string userPassword = "******";
                var    chkUser      = userManager.Create(user, userPassword);
                if (chkUser.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Admin");
                }
            }

            //Create Manager Role
            if (!roleManager.RoleExists("Manager"))
            {
                var role = new IdentityRole();
                role.Name = "Manager";
                roleManager.Create(role);
            }

            //Create Manager User
            if (userManager.FindByName("manager") == null)
            {
                var user = new ApplicationUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";
                string userPassword = "******";
                var    chkUser      = userManager.Create(user, userPassword);
                if (chkUser.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Manager");
                }
            }

            //Create Customer Role

            if (!roleManager.RoleExists("Customer"))
            {
                var role = new IdentityRole();
                role.Name = "Customer";
                roleManager.Create(role);
            }
        }
Esempio n. 2
0
        private void CreateUserAndRoles()
        {
            var context     = new ApplicationDBContext();
            var userStore   = new ApplicationUserStore(context);
            var userManager = new ApplicationUserManager(userStore);
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            //Create Admin Role
            if (!roleManager.RoleExists("Admin"))
            {
                var role = new IdentityRole();
                role.Name = "Admin";
                roleManager.Create(role);
            }

            //Create admin user
            if (userManager.FindByEmail("*****@*****.**") == null)
            {
                var user = new ApplicationUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";
                var userPassword = "******";
                var chkUser      = userManager.Create(user, userPassword);

                if (chkUser.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Admin");
                }
            }
        }
Esempio n. 3
0
        private ApplicationUserManager SetupMockApplicationUserManager(ApplicationUserStore storeMock)
        {
            var managerMock = new Mock <ApplicationUserManager>(storeMock);


            return(managerMock.Object);
        }
        public void MyTestInitialize()
        {
            //var _owin = HttpContext.GetOwinContext();
            var _provider = new DpapiDataProtectionProvider("WebSrv Identity");

            _context     = ApplicationDbContext.Create();
            _userStore   = new ApplicationUserStore(_context);
            _userManager = new ApplicationUserManager(_userStore);
            _userManager.UserTokenProvider =
                new DataProtectorTokenProvider <ApplicationUser>(_provider.Create("EmailConfirmation"));
            _userManager.EmailService = new EmailService();
            _serverManager            = new ApplicationServerManager(new ServerStore(_context));

            // https://stackoverflow.com/questions/11779311/testing-webapi-controller-url-link
            _config = new HttpConfiguration();
            _config.Routes.MapHttpRoute(
                name: "ConfirmEmailRoute",
                routeTemplate: "api/Account/ConfirmEmail/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
            _config.Routes.MapHttpRoute(
                name: "Default",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });
            // Request
            _request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/Account");
            _request.Properties[HttpPropertyKeys.HttpConfigurationKey] = _config;
            _request.Properties[HttpPropertyKeys.HttpRouteDataKey]     =
                new HttpRouteData(new HttpRoute());
            //
            _sut = new AccountController(_userManager, _serverManager, null)
            {
                Request = _request
            };
        }
Esempio n. 5
0
 public ActionResult Register(RegisterViewModel registerViewModel)
 {
     if (ModelState.IsValid)
     {
         ApplicationDbContext   dbContext   = new ApplicationDbContext();
         ApplicationUserStore   userStore   = new ApplicationUserStore(dbContext);
         ApplicationUserManager userManager = new ApplicationUserManager(userStore);
         string          passwordHash       = Crypto.HashPassword(registerViewModel.Password);
         ApplicationUser applicationUser    = new ApplicationUser()
         {
             Email        = registerViewModel.Email,
             PasswordHash = passwordHash,
             UserName     = registerViewModel.Username,
             Address      = registerViewModel.Address,
             City         = registerViewModel.City,
             Birthday     = registerViewModel.DateOfBirth,
             PhoneNumber  = registerViewModel.Mobile
         };
         IdentityResult result = userManager.Create(applicationUser);
         if (result.Succeeded)
         {
             userManager.AddToRole(applicationUser.Id, "Customer");
             var authenticationManager = HttpContext.GetOwinContext().Authentication;
             var userIdentity          = userManager.CreateIdentity(applicationUser, DefaultAuthenticationTypes.ApplicationCookie);
             authenticationManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties(), userIdentity);
         }
         return(RedirectToAction("Index", "Home"));
     }
     else
     {
         ModelState.AddModelError("My Error", "Invalid Data");
         return(View());
     }
 }
Esempio n. 6
0
 public void Setup()
 {
     _rndUsrs     = Generate.FakeUsers();
     _appUsrRepo  = SetupApplicationUserRepo();
     _appUsrStore = SetupMockApplicationUserStore();
     _unitOfWork  = new Mock <IUnitOfWork>().Object;
 }
        public BaseApiController()
        {
            _context = new TutorAppDbContext();
            var userStore = new ApplicationUserStore(_context);

            _userManager = new ApplicationUserManager(userStore);
        }
        public async Task <IHttpActionResult> CreateAccount(CreateAccountModel model)
        {
            if (model == null)
            {
                return(BadRequest());
            }

            var userStore = new ApplicationUserStore();

            var usermanager = new ApplicationUserManager(userStore);

            var user = new ApplicationUser
            {
                UserName = model.Email
            };

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

            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error);
                }

                return(BadRequest(ModelState));
            }

            return(Ok());
        }
Esempio n. 9
0
        public ApplicationUserManager(ApplicationUserStore store)
            : base(store)
        {
            this.UserValidator = new UserValidator <ApplicationUser, Guid>(this)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = false
            };

            // Configure validation logic for passwords
            this.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 3,
                RequireNonLetterOrDigit = false,
                RequireDigit            = false,
                RequireLowercase        = false,
                RequireUppercase        = false,
            };

            // Configure user lockout defaults
            this.UserLockoutEnabledByDefault          = true;
            this.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            this.MaxFailedAccessAttemptsBeforeLockout = 5;

            //var dataProtectionProvider = options.DataProtectionProvider;
            //if (dataProtectionProvider != null)
            //{
            //    manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser, Guid>(dataProtectionProvider.Create("ASP.NET Identity"));
            //}
        }
Esempio n. 10
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options,
                                                    IOwinContext context)
        {
            var store   = new ApplicationUserStore(context.Get <ApplicationDbContext>());
            var manager = new ApplicationUserManager(store);

            manager.UserValidator = new UserValidator <User>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = false,
            };

            manager.PasswordValidator = new PasswordValidator()
            {
                RequiredLength = 6,
            };
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <User>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
 public void MyTestInitialize()
 {
     _context       = ApplicationDbContext.Create();
     _userStore     = new ApplicationUserStore(_context);
     _sut           = new ApplicationUserManager(_userStore);
     _serverManager = new ApplicationServerManager(new ServerStore(_context));
 }
Esempio n. 12
0
        public async Task AddFundsAsync_WithCorrectData_ShouldSuccessfullyUpdate()
        {
            var errorMessage = "UsersService AddFundsAsync() method does not work properly.";

            // Arrange
            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            var usersRepository = new EfRepository <ApplicationUser>(context);

            var cloudinaryService = new Mock <ICloudinaryService>();

            var usersService = new UsersService(usersRepository, cloudinaryService.Object);

            var userStore = new ApplicationUserStore(context);

            var userManager = new UserManager <ApplicationUser>(userStore, null, null, null, null, null, null, null, null);

            var user = new ApplicationUser()
            {
                Id       = Guid.NewGuid().ToString(),
                UserName = "******",
            };

            // Act
            await userManager.CreateAsync(user);

            var funds = usersRepository.All().First().Funds;
            await usersService.AddFundsAsync(user, 5);

            var actualResult   = usersRepository.All().First().Funds;
            var expectedResult = funds + 5;

            // Assert
            Assert.True(expectedResult == actualResult, errorMessage);
        }
        public ActionResult Register(RegisterViewModel rvm)
        {
            if (ModelState.IsValid)
            {
                //register
                var appDbContext = new ApplicationDbContext();
                var userStore    = new ApplicationUserStore(appDbContext);
                var userManager  = new ApplicationUserManager(userStore);
                var passwordHash = Crypto.HashPassword(rvm.Password);
                var user         = new ApplicationUser()
                {
                    Email = rvm.Email, UserName = rvm.Username, PasswordHash = passwordHash, City = rvm.City, Country = rvm.Country, Birthday = rvm.DateOfBirth, Address = rvm.Address, PhoneNumber = rvm.Mobile
                };
                IdentityResult result = userManager.Create(user);

                if (result.Succeeded)
                {
                    //role
                    userManager.AddToRole(user.Id, "Customer");

                    //login
                    this.LoginUser(userManager, user);
                }
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ModelState.AddModelError("My Error", "Invalid data");
                return(View());
            }
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     canSeePostSettings = false;
     if (User.Identity.IsAuthenticated)
     {
         ApplicationUserManager manager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>();
         userID = ApplicationUserStore.GetUserIDByName(manager, User);
     }
     DisplayPosts();
     if (Page.IsPostBack)
     {
         string postID = Request["__EVENTARGUMENT"];
         if (Request["__EVENTTARGET"] == "starClick")
         {
             if (!User.Identity.IsAuthenticated)
             {
                 Response.Redirect(Page.ResolveUrl("~/Account/Login"));
                 return;
             }
             UpdateStarsCount(postID, userID);
         }
         else if (Request["__EVENTTARGET"] == "acceptPost")
         {
             SqlDatabase database   = new SqlDatabase();
             PostsTable  postsTable = new PostsTable(database);
             postsTable.AcceptPost(postID);
         }
         else if (Request["__EVENTTARGET"] == "removePost")
         {
             SqlDatabase database   = new SqlDatabase();
             PostsTable  postsTable = new PostsTable(database);
             postsTable.RemovePost(postID);
         }
     }
 }
Esempio n. 15
0
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var appDbContext = new ProjectDbContext();
                List <ApplicationUser> searchUsers = appDbContext.Users.Where(m => m.UserName == model.Username || m.Email == model.Email).ToList();
                if (searchUsers.Count > 0)
                {
                    ModelState.AddModelError("Err", "Nje perdorues me te njetin Email OSE Username tashme ekziston ne sistem.");
                    return(View(model));
                }
                var             userStore    = new ApplicationUserStore(appDbContext);
                var             userManager  = new ApplicationUserManager(userStore);
                var             passwordHash = Crypto.HashPassword(model.Password);
                ApplicationUser user         = new ApplicationUser()
                {
                    Email = model.Email, UserName = model.Username, PasswordHash = passwordHash, Emri = model.Emri, Mbiemri = model.Mbiemri
                };
                IdentityResult result = userManager.Create(user);

                if (result.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Student");
                    return(RedirectToAction("Login"));
                }
            }
            return(View(model));
        }
Esempio n. 16
0
        public ActionResult Register(RegisterViewModel rvm)
        {
            if (ModelState.IsValid)
            {
                var context     = new ApplicationDBContext();
                var store       = new ApplicationUserStore(context);
                var userManager = new ApplicationUserManager(store);
                var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

                if (!roleManager.RoleExists("Customer"))
                {
                    var role = new IdentityRole();
                    role.Name = "Customer";
                    roleManager.Create(role);
                }
                if (userManager.FindByName(rvm.UserName) == null)
                {
                    var user = new ApplicationUser();
                    user.UserName = rvm.UserName;
                    user.Email    = rvm.Email;
                    string password = Crypto.HashPassword(rvm.Password);
                    user.PasswordHash = password;
                    var chkUser = userManager.Create(user, user.PasswordHash);
                    if (chkUser.Succeeded)
                    {
                        userManager.AddToRole(user.Id, "Customer");
                    }
                }
                return(RedirectToAction("Index", "Home"));
            }
            return(View());
        }
Esempio n. 17
0
 public ActionResult ChangePassword(ChangePasswordVM obj)
 {
     if (ModelState.IsValid)
     {
         var    appDbContext       = new ProjectDbContext();
         var    userStore          = new ApplicationUserStore(appDbContext);
         var    userManager        = new ApplicationUserManager(userStore);
         string userId             = User.Identity.GetUserId();
         var    currentUser        = userService.GetUserById(userId);
         var    userIdentification = userManager.Find(currentUser.UserName, obj.OldPassword);
         if (userIdentification == null)
         {
             ModelState.AddModelError("OldPassword", "Passwordi i vjeter nuk eshte i sakte");
         }
         else
         {
             IdentityResult result = userManager.ChangePassword(userId, obj.OldPassword, obj.NewPassword);
             if (result.Succeeded)
             {
                 this.AddNotification("Passwordi u ndryshua.", NotificationType.SUCCESS);
             }
             else
             {
                 this.AddNotification("Passwordi nuk u ndryshua.", NotificationType.ERROR);
             }
             return(RedirectToAction("UserProfile"));
         }
     }
     return(View());
 }
        public ActionResult Login(LoginViewModel lvm)
        {
            //login
            var appDbContext = new ApplicationDbContext();
            var userStore    = new ApplicationUserStore(appDbContext);
            var userManager  = new ApplicationUserManager(userStore);
            var user         = userManager.Find(lvm.Username, lvm.Password);

            if (user != null)
            {
                //login
                this.LoginUser(userManager, user);

                if (userManager.IsInRole(user.Id, "Admin"))
                {
                    return(RedirectToAction("Index", "Home", new { area = "Admin" }));
                }
                else if (userManager.IsInRole(user.Id, "Manager"))
                {
                    return(RedirectToAction("Index", "Home", new { area = "Manager" }));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
            else
            {
                ModelState.AddModelError("myerror", "Invalid username or password");
                return(View());
            }
        }
 private ApplicationUser AddNewuser(ApplicationDbContext context, UserDTO dto)
 {
     try
     {
         var userStore   = new ApplicationUserStore(context);
         var usermanager = new ApplicationUserManager(userStore);
         var id1         = Guid.NewGuid().ToString();
         usermanager.Create(new ApplicationUser()
         {
             Id        = id1,
             UserName  = dto.Email,
             Email     = dto.Email,
             FirstName = dto.FirstName,
             LastName  = dto.LastName,
             Active    = dto.Active,
             Phone     = dto.Phone,
             ClientId  = dto.ClientId
         }, "Developer1!");
         return(usermanager.FindByEmail(dto.Email));
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            // Default UserStore constructor uses the default connection string named: DefaultConnection
            var context   = StudentsManagerDbContext.GetInstance();
            var userStore = new ApplicationUserStore <ApplicationUser>(context);
            var manager   = new ApplicationUserManager <ApplicationUser>();

            var user = new ApplicationUser()
            {
                UserName = UserName.Text
            };
            IdentityResult result = manager.Create(user, Password.Text);

            if (result.Succeeded)
            {
                StatusMessage.Text = string.Format("User {0} was created successfully!", user.UserName);
            }
            else
            {
                StatusMessage.Text = result.Errors.FirstOrDefault();
            }

            ApplicationUser someUser = context.Users.FirstOrDefault();

            context.Tasks.Add(new Task
            {
                Desciption = "You lold",
                Level      = 9,
                Name       = "lo",
                Tags       = "Oh, my, tags"
            });

            context.SaveChanges();
        }
Esempio n. 21
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var username = context.UserName;

            var password = context.Password;

            var userStore = new ApplicationUserStore();

            var usermanager = new ApplicationUserManager(userStore);

            var user = await usermanager.FindAsync(username, password);

            if (user != null)
            {
                var identity = await usermanager.CreateIdentityAsync(user, context.Options.AuthenticationType);

                var authProperties = new AuthenticationProperties(new Dictionary <string, string>
                {
                    { "x:client_id", context.ClientId }
                });

                var ticket = new AuthenticationTicket(identity, authProperties);

                context.Validated(ticket);
            }
        }
Esempio n. 22
0
        public void CreateRolesAndUsers()
        {
            var roleManager  = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>());
            var appDbContext = new ApplicationDbContext();
            var appUserStore = new ApplicationUserStore(appDbContext);
            var userManager  = new ApplicationUserManager(appUserStore);


            //Admini
            if (!roleManager.RoleExists("Admin"))
            {
                var role = new IdentityRole();
                role.Name = "Admin";
                roleManager.Create(role);
            }


            if (userManager.FindByName("klejsi") == null)
            {
                var user = new ApplicationUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";
                string userPassword = "******";
                var    chkUser      = userManager.Create(user, userPassword);
                if (chkUser.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Admin");
                }
            }

            //Financa
            if (!roleManager.RoleExists("Financa"))
            {
                var role = new IdentityRole();
                role.Name = "Financa";
                roleManager.Create(role);
            }


            if (userManager.FindByName("klejsi1") == null)
            {
                var user = new ApplicationUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";
                string userPassword = "******";
                var    chkUser      = userManager.Create(user, userPassword);
                if (chkUser.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Financa");
                }
            }

            //Klienti
            if (!roleManager.RoleExists("Customer"))
            {
                var role = new IdentityRole();
                role.Name = "Customer";
                roleManager.Create(role);
            }
        }
Esempio n. 23
0
        public ActionResult Register(RegisterViewModel rvm)
        {
            if (ModelState.IsValid)
            {
                //register
                var appDbContext = new ApplicationDbContext();
                var userStore    = new ApplicationUserStore(appDbContext);
                var userManager  = new ApplicationUserManager(userStore);
                var passwordHash = Crypto.HashPassword(rvm.Password);
                var user         = new ApplicationUser()
                {
                    Email = rvm.Email, UserName = rvm.Username, PasswordHash = passwordHash, City = rvm.City, Country = rvm.Country, Address = rvm.Address, PhoneNumber = rvm.Mobile
                };
                IdentityResult result = userManager.Create(user);

                if (result.Succeeded)
                {
                    //role
                    userManager.AddToRole(user.Id, "Customer");

                    //login
                    var authenticationManager = HttpContext.GetOwinContext().Authentication;
                    var userIdentity          = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties(), userIdentity);
                }
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ModelState.AddModelError("My Error", "Invalid data");
                return(View());
            }
        }
Esempio n. 24
0
        public async Task CreateInvalidUser()
        {
            StubData();

            // user to create
            user = new ApplicationUser
            {
                Email    = "*****@*****.**",
                UserName = "******"
            };

            using (var factory = new ApplicationDbContextFactory())
            {
                using (var dbContext = factory.CreateContext(false))
                {
                    using (var userStore = new ApplicationUserStore(dbContext))
                    {
                        await Assert.ThrowsExceptionAsync <InvalidOperationException>(async() =>
                        {
                            await userStore.CreateAsync(user, driverLicense, billingAddress, creditCard);
                        });
                    }
                }
            }
        }
Esempio n. 25
0
        public ActionResult Regjistrim(RegisterViewModel rg)
        {
            if (ModelState.IsValid)
            {
                var appDbContext = new ApplicationDbContext();
                var userStore    = new ApplicationUserStore(appDbContext);
                var userManager  = new ApplicationUserManager(userStore);
                var passwordHash = Crypto.HashPassword(rg.password);
                var user         = new ApplicationUser()
                {
                    Email = rg.email, UserName = rg.username, PasswordHash = passwordHash, emri = rg.name
                };
                IdentityResult result = userManager.Create(user);

                if (result.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Customer");
                    var authenticationManager = HttpContext.GetOwinContext().Authentication;
                    var userIdentity          = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties(), userIdentity);
                }
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                return(View());
            }
        }
Esempio n. 26
0
        public async Task <string> AddUser()
        {
            ApplicationUser user;
            //per ora isanziamo qua ApplicationUserStore e ApplicationUserManager ed
            //abbiamo creato una istanza di dbcontext
            //questo determina l'istanza di più istanze per richiesta
            //la soluzione consiste nel creare una sola istanza di userManager e dbcontext per richiesta.
            //ed utilizzarla per tutta la applicazione con il metodo CreatePerOwinContext dell'appbuilder
            ApplicationUserStore   Store       = new ApplicationUserStore(new ApplicationDbContext());
            ApplicationUserManager userManager = new ApplicationUserManager(Store);

            user = new ApplicationUser
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };

            var result = await userManager.CreateAsync(user);

            //il valore di ritorno è un identityreult con una proprietà succeeded
            if (!result.Succeeded)
            {
                return(result.Errors.First());
            }
            return("User added");
        }
Esempio n. 27
0
        public ActionResult Login(LoginViewModel lvm)
        {
            var appDbContext = new ApplicationDbContext();
            var userStore    = new ApplicationUserStore(appDbContext);
            var userManager  = new ApplicationUserManager(userStore);
            var user         = userManager.Find(lvm.Username, lvm.Password);

            if (user != null)
            {
                var authenticationManager = HttpContext.GetOwinContext().Authentication;
                var userIdentity          = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties(), userIdentity);

                if (userManager.IsInRole(user.Id, "Admin"))
                {
                    return(RedirectToAction("Index", "Home", new { area = "Admin" }));
                }
                else if (userManager.IsInRole(user.Id, "Manager"))
                {
                    return(RedirectToAction("Index", "Home", new { area = "Manager" }));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
            else
            {
                ModelState.AddModelError("Myerror", "Invalid username or password");
                return(View());
            }
        }
Esempio n. 28
0
        public ActionResult Login(LoginViewModel loginViewModel)
        {
            if (ModelState.IsValid)
            {
                ApplicationDbContext   context = new ApplicationDbContext();
                ApplicationUserStore   store   = new ApplicationUserStore(context);
                ApplicationUserManager manager = new ApplicationUserManager(store);
                ApplicationUser        user    = manager.Find(loginViewModel.Username, loginViewModel.Password);
                if (user != null)
                {
                    IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
                    ClaimsIdentity         userIdentity          = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(userIdentity);
                    if (manager.IsInRole(user.Id, "Admin"))
                    {
                        return(RedirectToAction("Index", "Home", new { area = "Admin" }));
                    }
                    else if (manager.IsInRole(user.Id, "Manager"))
                    {
                        return(RedirectToAction("Index", "Products", new { area = "Manager" }));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    ModelState.AddModelError("My Error", "Invalid Username or Password");
                    return(View());
                }
            }

            return(Content("this shouldnt return here"));
        }
Esempio n. 29
0
        public ActionResult AddUser(UserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var roleManager  = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>());
                var appDbContext = new ApplicationDbContext();
                var userStore    = new ApplicationUserStore(appDbContext);
                var userManager  = new ApplicationUserManager(userStore);

                ApplicationUser user = new ApplicationUser
                {
                    name         = model.Name,
                    UserName     = model.UserName,
                    Email        = model.Email,
                    PasswordHash = Crypto.HashPassword(model.Password),
                };
                IdentityResult result = userManager.Create(user);
                if (result.Succeeded)
                {
                    var role = new IdentityRole();
                    role.Name = "user";
                    roleManager.Create(role);

                    IdentityResult roleResult = userManager.AddToRole(user.Id, role.Name);
                }

                return(RedirectToAction("Index", "User"));
            }
            else
            {
                ModelState.AddModelError("", "Invalid data");

                return(View(model));
            }
        }
Esempio n. 30
0
        private void CreateInitialRolesAndUsers()
        {
            var dbCOntext = new ApplicationDBContext();
            RoleManager <IdentityRole> roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(dbCOntext));
            var appUserStore           = new ApplicationUserStore(dbCOntext);
            var applicationUserManager = new ApplicationUserManager(appUserStore);

            var a = roleManager.Roles.ToList();

            //Create Admin Role
            if (!roleManager.RoleExists("Admin"))
            {
                var role = new IdentityRole();
                role.Name = "Admin";
                roleManager.Create(role);
            }
            // Create admin role
            if (applicationUserManager.FindByName("admin") == null)
            {
                var user = new ApplicationUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";
                string passsword = "Admin123";
                var    chkUser   = applicationUserManager.Create(user, passsword);
                if (chkUser.Succeeded)
                {
                    applicationUserManager.AddToRole(user.Id, "Admin");
                }
            }
            //Create manager Role
            if (!roleManager.RoleExists("Manager"))
            {
                var role = new IdentityRole();
                role.Name = "Manager";
                roleManager.Create(role);
            }
            // Create manager role
            if (applicationUserManager.FindByName("manager") == null)
            {
                var user = new ApplicationUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";
                string passsword = "Manager123";
                var    chkUser   = applicationUserManager.Create(user, passsword);
                if (chkUser.Succeeded)
                {
                    applicationUserManager.AddToRole(user.Id, "Manager");
                }
            }
            //Create customer Role
            bool isCexists = roleManager.RoleExists("Customer");

            if (!isCexists)
            {
                var role = new IdentityRole();
                role.Name = "Customer";
                roleManager.Create(role);
            }
        }
Esempio n. 31
0
        public async Task<ApplicationUser> Authorize(string token)
        {
            var fbClient = new FacebookClient(token);
            dynamic me = await fbClient.GetTaskAsync("me");

            var adminEmail = CloudConfigurationManager.GetSetting("email");

            try
            {
                var userStore = new ApplicationUserStore();

                var user = await userStore.FindByIdAsync(me.id);
                if (user == null)
                {
                    var newUser = new ApplicationUser()
                                      {
                                          Email = me.email,
                                          Id = me.id,
                                          UserName = me.email,
                                          Role = adminEmail == me.email ? "Admin" : "User",
                                          FirstName = me.first_name,
                                          LastName = me.last_name
                                      };

                    await userStore.CreateAsync(newUser);

                    return newUser;
                }

                return user;
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                return null;
            }
        }
Esempio n. 32
0
 public UserRepository()
 {
     _userStore = new ApplicationUserStore();
     _userManager = new ApplicationUserManager(_userStore);
     //_signInManager = new AppSignInManager();
 }