public async Task<JsonData> ChangePassword(ChangePasswordModel changePass)
        {
            try
            {
                var db = new DataContext();
                var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));
                userMan.UserValidator = new UserValidator<MyUser>(userMan)
                {
                    AllowOnlyAlphanumericUserNames =
                        false
                };

                var user = await userMan.FindByIdAsync(User.Identity.GetUserId());
                if (user == null) throw new Exception("please check your old password");

                var newPassword = changePass.NewPassword;
                var result = await userMan.RemovePasswordAsync(user.Id);
                if (!result.Succeeded) throw new Exception(string.Join(", ", result.Errors));
                var result2 = await userMan.AddPasswordAsync(user.Id, newPassword);
                if (!result2.Succeeded) throw new Exception(string.Join(", ", result2.Errors));
                return DataHelpers.ReturnJsonData(null, true, "Password changed successful");
            }
            catch (Exception e)
            {
                return DataHelpers.ExceptionProcessor(e);
            }
        }
Exemplo n.º 2
0
        public async Task<WikiDownUser> Save(IPrincipal principal, UserManager<WikiDownUser> userManager)
        {
            var user = await userManager.FindByNameAsync(this.UserName);

            var roles = this.GetRoles(principal, user);

            if (user != null)
            {
                if (user.UserName == principal.Identity.Name)
                {
                    var userAccessLevel = ArticleAccessHelper.GetAccessLevel(user.Roles);
                    if (userAccessLevel < ArticleAccessLevel.Admin)
                    {
                        throw new HttpResponseException(HttpStatusCode.BadRequest);
                    }
                }

                user.SetRoles(roles);
                user.SetDisplayName(this.DisplayName);
                user.SetEmail(this.Email);

                if (!string.IsNullOrWhiteSpace(this.Password))
                {
                    await userManager.RemovePasswordAsync(user.Id);
                    await userManager.AddPasswordAsync(user.Id, this.Password);
                }

                await userManager.UpdateAsync(user);

                WikiDownUserCacheHelper.Clear(user.UserName);
            }
            else
            {
                user = new WikiDownUser(this.UserName) { Roles = roles };
                user.SetDisplayName(this.DisplayName);
                user.SetEmail(this.Email);

                await userManager.CreateAsync(user, this.Password);
            }

            return user;
        }
Exemplo n.º 3
0
        public virtual async Task <IdentityUserDto> UpdateAsync(Guid id, IdentityUserUpdateDto input)
        {
            var user = await UserManager.GetByIdAsync(id);

            user.ConcurrencyStamp = input.ConcurrencyStamp;

            (await UserManager.SetUserNameAsync(user, input.UserName)).CheckErrors();

            await UpdateUserByInput(user, input);

            input.MapExtraPropertiesTo(user);

            (await UserManager.UpdateAsync(user)).CheckErrors();

            if (!input.Password.IsNullOrEmpty())
            {
                (await UserManager.RemovePasswordAsync(user)).CheckErrors();
                (await UserManager.AddPasswordAsync(user, input.Password)).CheckErrors();
            }

            await CurrentUnitOfWork.SaveChangesAsync();

            return(ObjectMapper.Map <IdentityUser, IdentityUserDto>(user));
        }
        public async Task <IActionResult> SetPassword(SetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await GetCurrentUserAsync();

            if (user != null)
            {
                var result = await _userManager.AddPasswordAsync(user, model.NewPassword);

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

                    return(RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess }));
                }
                AddErrors(result);
                return(View(model));
            }
            return(RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }));
        }
Exemplo n.º 5
0
 public Task <IdentityResult> AddPasswordAsync(T user, string password)
 {
     return(u.AddPasswordAsync(user, password));
 }
Exemplo n.º 6
0
        public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordModel model)
        {
            var emp = await FindEmployeeAsync(model.UserId);

            if (emp?.User == null)
            {
                return(NotFound());
            }

            var target   = emp.User;
            var is_admin = await IsAdmin();

            var is_builtin = await IsBuiltInAdmin();

            var is_self = emp.UserId == GetUserId();
            var hasPwd  = await UserManager.HasPasswordAsync(target);

            var OldPasswordHash = string.Empty;

            if (hasPwd)
            {
                OldPasswordHash = target.PasswordHash;
            }

            if (!is_self)
            {
                // somebody's trying to update another user

                if (!is_admin)
                {
                    // a non-administrator cannot update another user
                    return(BadRequest());
                }

                if (!is_builtin && target.IsAdministrator)
                {
                    // only the built-in administrator can modify another admin
                    return(BadRequest());
                }

                return(await change_admin_pwd());
            }
            else if (is_admin || is_builtin)
            {
                return(await change_admin_pwd());
            }
            else if (string.IsNullOrWhiteSpace(model.OldPassword))
            {
                return(BadRequest(ModelState.AddError(string.Empty, ChangePasswordOldRequired)));
            }

            // when simple users change their password
            IdentityResult result;

            if (hasPwd)
            {
                result = await UserManager.ChangePasswordAsync(target, model.OldPassword, model.NewPassword);
            }
            else
            {
                result = await UserManager.AddPasswordAsync(target, model.NewPassword);
            }

            if (result.Succeeded)
            {
                return(await change_pwd_success());
            }

            return(BadRequest(ModelState.AddError(string.Empty, ChangePasswordBadAttempt)));

            // when an admin changes a user's password, no need to specify the old one
            async Task <IActionResult> change_admin_pwd()
            {
                IdentityResult res;

                if (hasPwd)
                {
                    target.PasswordHash = UserManager.PasswordHasher.HashPassword(target, model.NewPassword);
                    res = await UserManager.UpdateAsync(target);
                }
                else
                {
                    res = await UserManager.AddPasswordAsync(target, model.NewPassword);
                }

                if (res.Succeeded)
                {
                    return(await change_pwd_success());
                }

                return(BadRequest(ModelState.AddError(string.Empty, ChangePasswordFailed)));
            }

            async Task <IActionResult> change_pwd_success()
            {
                var user = target;

                if (!is_self)
                {
                    user = await FindUserAsync();
                }

                await EventLogger.LogAsync(SysEventType.UserPasswordChanged, user, target, new { UserId = user.Id, OldPasswordHash });

                return(Ok());
            }
        }
        public async Task <IActionResult> Patch(string key, [FromBody] JObject data)
        {
            var user = await userManager.FindByIdAsync(key);

            if (user == null)
            {
                return(NotFound());
            }

            EntityPatch.Apply(user, data);

            var roles = data.GetValue("RoleNames").ToObject <IEnumerable <string> >();

            OnUserUpdated(user);

            IdentityResult result = null;

            if (roles != null)
            {
                result = await userManager.RemoveFromRolesAsync(user, await userManager.GetRolesAsync(user));

                if (!result.Succeeded)
                {
                    return(IdentityError(result));
                }

                if (roles.Any())
                {
                    result = await userManager.AddToRolesAsync(user, roles);
                }

                if (!result.Succeeded)
                {
                    return(IdentityError(result));
                }
            }

            var password = data.GetValue("Password", StringComparison.OrdinalIgnoreCase).ToObject <string>();

            if (password != null)
            {
                result = await userManager.RemovePasswordAsync(user);

                if (!result.Succeeded)
                {
                    return(IdentityError(result));
                }

                result = await userManager.AddPasswordAsync(user, password);

                if (!result.Succeeded)
                {
                    return(IdentityError(result));
                }
            }

            result = await userManager.UpdateAsync(user);

            if (!result.Succeeded)
            {
                return(IdentityError(result));
            }

            return(new NoContentResult());
        }
        public async Task <IActionResult> ResetPassword(Skoruba.IdentityServer4.AspNetIdentity.Quickstart.Account.ResetPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                model.UserName = model.UserName.ToLower();

                var userExisted = await _userManager.FindByNameAsync(model.UserName);

                if (userExisted == null)
                {
                    ModelState.AddModelError(nameof(model.UserName), "账号不存在");
                    return(View(model));
                }
                else if (userExisted.Email != model.Email)
                {
                    if (string.IsNullOrWhiteSpace(userExisted.Email))
                    {
                        ModelState.AddModelError(nameof(model.Email), "激活时填写的Email地址有误,请联系管理员。");
                        return(View(model));
                    }
                    else
                    {
                        System.Text.RegularExpressions.Regex regex = new Regex("(\\w)(\\s+)@(\\w)(\\s+)\\.(\\w+)");
                        var match = regex.Match(userExisted.Email);
                        var msg   = string.Empty;
                        if (match.Success)
                        {
                            msg = $"{match.Groups[1].Value}{new string('*', match.Groups[2].Value.Length)}@{match.Groups[3].Value}{new string('*', match.Groups[4].Value.Length)}.{match.Groups[5].Value}";
                        }
                        ModelState.AddModelError(nameof(model.Email), $"与激活时填写的地址不符:{msg}");
                        return(View(model));
                    }
                }
                else
                {
                    var r = await _userManager.RemovePasswordAsync(userExisted);

                    if (r.Succeeded)
                    {
                        var r2 = await _userManager.AddPasswordAsync(userExisted, model.Password);

                        if (r2.Succeeded)
                        {
                            return(RedirectToAction(nameof(Login), new { model.ReturnUrl }));
                        }
                        else
                        {
                            _logger.LogWarning("设置用户密码失败:", string.Join(";", r.Errors.Select(x => x.Description)));
                            ModelState.AddModelError("", "设置用户密码失败");
                        }
                    }
                    else
                    {
                        _logger.LogWarning("移除用户密码失败:", string.Join(";", r.Errors.Select(x => x.Description)));
                        ModelState.AddModelError("", "移除用户密码失败");
                    }
                }
            }

            // something went wrong, show form with error
            return(View(model));
        }
