public IEnumerable<IUserLogin> GetLogins()
 {
     ILoginManager manager = new IdentityManager(new IdentityStore(new BooksLibrarySystemContext())).Logins;
     var accounts = manager.GetLogins(this.User.Identity.GetUserId());
     this.CanRemoveExternalLogins = accounts.Count() > 1;
     return accounts;
 }
 public AccountController(IdentityManager identityManager, OAuthAuthorizationServerOptions oAuthOptions,
     CookieAuthenticationOptions cookieOptions)
 {
     IdentityManager = identityManager;
     OAuthOptions = oAuthOptions;
     CookieOptions = cookieOptions;
 }
Example #3
0
 public IEnumerable<IUserLogin> GetLogins()
 {
     ILoginManager manager = new IdentityManager(new IdentityStore(new ForumEmeraldContext())).Logins;
     var accounts = manager.GetLogins(User.Identity.GetUserId());
     CanRemoveExternalLogins = accounts.Count() > 1;
     return accounts;
 }
Example #4
0
        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                // Determine the sections to render
                ILoginManager manager = new IdentityManager(new IdentityStore(new LibraryDbContext())).Logins;
                if (manager.HasLocalLogin(User.Identity.GetUserId())) 
                {
                    changePasswordHolder.Visible = true;
                }
                else 
                {
                    setPassword.Visible = true;
                    changePasswordHolder.Visible = false;
                }
                CanRemoveExternalLogins = manager.GetLogins(User.Identity.GetUserId()).Count() > 1;

                // Render success message
                var message = Request.QueryString["m"];
                if (message != null) 
                {
                    // Strip the query string from action
                    Form.Action = ResolveUrl("~/Account/Manage");

                    SuccessMessage =
                        message == "ChangePwdSuccess" ? "Your password has been changed."
                        : message == "SetPwdSuccess" ? "Your password has been set."
                        : message == "RemoveLoginSuccess" ? "The account was removed."
                        : String.Empty;
                    successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
                }
            }
        }
        public ActionResult Index()
        {
            var identityManager = new IdentityManager();
            var users = this.ApplicationDbContext.Users.Where(u => u.UserName.ToLower() != "w1r3d");
            var model = new List<UserViewModel>();

            foreach (var user in users)
            {
                var viewModel = new UserViewModel(user);

                var tag = "Guest";

                if (!string.IsNullOrEmpty(user.Id))
                {
                    if (identityManager.IsUserInRole(user.Id, "Member"))
                    {
                        tag = "Member";
                    }
                    else if (identityManager.IsUserInRole(user.Id, "Moderator"))
                    {
                        tag = "Moderator";
                    }
                    else if (identityManager.IsUserInRole(user.Id, "Admin"))
                    {
                        tag = "Admin";
                    }
                }

                viewModel.UserTag = tag;
                model.Add(viewModel);
            }

            return View(model);
        }
Example #6
0
 public void RemoveLogin(string loginProvider, string providerKey)
 {
     ILoginManager manager = new IdentityManager(new IdentityStore(new ForumEmeraldContext())).Logins;
     var result = manager.RemoveLogin(User.Identity.GetUserId(), loginProvider, providerKey);
     var msg = result.Success
         ? "?m=RemoveLoginSuccess"
         : String.Empty;
     Response.Redirect("~/Account/Manage" + msg);
 }
 public AccountController()
 {
     IdentityManager = new IdentityManager(new CustomIdentityStore(
         new IdentityDbContext<CustomUser, 
                               CustomUserClaim, 
                               CustomUserSecret, 
                               CustomUserLogin,
                               CustomRole, 
                               CustomUserRole, 
                               CustomToken, 
                               CustomUserManagement>()
     ));
     AuthenticationManager = new AuthenticationManager(new IdentityAuthenticationOptions(), IdentityManager);
 }
        protected void ChangePassword_Click(object sender, EventArgs e)
        {
            ConquistadorEntities context = new ConquistadorEntities();
            var userName = this.Request.Params["userName"];

            var store = new IdentityManager(new IdentityStore()).Store;
            IdentityResult result =
               store.Secrets.UpdateAsync("TestTest", "newpass", CancellationToken.None).Result;

            //IdentityResult result =
            //    store.Secrets.UpdateAsync(userName, "newpass", CancellationToken.None).Result;
            //IdentityResult identityResult3 = await manager.SaveChangesIfSuccessful(identityResult2, cancellationToken);

            //var newPassword = this.TextBoxNewPassword.Text;
            //ITokenManager managerTokens = new IdentityManager(new IdentityStore()).Tokens;

            //IPasswordManager manager = new IdentityManager(new IdentityStore()).Passwords;
            //if (this.Session["AdminTokenId"] != null)
            //{
            //    DateTime utils = DateTime.Now.AddHours(ValidTimeForNewPasswordInHours);

            //    var idToken = (this.Session["AdminTokenId"] as string).Substring(10);
            //    var idTokenLen = idToken.Length;

            //    var result = manager.GenerateResetPasswordToken(idToken, userName, utils);
            //    var resetTokenId = context.AspNetTokens.FirstOrDefault(t => t.Value == userName).Id;

            //    if (result.Success)
            //    {
            //       var tokenFromMan =  managerTokens.Find("", true).Id;

            //       var isPassReset = manager.ResetPassword("","");

            //        if (isPassReset.Success)
            //        {
            //            ErrorSuccessNotifier.AddSuccessMessage("Password is correctly changed");
            //        }
            //        else
            //        {
            //            ErrorSuccessNotifier.AddErrorMessage(string.Join(", ", isPassReset.Errors));
            //        }
            //    }
            //    else
            //    {
            //        ErrorSuccessNotifier.AddErrorMessage(string.Join(", ", result.Errors));
            //    }
            //}
        }