Exemplo n.º 9
0
        public static async Task Initialize(ApplicationDbContext context,
                                            UserManager <AccountUser> userManager,
                                            RoleManager <AccountRole> roleManager)
        {
            context.Database.EnsureCreated();


            String adminId1 = "";
            // String adminId2 = "";

            string role1 = "Manager";
            string desc1 = "This is the Manager role";

            string role2 = "Reception";
            string desc2 = "This is the Reception role";

            string role3 = "Housekeeper";
            string desc3 = "This is the Housekeeper role";

            string role4 = "Staff";
            string desc4 = "This is the staff role";



            string password = "******";

            if (await roleManager.FindByNameAsync(role1) == null)
            {
                await roleManager.CreateAsync(new AccountRole(role1, desc1));
            }
            if (await roleManager.FindByNameAsync(role2) == null)
            {
                await roleManager.CreateAsync(new AccountRole(role2, desc2));
            }
            if (await roleManager.FindByNameAsync(role3) == null)
            {
                await roleManager.CreateAsync(new AccountRole(role3, desc3));
            }
            if (await roleManager.FindByNameAsync(role4) == null)
            {
                await roleManager.CreateAsync(new AccountRole(role4, desc4));
            }


            if (await userManager.FindByNameAsync("*****@*****.**") == null)
            {
                var user = new AccountUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "6902341234",
                    //Group = "Admin",
                    CreationDate = DateTime.Now
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role1);
                }
                // adminId1 = user.Id;
            }

            if (await userManager.FindByNameAsync("*****@*****.**") == null)
            {
                var user = new AccountUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "88322392",
                    //Group = "Admin",
                    CreationDate = DateTime.Now
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role2);
                }
                // adminId1 = user.Id;
            }
            if (await userManager.FindByNameAsync("*****@*****.**") == null)
            {
                var user = new AccountUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    PhoneNumber = "123123123",
                    //Group = "Admin",
                    CreationDate = DateTime.Now
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role3);
                }
                // adminId1 = user.Id;
            }

            if (context.Rooms.Count() == 0)
            {
                var rooms = new Room[]
                {
                    new Room {
                        RoomType = roomType.Single, RoomNum = "R01", Status = Status.VacantClean, Description = "Mamimum two customers can stay in this room"
                    },
                    new Room {
                        RoomType = roomType.Single, RoomNum = "R02", Status = Status.VacantClean, Description = "Mamimum two customers can stay in this room"
                    },
                    new Room {
                        RoomType = roomType.Single, RoomNum = "R03", Status = Status.VacantClean, Description = "Mamimum two customers can stay in this room"
                    },

                    new Room {
                        RoomType = roomType.TwoBedRooms, RoomNum = "R04", Status = Status.VacantClean, Description = "Mamimum four customers can stay in this roo"
                    },
                    new Room {
                        RoomType = roomType.TwoBedRooms, RoomNum = "R05", Status = Status.VacantClean, Description = "Mamimum four customers can stay in this roo"
                    },
                    new Room {
                        RoomType = roomType.TwoBedRooms, RoomNum = "R06", Status = Status.VacantClean, Description = "Mamimum four customers can stay in this roo"
                    },

                    new Room {
                        RoomType = roomType.Superior, RoomNum = "R07", Status = Status.VacantClean, Description = "Mamimum two customers can stay in this room"
                    },
                    new Room {
                        RoomType = roomType.Superior, RoomNum = "R08", Status = Status.VacantClean, Description = "Mamimum two customers can stay in this room"
                    },
                    new Room {
                        RoomType = roomType.Superior, RoomNum = "R09", Status = Status.VacantClean, Description = "Mamimum two customers can stay in this room"
                    },
                };

                foreach (Room r in rooms)
                {
                    context.Rooms.Add(r);
                }
            }
            context.SaveChanges();
        }
Exemplo n.º 10
0
        public async Task <IActionResult> AddDefaultUsers(string pass)
        {
            var uExist = await _userManager.FindByNameAsync("admin");

            if (uExist == null)
            {
                if (!addDefaultPass.Equals(pass))
                {
                    ViewBag.Message   = "——密码错误,请重新输入——";
                    ViewBag.PassError = true;
                    return(View());
                }
                ApplicationRole adminRole = null;
                ApplicationRole userRole  = null;
                //?判断用户组是否存在
                var roleExists = await _roleManager.RoleExistsAsync("Admin");

                if (!roleExists)
                {
                    adminRole = new ApplicationRole()
                    {
                        Name = "Admin", DisplayName = "系统管理人员", Description = "适用于系统管理人员", ApplicationRoleType = ApplicationRoleTypeEnum.适用于系统管理人员, SortCode = "69a5f56g"
                    };
                    userRole = new ApplicationRole()
                    {
                        Name = "AverageUser", DisplayName = "普通注册用户", Description = "适用于普通注册用户", ApplicationRoleType = ApplicationRoleTypeEnum.适用于普通注册用户, SortCode = "99avf56g"
                    };
                    await _roleManager.CreateAsync(adminRole);

                    await _roleManager.CreateAsync(userRole);
                }

                //添加默认用户
                var password = "******";
                for (int i = 0; i < 5 + 1; i++)
                {
                    var user = new ApplicationUser();

                    if (i == 0)
                    {
                        user = new ApplicationUser()
                        {
                            UserName        = "******",
                            FirstName       = "易站",
                            LastName        = "超级管理员",
                            ChineseFullName = user.FirstName + user.LastName,
                            Email           = "*****@*****.**"
                        };
                        var addAdmin = await _userManager.CreateAsync(user);

                        var addAdminPassword = await _userManager.AddPasswordAsync(user, password);

                        //查询用户是否已经添加了权限 若不在添加进用户组
                        if (!await _userManager.IsInRoleAsync(user, adminRole.Name))
                        {
                            var roleOK = await _userManager.AddToRoleAsync(user, adminRole.Name);
                        }
                    }
                    else
                    {
                        user = new ApplicationUser()
                        {
                            UserName        = i == 1 ? "demo" : ("demo00" + (i - 1).ToString()),
                            FirstName       = "易站演示",
                            LastName        = "用户" + (i - 1),
                            ChineseFullName = "易站普通用户" + (i - 1),
                            Email           = i == 1 ? "demo" : ("demo00" + (i - 1).ToString()) + "@925i.cn"
                        };
                        var addUser = await _userManager.CreateAsync(user);

                        var addUserPassword = await _userManager.AddPasswordAsync(user, password);

                        //查询用户是否已经添加了权限 若不在添加进用户组
                        if (!await _userManager.IsInRoleAsync(user, userRole.Name))
                        {
                            var roleOK = await _userManager.AddToRoleAsync(user, userRole.Name);
                        }
                    }
                    var avatar = new BusinessImage
                    {
                        Name              = string.Empty,
                        DisplayName       = string.Empty,
                        OriginalFileName  = string.Empty,
                        Type              = ImageType.Avatars,
                        RelevanceObjectId = Guid.Parse(user.Id),
                        UploaderId        = Guid.Parse(user.Id),
                        Description       = "这是用户【" + user.ChineseFullName + "】的头像",
                        FileSize          = 0,
                        UploadPath        = "../../images/Avatars/defaultAvatar.gif",
                        PhysicalPath      = string.Empty
                    };
                    await _businessImage.AddOrEditAndSaveAsyn(avatar);
                }
                GetCurrUserName();
                ViewBag.Message   = "——数据添加完成,您可以通过下方按钮选择一些操作——";
                ViewBag.PassError = false;
                return(View());
            }
            else
            {
                ViewBag.Message   = "——数据已经添加,您可以通过下方按钮选择一些操作——";
                ViewBag.PassError = false;
                return(View());
            }
        }
Exemplo n.º 11
0
        public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordModel model)
        {
              
            if (ModelState.IsValid)
            {
                
                // Fetch userID by email
                DBservices dbs = new DBservices();
                dbs = dbs.ReadFromDataBase(27, model.EmailAddress);
                string userId = dbs.dt.Rows[0].ItemArray[0].ToString();
                string userName = dbs.dt.Rows[0].ItemArray[1].ToString();
                string userFname = dbs.dt.Rows[0].ItemArray[2].ToString();
                
                // Generate an 8th digit long password
                var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                var stringChars = new char[8];
                var random = new Random();
                for (int i = 0; i < stringChars.Length; i++)
                {
                    stringChars[i] = chars[random.Next(chars.Length)];
                }
                var randomPassword = new String(stringChars);
                UserManager<IdentityUser> UserManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
                IdentityResult resultRem = await UserManager.RemovePasswordAsync(userId);
                IdentityResult resultAdd = await UserManager.AddPasswordAsync(userId, randomPassword);

                //Send a notification to the user

                MailMessage mail = new MailMessage();
                StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath("~/Models/mailTemplates/forgotPasswordTemplate.html"));
                string readFile = reader.ReadToEnd();
                string StrContent = readFile;
                
                StrContent = StrContent.Replace("[FirstName]", userFname);
                StrContent = StrContent.Replace("[UserName]", userName);
                StrContent = StrContent.Replace("[Password]", randomPassword);
                
                mail.IsBodyHtml = true;
                mail.To.Add(model.EmailAddress);
                mail.Subject = "רוכבים לעבודה, איפוס סיסמא";                
                mail.Body = StrContent.ToString();
                mail.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Send(mail);

            }

            return Ok();

        }
 public async Task <IdentityResult> ResetPassword(string password, string userId)
 {
     _userManager.RemovePassword(userId);
     return(await _userManager.AddPasswordAsync(userId, password));
 }
        public async System.Threading.Tasks.Task <ActionResult> Edit(ModifyStaffViewModel staffviewmodel)
        {
            //checks if model is valid
            if (ModelState.IsValid)
            {
                //checks legal working age, 16 and above
                if (!(staffviewmodel.DOB.Year < DateTime.Now.Year - 16))
                {
                    ViewBag.RoleNo       = new SelectList(db.Roles, "Id", "Name");
                    ViewBag.ErrorMessage = "Not legal age to work";
                    staffviewmodel.Roles = db.Roles.Select(r => new SelectListItem {
                        Text = r.Name, Value = r.Name
                    }).ToList();

                    return(View(staffviewmodel));
                }

                //scans all instances of staff to check for pre existing staff by these details
                foreach (Staff s in db.ApplicationUsers.ToList())
                {
                    if (s.Id == staffviewmodel.tempid)
                    {
                        continue;
                    }

                    if (s.Email == staffviewmodel.Email || (s.Forename == staffviewmodel.Forename && s.Surname == staffviewmodel.Surname) || s.PhoneNumber == staffviewmodel.Telnum)
                    {
                        ViewBag.RoleNo       = new SelectList(db.Roles, "Id", "Name");
                        ViewBag.ErrorMessage = "Staff Member Already Exists By These Details";
                        staffviewmodel.Roles = db.Roles.Select(r => new SelectListItem {
                            Text = r.Name, Value = r.Name
                        }).ToList();

                        return(View(staffviewmodel));
                    }
                }

                //finds user and previous role
                var    staff   = UserManager.FindById(staffviewmodel.tempid);
                string oldRole = (await UserManager.GetRolesAsync(staffviewmodel.tempid)).Single();

                //updates details of staff
                staff.Forename    = staffviewmodel.Forename;
                staff.Surname     = staffviewmodel.Surname;
                staff.DOB         = staffviewmodel.DOB;
                staff.Email       = staffviewmodel.Email;
                staff.City        = staffviewmodel.City;
                staff.PhoneNumber = staffviewmodel.Telnum;
                staff.UserName    = staff.Email;
                staff.Town        = staffviewmodel.Town;
                staff.Street      = staffviewmodel.Street;

                //saves changes made
                await UserManager.UpdateAsync(staff);

                //removes from oldrole defined above, replaces with new role defined in staffviewmodel
                await UserManager.RemoveFromRoleAsync(staffviewmodel.tempid, oldRole);

                await UserManager.AddToRoleAsync(staffviewmodel.tempid, staffviewmodel.Role);

                //if a password is enter into the modifyviewmodel the password is then hashed, removes previous password and add the new one to user
                if (staffviewmodel.Password != null)
                {
                    IPasswordHasher passwordHasher = new PasswordHasher();

                    string hashedpassword = passwordHasher.HashPassword(staffviewmodel.Password);

                    UserManager.RemovePassword(staffviewmodel.tempid);
                    await UserManager.AddPasswordAsync(staffviewmodel.tempid, staffviewmodel.Password);

                    db.SaveChanges();
                }

                //overall savechanges if password is empty
                db.SaveChanges();

                return(RedirectToAction("Index"));
            }

            //if model is not valid returns viewmodel confirming error
            ViewBag.RoleNo       = new SelectList(db.Roles, "Id", "Name");
            ViewBag.ErrorMessage = "Submission not valid, please fill all fields";
            staffviewmodel.Roles = db.Roles.Select(r => new SelectListItem {
                Text = r.Name, Value = r.Name
            }).ToList();

            return(View(staffviewmodel));
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Edit(string id, [FromBody] UserEditM data)
        {
            var user = await _userManager.FindByIdAsync(id);

            if (user == null)
            {
                return(NotFound(data));
            }
            if (user.Name != data.Name && _userManager.Users.Any(u => u.Name == data.Name))
            {
                ModelState.AddModelError(nameof(data.Name), nameof(Resource.NameError));
                return(BadRequest(ModelState));
            }
            if (user.Login != data.Login && (await _userManager.FindByNameAsync(data.Login)) != null)
            {
                ModelState.AddModelError(nameof(data.Login), nameof(Resource.LoginError));
                return(BadRequest(ModelState));
            }
            if (data.NewPassword.HasValue())
            {
                var removePasswordResult = await _userManager.RemovePasswordAsync(user);

                if (!removePasswordResult.Succeeded)
                {
                    ModelState.AddModelError(nameof(data.NewPassword), nameof(Resource.PasswordUpdateError));
                    removePasswordResult.Errors.ForEach(err =>
                                                        ModelState.AddModelError(nameof(data.NewPassword), $"Code {err.Code}: {err.Description}"));
                    return(BadRequest(ModelState));
                }
                var addPasswordResult = await _userManager.AddPasswordAsync(user, data.NewPassword);

                if (!addPasswordResult.Succeeded)
                {
                    ModelState.AddModelError(nameof(data.NewPassword), nameof(Resource.PasswordUpdateError));
                    addPasswordResult.Errors.ForEach(err =>
                                                     ModelState.AddModelError(nameof(data.NewPassword), $"Code {err.Code}: {err.Description}"));
                    return(BadRequest(ModelState));
                }
            }

            var oldRole = (await _userManager.GetRolesAsync(user)).Single();

            if (oldRole != data.AssignedRole)
            {
                if (!(await _userManager.AddToRoleAsync(user, data.AssignedRole)).Succeeded ||
                    !(await _userManager.RemoveFromRoleAsync(user, oldRole)).Succeeded)
                {
                    ModelState.AddModelError(nameof(data.AssignedRole), nameof(Resource.RoleUpdateError));
                    return(BadRequest(ModelState));
                }
            }

            user.Name            = data.Name;
            user.Login           = data.Login;
            user.Email           = data.Email;
            user.PhoneNumber     = data.Phone;
            user.Description     = data.Description;
            user.DataAccessArray = data.DataAccess.ToStringCollection();
            user.Status          = data.Status.Value;

            if (!(await _userManager.UpdateAsync(user)).Succeeded)
            {
                ModelState.AddModelError(string.Empty, nameof(Resource.UserUpdateError));
                return(BadRequest(ModelState));
            }

            await _userService.RelateUserRegionsAsync(user, data);

            await _userService.RelateUserActivityCategoriesAsync(user, data);

            return(NoContent());
        }
Exemplo n.º 15
0
        public static async Task Initialize(GameSenseContext context,
                                            UserManager <User> userManager,
                                            RoleManager <IdentityRole> roleManager)
        {
            context.Database.EnsureCreated();

            String adminId1 = "";

            string role1 = "Admin";

            string role2 = "User";

            string role3 = "Editor";

            string password = "******";

            if (await roleManager.FindByNameAsync(role1) == null)
            {
                await roleManager.CreateAsync(new IdentityRole(role1));
            }
            if (await roleManager.FindByNameAsync(role2) == null)
            {
                await roleManager.CreateAsync(new IdentityRole(role2));
            }
            if (await roleManager.FindByNameAsync(role3) == null)
            {
                await roleManager.CreateAsync(new IdentityRole(role3));
            }

            if (await userManager.FindByNameAsync("Admin@Admin") == null)
            {
                var user = new User
                {
                    UserName   = "******",
                    Email      = "Admin@Admin",
                    firstName  = "Admin",
                    lastName   = "Admin",
                    MyUserName = "******"
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role1);
                }
                adminId1 = user.Id;
            }

            if (await userManager.FindByNameAsync("User@default") == null)
            {
                var user = new User
                {
                    UserName   = "******",
                    Email      = "User@default",
                    firstName  = "User",
                    lastName   = "User",
                    MyUserName = "******"
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role2);
                }
            }

            if (await userManager.FindByNameAsync("Editor@default") == null)
            {
                var user = new User
                {
                    UserName   = "******",
                    Email      = "Editor@default",
                    firstName  = "Editor",
                    lastName   = "Editor",
                    MyUserName = "******"
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role3);
                }
            }
        }
        public async Task <IActionResult> CreateDefaultUsers()
        {
            #region Roles

            var rolesDetails = new List <string>
            {
                Constants.Roles.Customer,
                Constants.Roles.Restaurant,
                Constants.Roles.Admin
            };

            foreach (string roleName in rolesDetails)
            {
                if (!await _roleManager.RoleExistsAsync(roleName))
                {
                    await _roleManager.CreateAsync(new IdentityRole(roleName));
                }
            }

            #endregion

            #region Users

            var userDetails = new Dictionary <string, IdentityUser> {
                {
                    Constants.Roles.Customer,
                    new IdentityUser {
                        Email = "*****@*****.**", UserName = "******", EmailConfirmed = true
                    }
                },
                {
                    Constants.Roles.Restaurant,
                    new IdentityUser {
                        Email = "*****@*****.**", UserName = "******", EmailConfirmed = true
                    }
                },
                {
                    Constants.Roles.Admin,
                    new IdentityUser {
                        Email = "*****@*****.**", UserName = "******", EmailConfirmed = true
                    }
                }
            };

            foreach (var details in userDetails)
            {
                var existingUserDetails = await _userManager.FindByEmailAsync(details.Value.Email);

                if (existingUserDetails == null)
                {
                    await _userManager.CreateAsync(details.Value);

                    await _userManager.AddPasswordAsync(details.Value, "Password");

                    await _userManager.AddToRoleAsync(details.Value, details.Key);
                }
            }

            #endregion

            return(Ok("Default User has been created"));
        }
Exemplo n.º 17
0
        public static async Task Initialize(ApplicationDbContext context, UserManager <ApplicationUser> userManager, RoleManager <IdentityRole> roleManager)
        {
            context.Database.EnsureCreated();

            string adminId1 = "";

            string role1 = "Admin";
            string role2 = "Manager";
            string role3 = "Resident";
            string role4 = "MaintenanceTech";

            string password = "******";

            if (await roleManager.FindByNameAsync(role1) == null)
            {
                await roleManager.CreateAsync(new IdentityRole(role1));
            }
            if (await roleManager.FindByNameAsync(role2) == null)
            {
                await roleManager.CreateAsync(new IdentityRole(role2));
            }
            if (await roleManager.FindByNameAsync(role3) == null)
            {
                await roleManager.CreateAsync(new IdentityRole(role3));
            }
            if (await roleManager.FindByNameAsync(role4) == null)
            {
                await roleManager.CreateAsync(new IdentityRole(role4));
            }
            if (await userManager.FindByNameAsync("*****@*****.**") == null)
            {
                var user = new ApplicationUser
                {
                    UserName     = "******",
                    Email        = "*****@*****.**",
                    FirstName    = "Adam",
                    LastName     = "Min",
                    isSuperAdmin = true
                };
                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role1);
                }
                adminId1 = user.Id;
            }
            if (await userManager.FindByNameAsync("*****@*****.**") == null)
            {
                var user = new ApplicationUser
                {
                    UserName     = "******",
                    Email        = "*****@*****.**",
                    FirstName    = "Rick",
                    LastName     = "Sanchez",
                    isSuperAdmin = false
                };
                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role2);
                }
            }
        }