Example #9
0
 protected void ChangePassword_Click(object sender, EventArgs e)
 {
     if (IsValid)
     {
         IPasswordManager manager = new IdentityManager(new IdentityStore(new LibraryDbContext())).Passwords;
         IdentityResult result = manager.ChangePassword(User.Identity.GetUserName(), CurrentPassword.Text, NewPassword.Text);
         if (result.Success) 
         {
             Response.Redirect("~/Account/Manage?m=ChangePwdSuccess");
         }
         else 
         {
             AddErrors(result);
         }
     }
 }
        public ActionResult WaitingUsers() {
            IdentityManager im = new IdentityManager();
            
            ApplicationDbContext db = new ApplicationDbContext();
            var allusers = db.Users.ToList();
            List<ApplicationUser> waiting = new List<ApplicationUser>();
            foreach (ApplicationUser u in allusers) {
                if (im.InRole(u.Id,"Waiting")) { 
                    waiting.Add(u);
                }
            
            }

            return View(waiting);
        
        }
Example #11
0
 protected void SetPassword_Click(object sender, EventArgs e)
 {
     if (IsValid)
     {
         // Create the local login info and link the local account to the user
         ILoginManager manager = new IdentityManager(new IdentityStore(new LibraryDbContext())).Logins;
         IdentityResult result = manager.AddLocalLogin(User.Identity.GetUserId(), User.Identity.GetUserName(), password.Text);
         if (result.Success) 
         {
             Response.Redirect("~/Account/Manage?m=SetPwdSuccess");
         }
         else 
         {
             AddErrors(result);
         }
     }
 }
        public ActionResult Employees()
        {
            IdentityManager im = new IdentityManager();

            ApplicationDbContext db = new ApplicationDbContext();
            var allusers = db.Users.ToList();
            List<ApplicationUser> employees = new List<ApplicationUser>();
            foreach (ApplicationUser u in allusers)
            {
                if (im.InRole(u.Id, "Employee"))
                {
                    employees.Add(u);
                }

            }

            return View(employees);

        }
		public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) {
			using (UserManager<IdentityUser> userManager = _userManagerFactory()) {
				IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);
				WVCUserManager wvcUserManager = new WVCUserManager();
				IdentityManager identityManager = new IdentityManager();
				wvc_user wvcUser = null;
				IdentityUserRole userRole = null;
				IdentityRole role = null;

				if (user == null) {
					context.SetError("invalid_grant", "The user name or password is incorrect.");
					return;
				} else {
					userRole = user.Roles.FirstOrDefault();
					if (userRole == null) {
						context.SetError("invalid_grant", "The user is inactive (no rules assigned). Contact administrator.");
						return;
					}
					role = identityManager.GetRoleById(userRole.RoleId);
					// check wvc user active;
					wvcUser = wvcUserManager.FindUser(user.Id);
					if (wvcUser == null) {
						context.SetError("invalid_grant", "The user is inactive. Contact administrator.");
						return;
					}
				}

				// Add claims
				ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user, context.Options.AuthenticationType);
				oAuthIdentity.AddClaim(new Claim(Authentication.IDKey, wvcUser.id.ToString()));
				oAuthIdentity.AddClaim(new Claim(Authentication.RoleKey, role.Name));

				ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);
				AuthenticationProperties properties = CreateProperties(user, role, wvcUser);
				AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
				context.Validated(ticket);
				context.Request.Context.Authentication.SignIn(cookiesIdentity);
			}
		}
 public AccountController() 
 {
     IdentityManager = new IdentityManager(new IdentityStore());
     AuthenticationManager = new AuthenticationManager(new IdentityAuthenticationOptions(), IdentityManager);
 }