Exemplo n.º 18
0
 public async Task <IdentityResult> AddPasswordAsync(dynamic user, string newPassword)
 {
     return(await UserManager.AddPasswordAsync(user, newPassword));
 }
 public async Task<JsonData> Reset(UserViewModel model)
 {
     try
     {
         var db = new DataContext();
         var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));
         userMan.UserValidator = new UserValidator<MyUser>(userMan)
         {
             AllowOnlyAlphanumericUserNames =
                 false
         };
         var user = await userMan.FindByEmailAsync(model.Email);
         if (user == null) throw new Exception("please check the email address");
         //todo: generate a unique password and email it to the user
         var newPassword = user.FullName.Substring(2, 3) + user.PasswordHash.Substring(0, 5);
         var result = await userMan.RemovePasswordAsync(user.Id);
         if (!result.Succeeded) throw new Exception(string.Join(", ", result.Errors));
         var result2 = await userMan.AddPasswordAsync(user.Id, newPassword);
         if (!result2.Succeeded) throw new Exception(string.Join(", ", result2.Errors));
         //todo: Email the new password to the user
         return DataHelpers.ReturnJsonData(null, true, "A new password has been emailed to your email address");
     }
     catch (Exception e)
     {
         return DataHelpers.ExceptionProcessor(e);
     }
 }
Exemplo n.º 20
0
        public async Task <ActionResult <MmtUser> > PutMmtUser(string MmtUserId, [FromForm] MmtUserPutDTO model)
        {
            var mmtUser = await _UserManager.FindByIdAsync(MmtUserId);

            if (mmtUser == null)
            {
                return(NotFound());
            }
            ;

            mmtUser.UserName       = model.UserName;
            mmtUser.FirstName      = model.FirstName;
            mmtUser.LastName       = model.LastName;
            mmtUser.Email          = model.Email;
            mmtUser.PostalCode     = model.PostalCode;
            mmtUser.City           = model.City;
            mmtUser.Country        = model.Country;
            mmtUser.PhoneNumber    = model.Mobile;
            mmtUser.PhoneHome      = model.PhoneHome;
            mmtUser.PhoneWork      = model.PhoneWork;
            mmtUser.Function       = model.Function;
            mmtUser.EmailConfirmed = model.EmailConfirmed;
            // check if password is not empty
            if (!string.IsNullOrWhiteSpace(model.Password))
            {
                if (model.Password != model.ConfirmPassword)
                {
                    return(BadRequest(ModelState));
                }

                // if password is not empty and password and his confirmation matchs we validate the password according to the password policy
                foreach (var v in _UserManager.PasswordValidators)
                {
                    var result = await v.ValidateAsync(_UserManager, null, model.Password);

                    if (!result.Succeeded)
                    {
                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError("", error.Description);
                        }
                        return(BadRequest(ModelState));
                    }
                }

                //removing the old password
                await _UserManager.RemovePasswordAsync(mmtUser);

                //adding the new validated password
                await _UserManager.AddPasswordAsync(mmtUser, model.Password);
            }
            ;


            // if there is any roles in the model then we validate them and check if they exist in the db
            if (model.Roles != null)
            {
                foreach (var role in model.Roles)
                {
                    if (!(await _RoleManager.RoleExistsAsync(role)))
                    {
                        ModelState.AddModelError("", $"{role} does not exists");
                        return(BadRequest(ModelState));
                    }
                }

                // we delete the old roles for the user
                var oldUserRoles = await _UserManager.GetRolesAsync(mmtUser);

                var result = await _UserManager.RemoveFromRolesAsync(mmtUser, oldUserRoles);

                if (!result.Succeeded)
                {
                    return(BadRequest(ModelState));
                }

                // we add the new roles to the user
                var addToRolesResult = await _UserManager.AddToRolesAsync(mmtUser, model.Roles);

                if (!addToRolesResult.Succeeded)
                {
                    return(BadRequest(ModelState));
                }
            }

            var updateMmtUserResult = await _UserManager.UpdateAsync(mmtUser);

            if (!updateMmtUserResult.Succeeded)
            {
                return(BadRequest(ModelState));
            }

            return(Ok(mmtUser));
        }
Exemplo n.º 21
0
        public static async Task Initialize(
            ApplicationDbContext context,
            UserManager <ApplicationUser> userManager,
            RoleManager <ApplicationRole> roleManager)
        {
            context.Database.EnsureCreated();

            string adminId1 = "";
            string adminId2 = "";

            string role1 = "Admin";
            string desc1 = "This is the administrator role";

            string role2 = "Member";
            string desc2 = "This is the members role";

            string password = "******";

            if (await roleManager.FindByNameAsync(role1) == null)
            {
                await roleManager.CreateAsync(new ApplicationRole(role1, desc1, DateTime.Now));
            }
            if (await roleManager.FindByNameAsync(role2) == null)
            {
                await roleManager.CreateAsync(new ApplicationRole(role2, desc2, DateTime.Now));
            }

            if (await userManager.FindByNameAsync("a") == null)
            {
                var user = new ApplicationUser {
                    UserName    = "******",
                    Email       = "[email protected]",
                    MemberSince = DateTime.Now
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role1);
                }
                adminId1 = user.Id;
            }

            if (await userManager.FindByNameAsync("b") == null)
            {
                var user = new ApplicationUser {
                    UserName    = "******",
                    Email       = "[email protected]",
                    MemberSince = DateTime.Now
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role1);
                }
                adminId2 = user.Id;
            }

            if (await userManager.FindByNameAsync("m") == null)
            {
                var user = new ApplicationUser {
                    UserName    = "******",
                    Email       = "[email protected]",
                    MemberSince = DateTime.Now
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role2);
                }
            }

            if (await userManager.FindByNameAsync("d") == null)
            {
                var user = new ApplicationUser {
                    UserName    = "******",
                    Email       = "[email protected]",
                    MemberSince = DateTime.Now
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role2);
                }
            }
        }
Exemplo n.º 22
0
        public async Task <ActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            var          userService = new UserService();
            User_Profile user        = userService.getUser(model.uid);

            model.name = user.Name;
            model.notValidateCurrent = false;
            if (HttpContext.Session["ResetPassword_NotValidateCurrent"] != null && HttpContext.Session["ResetPassword_NotValidateCurrent"] as bool? == true)
            {
                model.notValidateCurrent = true;
            }

            if (HttpContext.Session["ResetPassword"] != null && HttpContext.Session["ResetPassword"] as int? == model.uid)
            {
                if (!model.notValidateCurrent)
                {
                    if (string.IsNullOrEmpty(model.OldPassword))
                    {
                        ModelState.AddModelError("OldPassword", "The Current Password field is required.");
                    }
                }

                if (model.notValidateCurrent || (!string.IsNullOrEmpty(model.OldPassword) && (user.PWD.Equals(UserService.hashSHA256(model.OldPassword)))))
                {
                    if (ModelState.IsValid)
                    {
                        var result = userService.ResetPassword(model.uid, model.NewPassword);
                        if (result.Code != ReturnCode.SUCCESS)
                        {
                            return(RedirectToAction("ErrorPage", "Account", new ErrorViewModel()
                            {
                                Message = Error.GetMessage(ReturnCode.ERROR_UPDATE)
                            }));
                        }
                        else
                        {
                            UserManager <ApplicationUser> userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new AgnosDBContext()));
                            userManager.UserValidator = new UserValidator <ApplicationUser>(userManager)
                            {
                                AllowOnlyAlphanumericUserNames = false
                            };

                            IdentityResult iresult = await userManager.RemovePasswordAsync(user.ApplicationUser_Id);

                            if (iresult.Succeeded)
                            {
                                iresult = await userManager.AddPasswordAsync(user.ApplicationUser_Id, model.NewPassword);

                                if (iresult.Succeeded)
                                {
                                    HttpContext.Session.Remove("ResetPassword_NotValidateCurrent");
                                    HttpContext.Session.Remove("ResetPassword");
                                    HttpContext.Session.Remove("Activate");

                                    if (model.notValidateCurrent)
                                    {
                                        //SET LIMIT TIME
                                        if (HttpContext.Session["ResetPassword_ID"] != null)
                                        {
                                            userService.SetExpireActivationLinkTimeLimit((HttpContext.Session["ResetPassword_ID"] as int?).Value);
                                        }
                                    }
                                    return(View("ResetPasswordComplete"));
                                }
                                else
                                {
                                    //TODO
                                    AddErrors(iresult);
                                }
                            }
                            else
                            {
                                //TODO
                                AddErrors(iresult);
                            }
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("OldPassword", Resource.Is_Inccorect);
                }
            }
            else
            {
                return(RedirectToAction("ErrorPage", "Account", new ErrorViewModel()
                {
                    Message = Error.GetMessage(ReturnCode.ERROR_UNAUTHORIZED)
                }));
            }

            var v = GetErrorModelState();

            return(View(model));
        }
Exemplo n.º 23
0
        public static async Task Initialize(ApplicationDbContext context,
                                            UserManager <ApplicationUser> userManager,
                                            RoleManager <ApplicationRole> roleManager)
        {
            context.Database.EnsureCreated();

            var employerRole = "Employer";
            var personRole   = "Person";

            var password = "******";

            if (await roleManager.FindByNameAsync(employerRole) == null)
            {
                await roleManager.CreateAsync(new ApplicationRole(employerRole));
            }

            if (await roleManager.FindByNameAsync(personRole) == null)
            {
                await roleManager.CreateAsync(new ApplicationRole(personRole));
            }

            if (await userManager.FindByNameAsync("SiebeCorstjens") == null)
            {
                var user = new ApplicationUser
                {
                    Id          = "1",
                    UserName    = "******",
                    FirstName   = "Siebe",
                    LastName    = "Corstjens",
                    Email       = "*****@*****.**",
                    PhoneNumber = "0490634251",
                    QrCode      = Guid.NewGuid(),
                    Pincode     = HashEncoder.GetHashString("1000"),
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, employerRole);
                }
            }

            if (await userManager.FindByNameAsync("LiesbethVandevenne") == null)
            {
                var user = new ApplicationUser
                {
                    Id          = "2",
                    UserName    = "******",
                    FirstName   = "Liesbeth",
                    LastName    = "Vandevenne",
                    Email       = "*****@*****.**",
                    PhoneNumber = "0478812257",
                    QrCode      = Guid.NewGuid(),
                    Pincode     = HashEncoder.GetHashString("1000"),
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, employerRole);
                }
            }

            if (await userManager.FindByNameAsync("LornaDeVroom") == null)
            {
                var user = new ApplicationUser
                {
                    Id          = "3",
                    UserName    = "******",
                    FirstName   = "Lorna",
                    LastName    = "De Vroom",
                    Email       = "*****@*****.**",
                    PhoneNumber = "0474267406",
                    QrCode      = Guid.NewGuid(),
                    Pincode     = HashEncoder.GetHashString("9999"),
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, personRole);
                }
            }

            if (await userManager.FindByNameAsync("MyriamDekens") == null)
            {
                var user = new ApplicationUser
                {
                    Id          = "4",
                    UserName    = "******",
                    FirstName   = "Myriam",
                    LastName    = "Dekens",
                    Email       = "*****@*****.**",
                    PhoneNumber = "0473576611",
                    QrCode      = Guid.NewGuid(),
                    Pincode     = HashEncoder.GetHashString("9999"),
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, personRole);
                }
            }
        }
Exemplo n.º 24
0
        public virtual async Task <ApplicationIdentityResult> AddPasswordAsync(int userId, string password)
        {
            var identityResult = await _userManager.AddPasswordAsync(userId, password).ConfigureAwait(false);

            return(identityResult.ToApplicationIdentityResult());
        }
Exemplo n.º 25
0
        public static async Task Initialize(
            ApplicationDbContext context,
            UserManager <Models.DataModels.UserModels.User> userManager,
            RoleManager <Models.DataModels.UserModels.UserRole> roleManager,
            bool migarte)
        {
            if (migarte)
            {
                await context.Database.MigrateAsync();
            }

            if (!await roleManager.RoleExistsAsync("Admin"))
            {
                await roleManager.CreateAsync(new Models.DataModels.UserModels.UserRole("Admin", "مدیر سیستم"));
            }

            if (!await roleManager.RoleExistsAsync("Charity"))
            {
                await roleManager.CreateAsync(new Models.DataModels.UserModels.UserRole("Charity", "حسابدار"));
            }

            if (!await roleManager.RoleExistsAsync("User"))
            {
                await roleManager.CreateAsync(new Models.DataModels.UserModels.UserRole("User", "کاربر"));
            }

            await context.SaveChangesAsync();

            Models.DataModels.UserModels.User admin = await userManager.FindByNameAsync("admin");

            Models.DataModels.UserModels.User charity = await userManager.FindByNameAsync("charity");

            if (admin == null)
            {
                IdentityResult result = await userManager.CreateAsync(new Models.DataModels.UserModels.User(0, "*****@*****.**", false, "admin", null, false, null, "مدیر", "سیستم", null, null, null, null, null, null, null, null, DateTime.Now, null, null, null, Guid.NewGuid().ToString(), false, null, null, null, null, null));

                if (!result.Succeeded)
                {
                    throw new Exception(string.Join("\n", result.Errors.Select(t => t.Description)));
                }

                admin = await userManager.FindByNameAsync("admin");

                await userManager.AddPasswordAsync(admin, "1234");

                await userManager.AddToRoleAsync(admin, "Admin");
            }

            if (charity == null)
            {
                IdentityResult result = await userManager.CreateAsync(new Models.DataModels.UserModels.User(0, "*****@*****.**", false, "charity", null, false, null, "حسابدار", "سیستم", null, null, null, null, null, null, null, null, DateTime.Now, null, null, null, Guid.NewGuid().ToString(), false, null, null, null, null, null));

                if (!result.Succeeded)
                {
                    throw new Exception(string.Join("\n", result.Errors.Select(t => t.Description)));
                }

                charity = await userManager.FindByNameAsync("charity");

                await userManager.AddPasswordAsync(charity, "1234");

                await userManager.AddToRoleAsync(charity, "Charity");
            }

            if (context.Charities.Count() == 0)
            {
                Models.DataModels.Charity charity1 = new Models.DataModels.Charity(0, "محک", "تهران");
                Models.DataModels.Charity charity2 = new Models.DataModels.Charity(0, "ثاراله", "شیراز");
                Models.DataModels.Charity charity3 = new Models.DataModels.Charity(0, "کمیته امداد", "مشهد");
                Models.DataModels.Charity charity4 = new Models.DataModels.Charity(0, "حلال احمر", "تهران");
                context.Charities.Add(charity1);
                await context.SaveChangesAsync();

                Models.DataModels.CharityTag tag1 = new Models.DataModels.CharityTag(0, charity1.Id, "سرطان");
                context.CharityTags.Add(tag1);
                Models.DataModels.CharityTag tag2 = new Models.DataModels.CharityTag(0, charity1.Id, "کودک");
                context.CharityTags.Add(tag2);
                await context.SaveChangesAsync();

                context.Charities.Add(charity2);
                await context.SaveChangesAsync();

                Models.DataModels.CharityTag tag3 = new Models.DataModels.CharityTag(0, charity2.Id, "سرطان");
                context.CharityTags.Add(tag3);
                Models.DataModels.CharityTag tag4 = new Models.DataModels.CharityTag(0, charity2.Id, "کودک");
                context.CharityTags.Add(tag4);
                Models.DataModels.CharityTag tag5 = new Models.DataModels.CharityTag(0, charity2.Id, "نوزاد");
                context.CharityTags.Add(tag5);
                await context.SaveChangesAsync();

                context.Charities.Add(charity3);
                await context.SaveChangesAsync();

                Models.DataModels.CharityTag tag6 = new Models.DataModels.CharityTag(0, charity3.Id, "بازنشسته");
                context.CharityTags.Add(tag6);
                await context.SaveChangesAsync();

                context.Charities.Add(charity4);
                await context.SaveChangesAsync();

                Models.DataModels.CharityTag tag7 = new Models.DataModels.CharityTag(0, charity4.Id, "سیل");
                context.CharityTags.Add(tag7);
                Models.DataModels.CharityTag tag8 = new Models.DataModels.CharityTag(0, charity4.Id, "زلزله");
                context.CharityTags.Add(tag8);
                await context.SaveChangesAsync();
            }
        }
Exemplo n.º 26
0
        public static async Task Initialize(ApplicationDbContext context,
                                            UserManager <ApplicationUser> userManager, RoleManager <ApplicationRole> roleManager)
        {
            context.Database.EnsureCreated();
            String adminId1 = "";
            String adminId2 = "";
            string role1    = "Admin";
            string desc1    = "Este es el rol de Administrador";
            string role2    = "Rol de usuario";
            string desc2    = "Este es el rol de usuario";
            string password = "******";

            if (await roleManager.FindByNameAsync(role1) == null)
            {
                await roleManager.CreateAsync(new ApplicationRole(role1, desc1,
                                                                  DateTime.Now));
            }
            if (await roleManager.FindByNameAsync(role2) == null)
            {
                await roleManager.CreateAsync(new ApplicationRole(role2, desc2,
                                                                  DateTime.Now));
            }
            if (await userManager.FindByNameAsync("*****@*****.**") == null)
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Familia",
                    MiddleName  = "Locos",
                    LastName    = "Adams",
                    Street      = "Las Palmas 100",
                    City        = "Valle",
                    Province    = "Guanajuato",
                    PostalCode  = "38400",
                    PhoneNumber = "4561141329"
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role1);
                }
                adminId1 = user.Id;
            }
            if (await userManager.FindByNameAsync("*****@*****.**") == null)
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Los",
                    MiddleName  = "Simpson",
                    LastName    = "Fox",
                    Street      = "SiempreViva 64",
                    City        = "Spriendfield",
                    Province    = "Guanajuato",
                    PostalCode  = "38643",
                    PhoneNumber = "1234567890"
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role1);
                }
                adminId2 = user.Id;
            }
            if (await userManager.FindByNameAsync("*****@*****.**") == null)
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Mike",
                    MiddleName  = "Super",
                    LastName    = "Myers",
                    Street      = "Yew St",
                    City        = "Vancouver",
                    Province    = "BC",
                    PostalCode  = "96385",
                    PhoneNumber = "6572136821"
                };


                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role2);
                }
            }
            if (await userManager.FindByNameAsync("*****@*****.**") == null)
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Donald",
                    MiddleName  = "Pato",
                    LastName    = "Duck",
                    Street      = "Well St",
                    City        = "Vancouver",
                    Province    = "BC",
                    PostalCode  = "52820",
                    PhoneNumber = "6041234567"
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role2);
                }
            }
        }