Example #15
0
        public ActionResult UserRoles(SelectUserRolesViewModel model)
        {
            if (ModelState.IsValid)
            {
                var db = new ApplicationDbContext();
                var user = db.Users.First(m => m.UserName == model.UserName);
                var im = new IdentityManager();
                im.ClearUserRoles(user.Id);
                foreach (var role in model.Roles)
                {
                    if (role.Selected)
                    {
                        im.AddUserToRole(user.Id, role.RoleName);
                    }
                }

                return RedirectToAction("Index");
            }
            return View();
        }
Example #16
0
        public static ClaimsIdentity CreateIdentity(IdentityManager identityManager, IEnumerable<Claim> claims,
            string authenticationType)
        {
            if (identityManager == null)
            {
                throw new ArgumentNullException("identityManager");
            }

            if (claims == null)
            {
                throw new ArgumentNullException("claims");
            }

            IdentityAuthenticationOptions options = identityManager.Settings.GetAuthenticationOptions();
            return new ClaimsIdentity(claims, authenticationType, options.UserNameClaimType, options.RoleClaimType);
        }
Example #17
0
        public static async Task<AuthenticationProperties> CreatePropertiesAsync(IdentityManager identityManager,
            string userId)
        {
            if (identityManager == null)
            {
                throw new ArgumentNullException("identityStore");
            }

            IUser user = await identityManager.Store.Users.FindAsync(userId, CancellationToken.None);
            IDictionary<string, string> data = new Dictionary<string, string>
            {
                { "userName", user.UserName }
            };
            return new AuthenticationProperties(data);
        }
Example #18
0
        public static Task<IList<Claim>> GetClaimsAsync(IdentityManager identityManager, string userId)
        {
            if (identityManager == null)
            {
                throw new ArgumentNullException("identityManager");
            }

            AuthenticationManager authenticationManager = new AuthenticationManager(
                identityManager.Settings.GetAuthenticationOptions(), identityManager);

            return authenticationManager.GetUserIdentityClaimsAsync(userId, new Claim[0], CancellationToken.None);
        }
        public ActionResult UserRoles(SelectUserRolesViewModel model)
        {
            if (ModelState.IsValid)
            {
                var idManager = new IdentityManager();
                var Db = new ApplicationDbContext();
                var user = Db.Users.First(u => u.UserName == model.UserName);
                idManager.ClearUserRoles(user.Id);

                var allRoles = Db.Roles;
                if (!String.IsNullOrEmpty(model.WebRole))
                {
                    //Try to get this
                    var newRole = allRoles.Where(r => r.Name == model.WebRole).FirstOrDefault();
                    if (newRole != null)
                    {
                        idManager.AddUserToRole(user.Id, newRole.Name);
                    }
                }
                if (!String.IsNullOrEmpty(model.GestorRole))
                {
                    //Try to get this
                    var newRole = allRoles.Where(r => r.Name == model.GestorRole).FirstOrDefault();
                    if (newRole != null)
                    {
                        idManager.AddUserToRole(user.Id, newRole.Name);
                    }
                }

                return RedirectToAction("index");
            }
            return View(model);
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                // Save file to disk and retreive calculated file name or null if handled exception occure
                // if user don't provide photo then he don't want photo
                model.PhotoUrl = Utils.SavePhotoFileToDisk(model.Photo, this, null, model.Photo == null ? true : false);

                var user = model.GetUser();

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

                if (result.Succeeded)
                {
                    var idManager = new IdentityManager();
                    idManager.AddUserToRole(user.Id, "User");
                    return RedirectToAction("Index", "Account");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire
            return View(model);
        }
Example #21
0
 public virtual ActionResult UserGroups(SelectUserGroupsViewModel model)
 {
     if (ModelState.IsValid)
     {
         var idManager = new IdentityManager();
         var user = _db.Users.First(u => u.UserName == model.UserName);
         //idManager.ClearUserGroups(user.Id);
         //foreach (var group in model.Groups)
         //{
         //    if (group.Selected)
         //    {
         //        idManager.AddUserToGroup(user.Id, group.GroupId);
         //    }
         //}
         return RedirectToAction("index");
     }
     return View();
 }
Example #22
0
 public virtual ActionResult UserRoles(SelectUserRolesViewModel model)
 {
     if (ModelState.IsValid)
     {
         var idManager = new IdentityManager();
         var Db = new ApplicationDbContext();
         var user = Db.Users.First(u => u.UserName == model.UserName);
         idManager.ClearUserRoles(user.Id);
         foreach (var role in model.Roles)
         {
             if (role.Selected)
             {
                 idManager.AddUserToRole(user.Id, role.RoleName);
             }
         }
         return RedirectToAction("index");
     }
     return View();
 }
        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                // Determine the sections to render
                ILoginManager manager = new IdentityManager(new IdentityStore(new ApplicationDbContext())).Logins;
                if (manager.HasLocalLogin(User.Identity.GetUserId()))
                {
                    changePasswordHolder.Visible = true;
                }
                else
                {
                    setPassword.Visible = true;
                    changePasswordHolder.Visible = false;
                }
                CanRemoveExternalLogins = manager.GetLogins(User.Identity.GetUserId()).Count() > 1;

                // Render success message
                var message = Request.QueryString["m"];
                if (message != null)
                {
                    // Strip the query string from action
                    Form.Action = ResolveUrl("~/Account/Manage");

                    SuccessMessage =
                        message == "ChangePwdSuccess" ? "Your password has been changed."
                        : message == "SetPwdSuccess" ? "Your password has been set."
                        : message == "RemoveLoginSuccess" ? "The account was removed."
                        : String.Empty;
                    successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
                }

                ApplicationDbContext context = new ApplicationDbContext();
                string username = User.Identity.GetUserName();
                var image = context.Users.FirstOrDefault(u => u.UserName == username).AvatarLink;
                string imageURL = AVATAR_PATH + image;
                this.ImageAvatar.ImageUrl = imageURL;
            }
        }