Exemplo n.º 27
0
        public async Task <IActionResult> UpdatePassword([FromBody] UserRedefinicaoSenhaDTO request)
        {
            try
            {
                var user = await _userManager.FindByNameAsync(request.UserName);

                if (user != null)
                {
                    var validarNovaSenha = _passwordValidator.ValidateAsync(_userManager, user, request.NovaSenha);

                    if (!validarNovaSenha.Result.Succeeded)
                    {
                        return(BadRequest(new ApiResponseError(HttpStatusCode.BadRequest, "Erro na Modificação da Senha")
                        {
                            Errors = validarNovaSenha.Result.Errors.Select(p => p.Description).ToList()
                        }));
                    }

                    var autenticado = await _signInManager.PasswordSignInAsync(user, request.SenhaAtual, isPersistent : false, lockoutOnFailure : false);

                    if (!autenticado.Succeeded)
                    {
                        return(BadRequest(new ApiResponseError(HttpStatusCode.BadRequest, "Usuário ou Senha Inválidos")
                        {
                            Errors = new List <string>()
                            {
                                "Usuário ou Senha Inválidos"
                            }
                        }));
                    }

                    var verificarUltimasSenhas = _usuarioSenhaHistoryService.UltimasSenhas(user.Id, _appSettings.Auth.QtdSenhasVerificar);
                    foreach (var item in verificarUltimasSenhas)
                    {
                        var igualUltimasTres = _passwordHasher.VerifyHashedPassword(null, item.PasswordHash, request.NovaSenha);
                        if (igualUltimasTres == PasswordVerificationResult.Success)
                        {
                            return(BadRequest(new ApiResponseError(HttpStatusCode.BadRequest, "Senha não pode ser igual as últimas 3 Senhas válidas")
                            {
                                Errors = new List <string>()
                                {
                                    "Senha não pode ser igual as últimas 3 Senhas válidas"
                                }
                            }));
                        }
                    }

                    var hashPass = _passwordHasher.HashPassword(user, request.NovaSenha);
                    await _userManager.RemovePasswordAsync(user);

                    var result = await _userManager.AddPasswordAsync(user, hashPass);

                    if (result.Succeeded)
                    {
                        user.DataUltimaTrocaSenha = DateTime.Now;
                        user.FirstLogin           = false;
                        user.ForcaTrocaSenha      = false;
                        user.Logado          = true;
                        user.DataUltimoLogin = DateTime.Now;
                        user.PasswordHash    = hashPass;

                        await _userManager.UpdateAsync(user);

                        var usuarioSenhaHistory = new UsuarioSenhaHistory()
                        {
                            UsuarioId    = user.Id,
                            DataCriacao  = DateTime.Now,
                            PasswordHash = user.PasswordHash
                        };

                        _usuarioSenhaHistoryService.Add(usuarioSenhaHistory);

                        var roles = await _userManager.GetRolesAsync(user);

                        var buildToken = TokenHelper.BuildToken(user, roles.ToList(), _appSettings.Auth.JWTSecret, _appSettings.Auth.Expiration);

                        var userAutentication = new UserAutenticationDTO()
                        {
                            UserName        = user.UserName,
                            DataLogin       = user.DataUltimoLogin,
                            Token           = buildToken,
                            Autenticated    = true,
                            ForcaTrocaSenha = false
                        };

                        return(Ok(new ApiResponseSuccess <UserAutenticationDTO>(userAutentication, "Senha Redefina com Sucesso!")));
                    }
                    else
                    {
                        return(BadRequest(new ApiResponseError(HttpStatusCode.BadRequest, "Erro na Modificação da Senha")
                        {
                            Errors = result.Errors.Select(p => p.Description).ToList()
                        }));
                    }
                }
                else
                {
                    return(BadRequest(new ApiResponseError(HttpStatusCode.BadRequest, "Usuário ou Senha Inválidos")
                    {
                        Errors = new List <string>()
                        {
                            "Usuário ou Senha Inválidos"
                        }
                    }));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Erro ao Modificar a Senha {message}", ex.Message);
                return(NotFound(new ApiResponseError(HttpStatusCode.NotFound, "Erro na Troca de Senha")
                {
                    Errors = new List <string>()
                    {
                        $"Erro ao tentar Trocar a Senha"
                    }
                }));
            }
        }
Exemplo n.º 28
0
        public async Task <IActionResult> Put(string id, [FromBody] EditDto model)
        {
            User user = await _userManager.FindByIdAsync(id);

            if (user == null)
            {
                return(NoContent());
            }

            Warehouse warehouse = _context.Warehouses.Find(model.Warehouse);

            if (warehouse == null)
            {
                return(BadRequest("No Warehouse"));
            }
            Department department = _context.Departments.Find(model.Department);

            if (department == null)
            {
                return(BadRequest("No Departamento"));
            }

            IdentityRole Role = await _roleManager.FindByIdAsync(model.Role);

            if (Role == null)
            {
                return(BadRequest("NO ROL"));
            }

            user.UserName   = model.Email;
            user.Email      = model.Email;
            user.Name       = model.Name;
            user.LastName   = model.LastName;
            user.SAPID      = model.SAPID;
            user.Active     = model.Active;
            user.Warehouse  = warehouse;
            user.Department = department;

            var result = await _userManager.UpdateAsync(user);

            if (model.Password != null)
            {
                await _userManager.RemovePasswordAsync(user);

                await _userManager.AddPasswordAsync(user, model.Password);
            }

            if (result.Succeeded)
            {
                IList <string> userRoleNames = await _userManager.GetRolesAsync(user);

                string ActualRole = userRoleNames.FirstOrDefault();
                if (Role.Name != ActualRole)
                {
                    if (ActualRole != null)
                    {
                        await _userManager.RemoveFromRoleAsync(user, ActualRole);
                    }
                    await _userManager.AddToRoleAsync(user, Role.Name);
                }

                var UserClaims = await _userManager.GetClaimsAsync(user);

                var Permissions = UserClaims.Where(x => x.Type == CustomClaimTypes.Permission);

                foreach (var permission in Permissions)
                {
                    if (!model.PermissionsExtra.Exists(x => x == permission.Value))
                    {
                        await _userManager.RemoveClaimAsync(user, permission);
                    }
                }

                var PermissionList = Permissions.ToList();
                foreach (var permission in model.PermissionsExtra)
                {
                    if (!PermissionList.Exists(x => x.Value == permission))
                    {
                        await _userManager.AddClaimAsync(user, new Claim(CustomClaimTypes.Permission, permission));
                    }
                }

                return(Ok());
            }

            StringBuilder stringBuilder = new StringBuilder();

            foreach (IdentityError m in result.Errors.ToList())
            {
                stringBuilder.AppendFormat("Codigo: {0} Descripcion: {1}\n", m.Code, m.Description);
            }
            return(BadRequest(stringBuilder.ToString()));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Creates a new user
        /// </summary>
        /// <param name="userSave"></param>
        /// <returns></returns>
        public async Task <UserDisplay> PostCreateUser(UserInvite userSave)
        {
            if (userSave == null)
            {
                throw new ArgumentNullException("userSave");
            }

            if (ModelState.IsValid == false)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            if (Current.Configs.Settings().Security.UsernameIsEmail)
            {
                //ensure they are the same if we're using it
                userSave.Username = userSave.Email;
            }
            else
            {
                //first validate the username if were showing it
                CheckUniqueUsername(userSave.Username, null);
            }
            CheckUniqueEmail(userSave.Email, null);

            //Perform authorization here to see if the current user can actually save this user with the info being requested
            var authHelper  = new UserEditorAuthorizationHelper(Services.ContentService, Services.MediaService, Services.UserService, Services.EntityService, AppCaches);
            var canSaveUser = authHelper.IsAuthorized(Security.CurrentUser, null, null, null, userSave.UserGroups);

            if (canSaveUser == false)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized, canSaveUser.Result));
            }

            //we want to create the user with the UserManager, this ensures the 'empty' (special) password
            //format is applied without us having to duplicate that logic
            var identityUser = BackOfficeIdentityUser.CreateNew(userSave.Username, userSave.Email, GlobalSettings.DefaultUILanguage);

            identityUser.Name = userSave.Name;

            var created = await UserManager.CreateAsync(identityUser);

            if (created.Succeeded == false)
            {
                throw new HttpResponseException(
                          Request.CreateNotificationValidationErrorResponse(string.Join(", ", created.Errors)));
            }

            //we need to generate a password, however we can only do that if the user manager has a password validator that
            //we can read values from
            var passwordValidator = UserManager.PasswordValidator as PasswordValidator;
            var resetPassword     = string.Empty;

            if (passwordValidator != null)
            {
                var password = UserManager.GeneratePassword();

                var result = await UserManager.AddPasswordAsync(identityUser.Id, password);

                if (result.Succeeded == false)
                {
                    throw new HttpResponseException(
                              Request.CreateNotificationValidationErrorResponse(string.Join(", ", created.Errors)));
                }
                resetPassword = password;
            }

            //now re-look the user back up which will now exist
            var user = Services.UserService.GetByEmail(userSave.Email);

            //map the save info over onto the user
            user = Mapper.Map(userSave, user);

            //since the back office user is creating this user, they will be set to approved
            user.IsApproved = true;

            Services.UserService.Save(user);

            var display = Mapper.Map <UserDisplay>(user);

            display.ResetPasswordValue = resetPassword;
            return(display);
        }
Exemplo n.º 30
0
        public async Task <IActionResult> ResetPasswordAsync(
            string code,
            string email    = "*****@*****.**",
            string password = "******",
            CancellationToken cancellationToken = default
            )
        {
            User user = await UserManager.FindByEmailAsync(email);

            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "کاربر نا معتبر");
                return(View());
            }

            IdentityResult result = await UserManager.ResetPasswordAsync(user, code, password);

            if (result.Succeeded)
            {
                return(RedirectToAction(nameof(ResetPassword)));
            }

            foreach (IdentityError error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            user.PasswordHash = UserManager.PasswordHasher.HashPassword(user, password);
            var resultt = await UserManager.UpdateAsync(user);

            if (!resultt.Succeeded)
            {
            }
            var token = await UserManager.GeneratePasswordResetTokenAsync(user);

            var resulttt = await UserManager.ResetPasswordAsync(user, token, password);

            var resultttt = await UserManager.ChangePasswordAsync(user, password, password);

            await UserManager.RemovePasswordAsync(user);

            await UserManager.AddPasswordAsync(user, password);

            if (!await UserManager.CheckPasswordAsync(user, password))
            {
                ViewBag.Notification = "Incorrect password ..";
                return(View());
            }
            else
            {
                if (password != password)
                {
                    ViewBag.notification = "try again";
                    return(View());
                }
                else
                {
                    string hashedNewPassword = UserManager.PasswordHasher.HashPassword(user, password);
                    await PasswordStore.SetPasswordHashAsync(user, hashedNewPassword, cancellationToken);

                    await UserManager.UpdateAsync(user);

                    ViewBag.notification = "successful";
                    return(View());
                }
            }

            return(View());
        }
Exemplo n.º 31
0
        public static async Task InitializeAsync(ApplicationDbContext context, UserManager <ApplicationUser> userManager)
        {
            context.Database.EnsureCreated();

            if (!context.Dice.Any())
            {
                List <Die> dice = new List <Die>()
                {
                    new Die {
                        Type = "d4", NumSides = 4
                    },
                    new Die {
                        Type = "d6", NumSides = 6
                    },
                    new Die {
                        Type = "d8", NumSides = 8
                    },
                    new Die {
                        Type = "d10", NumSides = 10
                    },
                    new Die {
                        Type = "d12", NumSides = 12
                    },
                    new Die {
                        Type = "d20", NumSides = 20
                    },
                };

                context.Dice.AddRange(dice);
                context.SaveChanges();
            }


            if (!context.CharacterRaces.Any())
            {
                List <CharacterRace> races = new List <CharacterRace>()
                {
                    new CharacterRace {
                        Name = "Dragonborn", Discription = "Dragonborn look very much like dragons standing erect in humanoid form, though they lack wings or a tail."
                    },
                    new CharacterRace {
                        Name = "Dwarf", Discription = "Bold and hardy, dwarves are known as skilled warriors, miners, and workers of stone and metal."
                    },
                    new CharacterRace {
                        Name = "Elf", Discription = "Elves are a magical people of otherworldly grace, living in the world but not entirely part of it."
                    },
                    new CharacterRace {
                        Name = "Gnome", Discription = "A gnome’s energy and enthusiasm for living shines through every inch of his or her tiny body."
                    },
                    new CharacterRace {
                        Name = "Half-Elf", Discription = "Half-elves combine what some say are the best qualities of their elf and human parents."
                    },
                    new CharacterRace {
                        Name = "Halfling", Discription = "The diminutive halflings survive in a world full of larger creatures by avoiding notice or, barring that, avoiding offense."
                    },
                    new CharacterRace {
                        Name = "Human", Discription = "Humans are the most adaptable and ambitious people among the common races. Whatever drives them, humans are the innovators, the achievers, and the pioneers of the worlds."
                    },
                    new CharacterRace {
                        Name = "Tiefling", Discription = "To be greeted with stares and whispers, to suffer violence and insult on the street, to see mistrust and fear in every eye: this is the lot of the tiefling"
                    },
                };

                context.CharacterRaces.AddRange(races);
                context.SaveChanges();
            }


            if (!context.CharacterClasses.Any())
            {
                List <CharacterClass> classes = new List <CharacterClass>()
                {
                    new CharacterClass {
                        Name = "Barbarian", HitDie = "d12", Discription = "A fierce warrior of primitive background who can enter a battle rage"
                    },
                    new CharacterClass {
                        Name = "Bard", HitDie = "d8", Discription = "An inspiring magician whose power echoes the music of creation"
                    },
                    new CharacterClass {
                        Name = "Cleric", HitDie = "d8", Discription = "A priestly champion who wields divine magic in service of a higher power"
                    },
                    new CharacterClass {
                        Name = "Druid", HitDie = "d8", Discription = "A priest of the Old Faith, wielding the powers of nature and adopting animal forms"
                    },
                    new CharacterClass {
                        Name = "Fighter", HitDie = "d10", Discription = "A master of martial combat, skilled with a variety of weapons and armor"
                    },
                    new CharacterClass {
                        Name = "Monk", HitDie = "d8", Discription = "A master of martial arts, harnessing the power of the body in pursuit of physical and spiritual perfection"
                    },
                    new CharacterClass {
                        Name = "Paladin", HitDie = "d10", Discription = "A holy warrior bound to a sacred oath"
                    },
                    new CharacterClass {
                        Name = "Ranger", HitDie = "d10", Discription = "A warrior who combats threats on the edges of civilization"
                    },
                    new CharacterClass {
                        Name = "Rogue", HitDie = "d8", Discription = "A scoundrel who uses stealth and trickery to overcome obstacles and enemies"
                    },
                    new CharacterClass {
                        Name = "Sorcerer", HitDie = "d6", Discription = "A spellcaster who draws on inherent magic from a gift or bloodline"
                    },
                    new CharacterClass {
                        Name = "Warlock", HitDie = "d8", Discription = "A wielder of magic that is derived from a bargain with an extraplanar entity"
                    },
                    new CharacterClass {
                        Name = "Wizard", HitDie = "d6", Discription = "A scholarly magic-user capable of manipulating the structures of reality"
                    },
                };

                context.CharacterClasses.AddRange(classes);
                context.SaveChanges();
            }


            if (!context.Alignments.Any())
            {
                List <Alignment> alignments = new List <Alignment>()
                {
                    new Alignment {
                        AlignmentCode = "LG", Name = "Lawful Good", Description = "creatures can be counted on to do the right thing as expected by society. Gold dragons, paladins, and most dwarves are lawful good."
                    },
                    new Alignment {
                        AlignmentCode = "LN", Name = "Lawful Neutral", Description = "individuals act in accordance with law, tradition, or personal codes. Many monks and some wizards are lawful neutral."
                    },
                    new Alignment {
                        AlignmentCode = "LE", Name = "Lawful Evil", Description = "creatures methodically take what they want, within the limits of a code of tradition, loyalty, or order. Devils, blue dragons, and hobgoblins are Lawful evil."
                    },
                    new Alignment {
                        AlignmentCode = "NG", Name = "Neutral Good", Description = "folk do the best they can to help others according to their needs. Many celestials, some cloud giants, and most gnomes are neutral good."
                    },
                    new Alignment {
                        AlignmentCode = "N", Name = "Neutral", Description = "is the alignment of those who prefer to steer clear of moral questions and don't take sides, doing what seems best at the time. Lizardfolk, most druids, and many humans are neutral."
                    },
                    new Alignment {
                        AlignmentCode = "NE", Name = "Neutral Evil", Description = "is the alignment of those who do whatever they can get away with, without compassion or qualms. Many drow, some cloud giants, and yugoloths are neutraI evil."
                    },
                    new Alignment {
                        AlignmentCode = "CG", Name = "Chaotic Good", Description = "creatures act as their conscience directs, with little regard for what others expect. Copper dragons, many elves, and unicorns are chaotic good."
                    },
                    new Alignment {
                        AlignmentCode = "CN", Name = "Chaotic Neutral", Description = "creatures follow their whims, holding their personal freedom above all else. Many barbarians and rogues, and some bards, are chaotic neutral."
                    },
                    new Alignment {
                        AlignmentCode = "CE", Name = "Chaotic Evil", Description = "creatures act with arbitrary violence, spurred by their greed, hatred, or bloodlust. Demons, red dragons, and orcs are chaotic evil."
                    },
                };

                context.Alignments.AddRange(alignments);
                context.SaveChanges();
            }


            //Users
            string password = "******";

            if (await userManager.FindByNameAsync("[email protected]") == null)
            {
                var user = new ApplicationUser {
                    UserName = "******",
                    Email    = "[email protected]"
                };
                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);
                }
            }

            var chloee = await userManager.FindByEmailAsync("[email protected]");

            string path = Directory.GetCurrentDirectory();

            Byte[] test = File.ReadAllBytes(path + "\\wwwroot\\images\\taako.jpg");

            if (!context.Characters.Any())
            {
                List <Character> characters = new List <Character>()
                {
                    new Character {
                        User             = chloee.Id,
                        Name             = "Lou-Lou",
                        Class            = "Rogue",
                        Race             = "Elf",
                        Alignment        = "CG",
                        ExperiencePoints = 100,
                        Level            = 1,
                    },
                    new Character {
                        User             = chloee.Id,
                        Name             = "Taako",
                        Class            = "Wizard",
                        Race             = "Elf",
                        Alignment        = "CG",
                        ExperiencePoints = 100,
                        Level            = 1,
                        Picture          = File.ReadAllBytes(path + "\\wwwroot\\images\\taako.jpg"),
                        Strength         = 10,
                        Dexterity        = 15,
                        Consitution      = 14,
                        Intelligence     = 16,
                        Wisdom           = 12,
                        Charisma         = 8,
                        Inspiration      = 1,
                        ProficiencyBonus = 2,
                        ArmorClass       = 12,
                        Initiative       = 2,
                        Speed            = 20,
                        //Saving Throws
                        ST_Strength     = 0,
                        ST_Dexterity    = 2,
                        ST_Consitution  = 2,
                        ST_Intelligence = 5,
                        ST_Wisdom       = 3,
                        ST_Charisma     = -1,
                        //Skills
                        Acrobatics     = 2,
                        AnimalHandling = 1,
                        Arcana         = 5,
                        Athletics      = 0,
                        Deception      = -1,
                        History        = 3,
                        Insight        = 3,
                        Intimidation   = -1,
                        Investigation  = 5,
                        Medicine       = 1,
                        Nature         = 3,
                        Perception     = 3,
                        Performance    = -1,
                        Persuasion     = -1,
                        Religion       = 5,
                        SleightOfHand  = 2,
                        Stealth        = 2,
                        Survival       = 1
                    },
                    new Character {
                        User             = chloee.Id,
                        Name             = "Magnus Burnsides",
                        Class            = "Fighter",
                        Race             = "Human",
                        Alignment        = "LG",
                        ExperiencePoints = 100,
                        Level            = 1,
                        Picture          = File.ReadAllBytes(path + "\\wwwroot\\images\\magnus.jpg"),
                        Strength         = 16,
                        Dexterity        = 14,
                        Consitution      = 15,
                        Intelligence     = 10,
                        Wisdom           = 8,
                        Charisma         = 12,
                        Inspiration      = 1,
                        ProficiencyBonus = 2,
                        ArmorClass       = 17,
                        Initiative       = 2,
                        Speed            = 30,
                        //Saving Throws
                        ST_Strength     = 5,
                        ST_Dexterity    = 2,
                        ST_Consitution  = 4,
                        ST_Intelligence = 0,
                        ST_Wisdom       = -1,
                        ST_Charisma     = 1,
                        //Skills
                        Acrobatics     = 2,
                        AnimalHandling = 2,
                        Arcana         = 0,
                        Athletics      = 5,
                        Deception      = 1,
                        History        = 0,
                        Insight        = -1,
                        Intimidation   = 3,
                        Investigation  = 0,
                        Medicine       = -1,
                        Nature         = 0,
                        Perception     = -1,
                        Performance    = 1,
                        Persuasion     = 1,
                        Religion       = 0,
                        SleightOfHand  = 2,
                        Stealth        = 2,
                        Survival       = 1
                    },
                    new Character {
                        User             = chloee.Id,
                        Name             = "Merle Highchurch",
                        Class            = "Cleric",
                        Race             = "Dwarf",
                        Alignment        = "LG",
                        ExperiencePoints = 100,
                        Level            = 1,
                        Picture          = File.ReadAllBytes(path + "\\wwwroot\\images\\merle.jpg")
                    },
                };
                context.Characters.AddRange(characters);
                context.SaveChanges();
            }

            if (!context.CharacterEquipment.Any())
            {
                List <CharacterEquipment> characterEquipments = new List <CharacterEquipment>()
                {
                    new CharacterEquipment {
                        User = chloee.Id, Name = "Taako", ItemName = "Umbra-Staff", Description = "A Magical umbrella"
                    },
                    new CharacterEquipment {
                        User = chloee.Id, Name = "Taako", ItemName = "Wand of Switcheroo", Description = "When pointed at another creature of similar size within 100 feet and activated the holder will switch places with the target if it is willing. If the target is unwilling it must succeed a DC 17 Constitution saving throw to remain in place. Holds 3 charges, regains one charge after a long rest."
                    },
                    new CharacterEquipment {
                        User = chloee.Id, Name = "Taako", ItemName = "Flaming Poisoning Raging Sword Of Doom", Description = "It features a gigantic blade wreathed in flames with a crooked, oozing scorpion’s stinger affixed to its point. Deals an extra 20 melee damage."
                    },
                    new CharacterEquipment {
                        User = chloee.Id, Name = "Taako", ItemName = "Stone of Farspeech", Description = "Basically a fantasy walkie-talkie or, if you prefer, a fantasy smartphone."
                    },

                    new CharacterEquipment {
                        User = chloee.Id, Name = "Merle Highchurch", ItemName = "Phone-a-Friend Scrybones", Description = "The Scrybones enable the bearer to ask the Dungeon Master (Griffin) a yes-or-no question once per day."
                    },
                    new CharacterEquipment {
                        User = chloee.Id, Name = "Merle Highchurch", ItemName = "Extreme Teen Bible", Description = "The Extreme Teen Bible is a +1 holy symbol featuring a rad skateboarder on its cover. It allows the user to more easily spread the work of Pan to teens.."
                    },
                    new CharacterEquipment {
                        User = chloee.Id, Name = "Merle Highchurch", ItemName = "Nitpicker", Description = "The Nitpicker is a highly sarcastic, cantankerous humanoid resembling a garden gnome. Twice a day, it can be brought into the presence of a lock, wherein it becomes animated and picks the lock. While working, the Nitpicker criticizes the members of the party on their recent performance in the campaign."
                    },
                    new CharacterEquipment {
                        User = chloee.Id, Name = "Merle Highchurch", ItemName = "Stone of Farspeech", Description = "Basically a fantasy walkie-talkie or, if you prefer, a fantasy smartphone."
                    },

                    new CharacterEquipment {
                        User = chloee.Id, Name = "Magnus Burnsides", ItemName = "Rail Splitter", Description = "An ax offers +1 to attack and damage rolls, as well as the ability to fell any tree once per day."
                    },
                    new CharacterEquipment {
                        User = chloee.Id, Name = "Magnus Burnsides", ItemName = "Stone of Farspeech", Description = "Basically a fantasy walkie-talkie or, if you prefer, a fantasy smartphone."
                    },
                    new CharacterEquipment {
                        User = chloee.Id, Name = "Magnus Burnsides", ItemName = "Lens of straight creepin'", Description = "Allows the user to find footprints, tracks or markings of any person or thing that traveled through the area recently once per day."
                    },
                    new CharacterEquipment {
                        User = chloee.Id, Name = "Magnus Burnsides", ItemName = "Gluttons Fork", Description = "Once a day, this fork will allow the user to eat any non-magical item they can fit in their mouth and gain 2 d6 points of health. Just tap the fork on the item and it will turn edible."
                    },
                };
                context.CharacterEquipment.AddRange(characterEquipments);
                context.SaveChanges();
            }

            if (!context.Proficiencies.Any())
            {
                List <Proficiency> proficiency = new List <Proficiency>()
                {
                    new Proficiency {
                        User = chloee.Id, Name = "Taako", ProficiencyName = "Daggers",
                    },
                    new Proficiency {
                        User = chloee.Id, Name = "Taako", ProficiencyName = "Darts",
                    },
                    new Proficiency {
                        User = chloee.Id, Name = "Taako", ProficiencyName = "Longbows",
                    },
                    new Proficiency {
                        User = chloee.Id, Name = "Taako", ProficiencyName = "Longswords",
                    },
                    new Proficiency {
                        User = chloee.Id, Name = "Taako", ProficiencyName = "Quartershaft",
                    },
                    new Proficiency {
                        User = chloee.Id, Name = "Taako", ProficiencyName = "Shortbows",
                    },
                    new Proficiency {
                        User = chloee.Id, Name = "Taako", ProficiencyName = "Shortswords",
                    },
                    new Proficiency {
                        User = chloee.Id, Name = "Taako", ProficiencyName = "Sling",
                    },
                    new Proficiency {
                        User = chloee.Id, Name = "Magnus Burnsides", ProficiencyName = "Animal Handling",
                    },
                    new Proficiency {
                        User = chloee.Id, Name = "Magnus Burnsides", ProficiencyName = "vehicles",
                    },
                    new Proficiency {
                        User = chloee.Id, Name = "Merle Highchurch", ProficiencyName = "shortsword",
                    },
                    new Proficiency {
                        User = chloee.Id, Name = "Merle Highchurch", ProficiencyName = "Religion",
                    },
                };
                context.Proficiencies.AddRange(proficiency);
                context.SaveChanges();
            }
        }