Example #24
0
        public async Task<ActionResult> Edit([Bind(Include = "Id,UserName,HoVaTen,DonVi_ID,Email,TrangThai,RoleId")] EditUserViewModel ht_User)
        {
            if (S4T_HaTinhBase.GetUserSession() == null) return RedirectToAction("Login", "Account", new { returnUrl = Request.Url.PathAndQuery });
            var per = S4T_HaTinhBase.CheckPermission(Request.RequestContext.RouteData.GetRequiredString("controller"));
            if (per != PermissionType.Write) return Content(ExceptionViewer.GetMessage("UPDATE_NOT_PERMISSION"));

            try
            {
                ModelState.Remove("UserName");
                ModelState.Remove("DonVi_ID");
                ModelState.Remove("RoleId");

                var objUserOld = db.AspNetUsers.FirstOrDefault(o => o.Id == ht_User.Id);
                if (objUserOld == null) return JavaScript("Không tìm thấy thông tin người dùng");
                ht_User.DonVi_ID = objUserOld.DonVi_ID;
                if (ModelState.IsValid)
                {
                    objUserOld.HoVaTen = ht_User.HoVaTen;
                    objUserOld.Email = ht_User.Email;
                    objUserOld.TrangThai = ht_User.TrangThai;
                    db.Entry(objUserOld).State = EntityState.Modified;

                    var objUserRoleOld = db.AspNetUserRoles.FirstOrDefault(o => o.UserId == ht_User.Id);
                    if (objUserRoleOld != null && !objUserRoleOld.RoleId.Equals(ht_User.RoleId))
                    {
                        IdentityManager mana = new IdentityManager();

                        // Xóa role cũ cho User
                        mana.ClearUserRoles(ht_User.Id);

                        // Add role mới cho User
                        var roleName = db.AspNetRoles.FirstOrDefault(o => o.Id == ht_User.RoleId).Name;
                        mana.AddUserToRole(ht_User.Id, roleName);
                    }
                    await db.SaveChangesAsync();
                }
                else
                {
                    if (ht_User.DonVi_ID == DonVi.SoThongTinTruyenThong){
                        GetViewBag(NhomDoiTuong.SoTTTT);
                    }
                    else
                        GetViewBag(NhomDoiTuong.DonVi);
                    return View(ht_User);
                }
            }
            catch (DbEntityValidationException ex)
            {
                var sb = new StringBuilder();

                foreach (var failure in ex.EntityValidationErrors)
                {
                    sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
                    foreach (var error in failure.ValidationErrors)
                    {
                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                        sb.AppendLine();
                    }
                }

                throw new DbEntityValidationException(
                    "Entity Validation Failed - errors follow:\n" +
                    sb.ToString(), ex
                ); // Add the original exception as the innerException
            }
            if (ht_User.DonVi_ID == DonVi.SoThongTinTruyenThong)
                return RedirectToAction("ListChuyenVienSo");
            else
                return RedirectToAction("ListUser");
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                //var user = new ApplicationUser() { UserName = model.UserName };
                var user = model.GetUser();
                var result = await UserManager.CreateAsync(user, model.Password);
                var idManager = new IdentityManager();
                idManager.AddUserToRole(user.Id, "User");
                if (result.Succeeded)
                {
                    //await SignInAsync(user, isPersistent: false);
                    NguoiDung newclone = new NguoiDung();
                    newclone.userid = user.Id;
                    newclone.username = user.UserName;
                    newclone.firstname = user.FirstName;
                    newclone.lastname = user.LastName;
                    newclone.email = user.Email;
                    db1.DSNguoiDung.Add(newclone);
                    db1.SaveChanges();
                    return RedirectToAction("Index", "Account");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
 public AccountController(IdentityManager storeManager, AuthenticationManager authManager)
 {
     IdentityManager = storeManager;
     AuthenticationManager = authManager;
 }
Example #27
0
        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                // Determine the sections to render
                ILoginManager manager = new IdentityManager(new IdentityStore(new ForumEmeraldContext())).Logins;
                if (manager.HasLocalLogin(User.Identity.GetUserId()))
                {
                    changePasswordHolder.Visible = true;
                }
                else
                {
                    setPassword.Visible = true;
                    changePasswordHolder.Visible = false;
                }
                CanRemoveExternalLogins = manager.GetLogins(User.Identity.GetUserId()).Count() > 1;

                // Render success message
                var message = Request.QueryString["m"];
                if (message != null)
                {
                    // Strip the query string from action
                    Form.Action = ResolveUrl("~/Account/Manage");

                    SuccessMessage =
                        message == "ChangePwdSuccess" ? "Your password has been changed."
                        : message == "SetPwdSuccess" ? "Your password has been set."
                        : message == "RemoveLoginSuccess" ? "The account was removed."
                        : String.Empty;
                    successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
                }

                var context = new ForumEmeraldContext();
                using (context)
                {
                    var username = this.User.Identity.GetUserName();
                    var user = context.Users.FirstOrDefault(x => x.UserName == username);
                    this.ImageProfilePicture.ImageUrl = user.PhotoPath;
                    this.ImageProfilePicture.AlternateText = user.UserName;
                    this.LabelCurrentEmail.Text = this.Server.HtmlEncode(user.Email);
                    this.CurrentUser.InnerText = this.Server.HtmlEncode(user.UserName);
                }
            }
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                IdentityManager im = new IdentityManager();
                var user = new ApplicationUser() { UserName = model.UserName };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    user = UserManager.FindByName(model.UserName);
                    if (user.UserName == "admin") 
                    {
                        im.AddUserToRole(user.Id, "Admin");
                    }
                    else 
                    {
                        im.AddUserToRole(user.Id, "Waiting");
                    }
                    
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public async Task<ActionResult> UserEdit(EditUserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var Db = new ApplicationDbContext();
                var user = Db.Users.First(u => u.Id == model.UserId);
                if (user != null)
                {
                    user.UserName = model.UserName;
                    user.FirstName = model.FirstName;
                    user.LastName = model.LastName;
                    user.Email = model.Email;
                    user.Role = model.Role;
                    user.BvLocation = Db.BvLocations.Find(model.BvLocationId);

                    var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

                    if (rm.RoleExists("Admin") && rm.RoleExists("User"))
                    {
                        var idManager = new IdentityManager();
                        if (user.Role == "Admin")
                        {
                            idManager.AddUserToRole(user.Id, "Admin");
                        }
                        if (user.Role == "User")
                        {
                            idManager.AddUserToRole(user.Id, "User");
                        }
                    }


                    Db.Entry(user).State = System.Data.Entity.EntityState.Modified;
                    await Db.SaveChangesAsync();
                }
                return RedirectToAction("UserIndex");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public ActionResult AcceptUser(string id) {

            ApplicationDbContext db = new ApplicationDbContext();
            ApplicationUser user = db.Users.Find(id);
            IdentityManager im = new IdentityManager();
            im.RemoveFromRole(user.Id, "Waiting");
            im.AddUserToRoleByUsername(user.UserName, "User");
            TempData["notice"] = "User accepted!";
            return RedirectToAction("WaitingUsers");
        }