Exemplo n.º 32
0
        private static void Seed(
            AppDbContext context,
            AdminConfig adminConfig,
            ILogger <AppDbContext> logger,
            UserManager <User> userManager,
            RoleManager <IdentityRole <int> > rolesManager
            )
        {
            try
            {
                /* init app */
                var roles = Enum.GetNames(typeof(UserRoles));

                var dbRoles = context.Roles.ToList();

                if (roles.Length > dbRoles.Count)
                {
                    var rolesToAdd = roles
                                     .Where(x => dbRoles.All(dbr => dbr.Name != x));

                    foreach (var role in rolesToAdd)
                    {
                        rolesManager.CreateAsync(new IdentityRole <int>(role)).Wait();
                    }
                }

                context.SaveChanges();

                /* init project data */
                /* admin */
                var mainAdmin = new User(adminConfig.Mail)
                {
                    Nick  = adminConfig.Nick,
                    Photo = adminConfig.Photo
                };

                var createResult = userManager.CreateAsync(user: mainAdmin).GetAwaiter().GetResult();

                context.SaveChanges();

                var addPasswordResult = userManager.AddPasswordAsync(mainAdmin, adminConfig.Password).GetAwaiter().GetResult();
                var addRoleResult     = userManager.AddToRoleAsync(mainAdmin, UserRoles.Admin.ToString()).GetAwaiter().GetResult();

                context.SaveChanges();

                /* subjects */
                var reactSubject = new Subject("React.js");
                context.Add(reactSubject);
                context.SaveChanges();

                using var stream =
                          typeof(AppDbInitialize).Assembly.GetManifestResourceStream("Infrastructure.lessons.json");

                using var reader = new StreamReader(stream !);

                var text = reader.ReadToEnd();

                var objs = JsonConvert.DeserializeObject <LessonDetailedView[]>(text);

                var lessons = objs.Select(x =>
                                          new Lesson(x.Name, x.IsPractice, reactSubject, x.Index, x.Description, x.Content));

                context.Lessons.AddRange(lessons);

                context.SaveChanges();
            }
            catch (Exception err)
            {
                logger.LogCritical(err.Message);
                throw;
            }
        }
        public static async Task Initialize(ApplicationDbContext context,
                                            UserManager <ApplicationUser> userManager,
                                            RoleManager <ApplicationRole> roleManager)
        {
            context.Database.EnsureCreated();

            String adminId1 = "";
            String adminId2 = "";

            string role1 = "Admin";
            string desc1 = "This is the administrator role";

            string role2 = "Member";
            string desc2 = "This is the members role";

            string password = "******";

            if (await roleManager.FindByNameAsync(role1) == null)
            {
                await roleManager.CreateAsync(new ApplicationRole(role1, desc1, DateTime.Now));
            }
            if (await roleManager.FindByNameAsync(role2) == null)
            {
                await roleManager.CreateAsync(new ApplicationRole(role2, desc2, DateTime.Now));
            }

            if (await userManager.FindByNameAsync("a") == null)
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "[email protected]",
                    FirstName   = "Adam",
                    LastName    = "Aldridge",
                    Street      = "Fake St",
                    City        = "Vancouver",
                    Province    = "BC",
                    PostalCode  = "V5U K8I",
                    Country     = "Canada",
                    PhoneNumber = "6902341234"
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role1);
                }
                adminId1 = user.Id;
            }

            if (await userManager.FindByNameAsync("b") == null)
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "[email protected]",
                    FirstName   = "Bob",
                    LastName    = "Barker",
                    Street      = "Vermont St",
                    City        = "Surrey",
                    Province    = "BC",
                    PostalCode  = "V1P I5T",
                    Country     = "Canada",
                    PhoneNumber = "7788951456"
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role1);
                }
                adminId2 = user.Id;
            }

            if (await userManager.FindByNameAsync("m") == null)
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "[email protected]",
                    FirstName   = "Mike",
                    LastName    = "Myers",
                    Street      = "Yew St",
                    City        = "Vancouver",
                    Province    = "BC",
                    PostalCode  = "V3U E2Y",
                    Country     = "Canada",
                    PhoneNumber = "6572136821"
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role2);
                }
            }

            if (await userManager.FindByNameAsync("d") == null)
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "[email protected]",
                    FirstName   = "Donald",
                    LastName    = "Duck",
                    Street      = "Well St",
                    City        = "Vancouver",
                    Province    = "BC",
                    PostalCode  = "V8U R9Y",
                    Country     = "Canada",
                    PhoneNumber = "6041234567"
                };

                var result = await userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await userManager.AddPasswordAsync(user, password);

                    await userManager.AddToRoleAsync(user, role2);
                }
            }
        }
Exemplo n.º 34
0
 public Task <IActionResult> SetPassword(SetPasswordModel model)
 {
     return(MakeChangeAsync(user => userManager.AddPasswordAsync(user.Identity, model.Password),
                            "Password set successfully."));
 }