public async Task <IActionResult> Edit(int id, [Bind("UserToRoleID,UserID,RoleID")] UserToRole userToRole)
        {
            if (id != userToRole.UserToRoleID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(userToRole);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserToRoleExists(userToRole.UserToRoleID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(userToRole));
        }
Esempio n. 2
0
        private static void InertUsersAnsRoles(IUserToRoleRepository userToRoleRepository)
        {
            var user1 = new User("Vadim", "Abdullaev", "password", "Abdullaev@email");
            //userRepository.Save(user1);
            var user2 = new User("Jon", "Willson", "password", "Willson@email");
            //userRepository.Save(user2);
            var user3 = new User("Serge", "Ibaka", "password", "Ibaka@email");
            //userRepository.Save(user3);

            var roleAdmin = new Role("Admin");
            //roleRepository.Save(roleAdmin);

            var roleUser = new Role("User");
            //roleRepository.Save(roleUser);

            var user1ToAdmin = new UserToRole(user1, roleAdmin);

            userToRoleRepository.Save(user1ToAdmin);

            var user1ToUserRole = new UserToRole(user1, roleUser);

            userToRoleRepository.Save(user1ToUserRole);
            user1ToUserRole = new UserToRole(user2, roleUser);
            userToRoleRepository.Save(user1ToUserRole);
            user1ToUserRole = new UserToRole(user3, roleUser);
            userToRoleRepository.Save(user1ToUserRole);
        }
        public async Task TestAddRoleToUseTrigger()
        {
            //SETUP
            var options = SqliteInMemory.CreateOptions <ExtraAuthorizeDbContext>();

            using (var context = new ExtraAuthorizeDbContext(options, new AuthChanges()))
            {
                context.Database.EnsureCreated();
                var rolToPer = RoleToPermissions.CreateRoleWithPermissions
                                   ("test", "test", new List <Permissions> {
                    Permissions.AccessAll
                }, context).Result;
                context.Add(rolToPer);
                context.SaveChanges();

                //ATTEMPT
                var userToRole = new UserToRole("test", rolToPer);
                context.Add(userToRole);
                await context.SaveChangesAsync();

                //VERIFY
                context.TimeStores.Count().ShouldEqual(1);
                context.UserToRoles.Count().ShouldEqual(1);
            }
        }
        public static void SeedUserWithTwoRoles(this ExtraAuthorizeDbContext context, string userId = "userId")
        {
            var userStatus = RoleToPermissions.CreateRoleWithPermissions(
                "TestRole1", "TestRole1", new List <Permissions> {
                Permissions.StockRead
            }, context);

            userStatus.IsValid.ShouldBeTrue(userStatus.GetAllErrors());
            context.Add(userStatus.Result);
            userStatus = RoleToPermissions.CreateRoleWithPermissions(
                "TestRole2", "TestRole1", new List <Permissions> {
                Permissions.SalesSell
            }, context);
            userStatus.IsValid.ShouldBeTrue(userStatus.GetAllErrors());
            context.Add(userStatus.Result);

            var roleStatus = UserToRole.AddRoleToUser(userId, "TestRole1", context);

            roleStatus.IsValid.ShouldBeTrue(userStatus.GetAllErrors());
            context.Add(roleStatus.Result);
            roleStatus = UserToRole.AddRoleToUser(userId, "TestRole2", context);
            roleStatus.IsValid.ShouldBeTrue(userStatus.GetAllErrors());
            context.Add(roleStatus.Result);

            context.SaveChanges();
        }
        /// <summary>
        /// 尝试创建用户,并发送注册邮件到用户邮箱
        /// </summary>
        /// <param name="registerUser"></param>
        /// <param name="roleType"></param>
        /// <returns></returns>
        private async Task <ValueTuple <bool, MoUserInfo> > TryCreateUser(MoUserInfoSimple registerUser, RoleType roleType)
        {
            if (registerUser == null)
            {
                throw new ArgumentNullException(nameof(registerUser));
            }

            // 因为我们要考虑到已经入库了但邮箱还未激活的用户(也就是还未完成全部注册流程的用户)可能会重复注册,所以我这里改成这样子
            User user = _uf.UserRepository.GetFirstOrDefault(x => x.Email.Equals(registerUser.UserName, StringComparison.OrdinalIgnoreCase));

            if (user == null)
            {
                using (var trans = _uf.BeginTransaction())
                {
                    try
                    {
                        user = await _uf.UserRepository.CreateUserAsync(registerUser);

                        //_uf.SaveChanges();
                        var role = await _uf.RoleRepository.GetOrAddAsync(roleType);

                        //_uf.SaveChanges();
                        var userToRole = new UserToRole
                        {
                            UserId = user.Id,
                            RoleId = role.Id
                        };

                        await _uf.UserToRoleRepository.InsertAsync(userToRole);

                        await _uf.SaveChangesAsync();

                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        this.MsgBox("注册用户失败");
                        return(false, null);
                    }
                }
            }

            var userInfo = new MoUserInfo
            {
                Id         = user.Id,
                UserStatus = (int)user.UserStatus,
                Email      = user.Email,
                HeadPhoto  = user.HeadPhoto,
                UserName   = user.UserName,
                Roles      = roleType.ToString()
            };

            HttpContext.AddUserInfo(userInfo);
            this.MsgBox("注册用户成功,请查看您的邮箱,确认激活!");
            return(true, userInfo);
        }
Esempio n. 6
0
        /// <summary>
        /// This ensures there is a UserToRole linking the userId to the given roleName
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="roleName"></param>
        public async Task AddRoleToUserAsync(string userId, string roleName)
        {
            IStatusGeneric <UserToRole> status = await UserToRole.AddRoleToUserAsync(userId, roleName, _repository);

            if (status.IsValid)
            {
                //we assume there is already a link to the role is the status wasn't valid
                await _repository.AddAsync(status.Result);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// This ensures there is a UserToRole linking the userId to the given roleName
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="roleName"></param>
        public void CheckAddRoleToUser(string userId, string roleName)
        {
            var status = UserToRole.AddRoleToUser(userId, roleName, _context);

            if (status.IsValid)
            {
                //we assume there is already a link to the role is the status wasn't valid
                _context.Add(status.Result);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// 修改用户角色对应表
        /// </summary>
        /// <param name="index">用户角色对应表对象</param>
        /// <returns></returns>
        public int Update(UserToRole index)
        {
            string sql = "update User_To_Role set Id=@Id,User_Id=@User_Id,Role_Id=@Role_Id where Id=@Id";

            SQLiteParameter[] parm = new SQLiteParameter[] {
                new SQLiteParameter("@Id", index.Id),
                new SQLiteParameter("@User_Id", index.UserId),
                new SQLiteParameter("@Role_Id", index.RoleId)
            };
            return(SqlLiteHelper.ExecuteNonQuery(sql, CommandType.Text, parm));
        }
Esempio n. 9
0
        /// <summary>
        /// 增加用户角色对应表
        /// </summary>
        /// <param name="index">用户角色对应表对象</param>
        /// <returns></returns>
        public int Add(UserToRole index)
        {
            string sql = string.Format("insert into User_To_Role(Id,User_Id,Role_Id) values(@Id,@User_Id,@Role_Id)");

            SQLiteParameter[] parm = new SQLiteParameter[] {
                new SQLiteParameter("@Id", index.Id),
                new SQLiteParameter("@User_Id", index.UserId),
                new SQLiteParameter("@Role_Id", index.RoleId)
            };
            return(SqlLiteHelper.ExecuteNonQuery(sql, CommandType.Text, parm));
        }
        public async Task <IActionResult> Create([Bind("UserToRoleID,UserID,RoleID")] UserToRole userToRole)
        {
            if (ModelState.IsValid)
            {
                _context.Add(userToRole);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(userToRole));
        }
Esempio n. 11
0
        public async Task <bool> AddRole(int IdUser, int IdRole)
        {
            var UR = new UserToRole()
            {
                IsActive = true,
                RoleId   = IdRole,
                UserId   = IdUser
            };
            await _context.UserRoles.AddAsync(UR);

            await _context.SaveChangesAsync();

            return(true);
        }
Esempio n. 12
0
        public async Task <IActionResult> AddRoleToUser([FromBody] UserToRole userToRole)
        {
            var user = await _userManager.FindByNameAsync(userToRole.User);

            if (!await _userManager.IsInRoleAsync(user, userToRole.Role))
            {
                await _userManager.AddToRoleAsync(user, userToRole.Role);

                return(Ok("Role added to User"));
            }
            else
            {
                return(Ok("User has this role already"));
            }
        }
Esempio n. 13
0
        public async Task <IActionResult> AssigningUserToRole([FromBody] UserToRole userToRole)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var assign = await _auth.UserToRoleAssign(userToRole);

            if (!string.IsNullOrEmpty(assign))
            {
                return(BadRequest(assign));
            }

            return(Ok(userToRole));
        }
Esempio n. 14
0
 public int RemoveRoleFromUser([FromBody] UserToRole usrtoRoleMap)
 {
     using (DataAccessLayer modelAccess = new DataAccessLayer())
     {
         try
         {
             LogHelper.WarnLog("Attempting to remove Role with ID: " + usrtoRoleMap.roleID + " from User with ID: " + usrtoRoleMap.userID);
             modelAccess.DeleteUserFromRole(usrtoRoleMap.userID, usrtoRoleMap.roleID);
             return(1);
         }
         catch (Exception ex)
         {
             LogHelper.ErrorLog("Error Removing Role from User: " + ex.ToString());
             return(0);
         }
     }
 }
Esempio n. 15
0
        public async Task <IActionResult> Edit(UserToRole model)
        {
            IdentityResult result;

            if (ModelState.IsValid)
            {
                foreach (string userId in model.IdToAdd ?? new string[] { })
                {
                    ApplicationUser user = await _userManager.FindByIdAsync(userId);

                    if (user != null)
                    {
                        result = await _userManager.AddToRoleAsync(user, model.RoleName);

                        if (!result.Succeeded)
                        {
                            AddErrorsFromResult(result);
                        }
                    }
                }

                foreach (string userId in model.IdToDelete ?? new string[] { })
                {
                    ApplicationUser user = await _userManager.FindByIdAsync(userId);

                    if (user != null)
                    {
                        result = await _userManager.RemoveFromRoleAsync(user,
                                                                        model.RoleName);

                        if (!result.Succeeded)
                        {
                            AddErrorsFromResult(result);
                        }
                    }
                }
            }
            if (ModelState.IsValid)
            {
                return(RedirectToAction(nameof(Edit)));
            }
            else
            {
                return(await Edit(model.RoleId));
            }
        }
Esempio n. 16
0
 public int AddRoleToUser([FromBody] UserToRole usrtoRoleMap)
 {
     using (DataAccessLayer modelAccess = new DataAccessLayer())
     {
         try
         {
             LogHelper.WarnLog("Attempting to add Role with ID: " + usrtoRoleMap.roleID + " to user with ID: " + usrtoRoleMap.userID);
             modelAccess.AddUserToRole(usrtoRoleMap.userID, usrtoRoleMap.roleID, true);
             return(1);
         }
         catch (Exception ex)
         {
             LogHelper.ErrorLog("Error Attempting to add Role with ID: " + usrtoRoleMap.roleID + " to user with ID: " + usrtoRoleMap.userID + " with Error: " + ex.ToString());
             return(0);
         }
     }
 }
Esempio n. 17
0
        public async Task <string> UserToRoleAssign(UserToRole userRole)
        {
            var usr = await _userManager.FindByIdAsync(userRole.UserId);

            if (usr is null || !await _roleManager.RoleExistsAsync(userRole.roleName))
            {
                return("Something went wrong");
            }

            //return usr is null || !await _roleManager.RoleExistsAsync(userRole.roleName) ? "Something went wrong" :

            if (await _userManager.IsInRoleAsync(usr, userRole.roleName))
            {
                return("the user is already assigned to this role");
            }

            var assigning = await _userManager.AddToRoleAsync(usr, userRole.roleName);

            return(assigning.Succeeded ? string.Empty : "something wrong");
        }
Esempio n. 18
0
        public async Task <ActionResult> AsignRole(UserToRole model)
        {
            ApplicationUser User = _context.Users.Where(user => user.Email.Equals(model.UserEmail)).First();

            if (User != null)
            {
                IdentityRole role = _context.Roles.Find(model.RoleId.ToString());
                await UserManager.AddToRoleAsync(User.Id, role.Name);

                if (role.Name == "Seller" || role.Name == "Administrator")
                {
                    SubmitedProducts submitedProducts = new SubmitedProducts();
                    submitedProducts.UserId   = User.Id;
                    submitedProducts.Products = new System.Collections.Generic.List <ShoppingItem>();
                    _context.SubmitedProducts.Add(submitedProducts);
                    _context.Entry(submitedProducts).State = System.Data.Entity.EntityState.Added;
                    _context.SaveChanges();
                }
            }
            return(RedirectToAction("Index", "Home"));
        }
Esempio n. 19
0
        /// <summary>
        /// 根据编号查询用户角色对应表
        /// </summary>
        /// <param name="Id">编号</param>
        /// <returns>数据集合</returns>
        public UserToRole Select(string Id)
        {
            String sql = "select * from UserToRole where Id=@Id";

            System.Data.SQLite.SQLiteParameter[] parm = new System.Data.SQLite.SQLiteParameter[] {
                new SQLiteParameter("@Id", Id),
            };
            DataTable dt = SqlLiteHelper.GetTable(sql, CommandType.Text, parm);

            if (dt.Rows.Count > 0)
            {
                UserToRole index = new UserToRole();
                index.Id     = dt.Rows[0]["Id"].GetString();
                index.UserId = dt.Rows[0]["User_Id"].GetString();
                index.RoleId = dt.Rows[0]["Role_Id"].GetString();
                return(index);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 20
0
        /// <summary>
        /// 分页查询用户角色对应表
        /// </summary>
        /// <param name="pageSize">每页多少条数据</param>
        /// <param name="start">排除多少条数据</param>
        /// <param name="hash">筛选条件</param>
        /// <param name="total">总共多少条</param>
        /// <returns>数据集合</returns>
        public List <UserToRole> Select(int pageSize, int start, HashTableExp hash, out int total, String sqlWhere)
        {
            List <UserToRole> list = new List <UserToRole>();

            sqlWhere = "1=1 " + sqlWhere;

            #region 查询条件
            if (hash != null)
            {
                if (hash["Id"] != null)
                {
                    sqlWhere += string.Format(" and Id='{0}'", hash["Id"]);
                }
                if (hash["UserId"] != null)
                {
                    sqlWhere += string.Format(" and User_Id='{0}'", hash["UserId"]);
                }
                if (hash["RoleId"] != null)
                {
                    sqlWhere += string.Format(" and Role_Id='{0}'", hash["RoleId"]);
                }
            }
            #endregion

            DataTable dt = SqlLiteHelper.GetTable("User_To_Role",
                                                  "Id,User_Id,Role_Id",
                                                  pageSize, start, sqlWhere, "Id", "asc", out total);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                UserToRole index = new UserToRole();
                index.Id     = dt.Rows[i]["Id"].GetString();
                index.UserId = dt.Rows[i]["User_Id"].GetString();
                index.RoleId = dt.Rows[i]["Role_Id"].GetString();
                list.Add(index);
            }

            return(list);
        }
        public static void SeedUserWithDefaultPermissions(this ExtraAuthorizeDbContext context,
                                                          PaidForModules modules = PaidForModules.None, string userId = "userId")
        {
            var defaultPermissions = new List <Permissions> {
                Permissions.StockRead, Permissions.Feature1Access
            };

            var roleStatus = RoleToPermissions.CreateRoleWithPermissions(
                "TestRole1", "TestRole1", defaultPermissions, context);

            roleStatus.IsValid.ShouldBeTrue(roleStatus.GetAllErrors());
            context.Add(roleStatus.Result);

            var moduleUser = new ModulesForUser(userId, modules);

            context.Add(moduleUser);

            var userStatus = UserToRole.AddRoleToUser(userId, "TestRole1", context);

            userStatus.IsValid.ShouldBeTrue(roleStatus.GetAllErrors());
            context.Add(userStatus.Result);

            context.SaveChanges();
        }
Esempio n. 22
0
        /// <summary>
        /// 查询所有数据
        /// </summary>
        /// <returns></returns>
        public List <UserToRole> Select(HashTableExp hash, String sqlWhere)
        {
            List <UserToRole> list = new List <UserToRole>();
            string            sql  = "select Id,User_Id,Role_Id from User_To_Role where 1=1 ";

            #region 查询条件
            if (hash != null)
            {
                if (hash["Id"] != null)
                {
                    sql += string.Format(" and Id='{0}'", hash["Id"]);
                }
                if (hash["UserId"] != null)
                {
                    sql += string.Format(" and User_Id='{0}'", hash["UserId"]);
                }
                if (hash["RoleId"] != null)
                {
                    sql += string.Format(" and Role_Id='{0}'", hash["RoleId"]);
                }
            }
            #endregion

            sql += sqlWhere;

            DataTable dt = SqlLiteHelper.GetTable(sql, CommandType.Text);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                UserToRole index = new UserToRole();
                index.Id     = dt.Rows[i]["Id"].GetString();
                index.UserId = dt.Rows[i]["User_Id"].GetString();
                index.RoleId = dt.Rows[i]["Role_Id"].GetString();
                list.Add(index);
            }
            return(list);
        }
Esempio n. 23
0
 /// <summary>
 /// 新增
 /// </summary>
 /// <returns>影响的行数</returns>
 public int Add(UserToRole userToRole)
 {
     return(dLUserToRole.Add(userToRole));
 }
Esempio n. 24
0
        public static async Task InitializeAsync(IServiceProvider services)
        {
            var databaseDbContext = services.GetRequiredService <StoreOrderDbContext>();
            var logger            = services.GetRequiredService <ILogger <StoreOrderDbContext> >();

            // migration db
            databaseDbContext.Database.EnsureCreated();

            if (!databaseDbContext.Roles.Any())
            {
                string password = "******";
                var    hashPass = Helpers.SercurityHelper.GenerateSaltedHash(password);

                //// I will add 1 user to one Role
                //var book1 = new Book();
                //var book2 = new Book();
                var roleAdmin = new Role {
                    Id = Guid.NewGuid().ToString(), Code = Guid.NewGuid().ToString(), RoleName = RoleTypeHelper.RoleAdmin, Desc = "Admin of Store"
                };
                var roleOrderUser = new Role {
                    Id = Guid.NewGuid().ToString(), Code = Guid.NewGuid().ToString(), RoleName = RoleTypeHelper.RoleOrderUser, Desc = "NV Order of Store"
                };
                var roleCookieUser = new Role {
                    Id = Guid.NewGuid().ToString(), Code = Guid.NewGuid().ToString(), RoleName = RoleTypeHelper.RoleCookieUser, Desc = "NV phụ bếp of Store"
                };
                var rolePayUser = new Role {
                    Id = Guid.NewGuid().ToString(), Code = Guid.NewGuid().ToString(), RoleName = RoleTypeHelper.RolePayUser, Desc = "Nv Thanh toán of Store"
                };
                var roleCustomerUser = new Role {
                    Id = Guid.NewGuid().ToString(), Code = Guid.NewGuid().ToString(), RoleName = RoleTypeHelper.RoleCustomerUser, Desc = "Role Account of Customer"
                };

                //// I create the User
                //var lib = new Library();
                var user1 = new User {
                    Id = Guid.NewGuid().ToString(), Age = 29, BirthDay = new DateTime(1991, 1, 1).ToUniversalTime(), CountLoginFailed = 0, FirstName = "admin", LastName = "admin", IsActived = 1, Email = "*****@*****.**", UserName = "******", HashPassword = hashPass.Hash, SaltPassword = hashPass.Salt, Gender = 1, OldPassword = hashPass.Hash + ";" + hashPass.Salt, PhoneNumber = "1234567"
                };
                var nv1 = new User {
                    Id = Guid.NewGuid().ToString(), Age = 29, BirthDay = new DateTime(1991, 1, 1).ToUniversalTime(), CountLoginFailed = 0, FirstName = "nv1", LastName = "nv1", IsActived = 1, Email = "*****@*****.**", UserName = "******", HashPassword = hashPass.Hash, SaltPassword = hashPass.Salt, Gender = 1, OldPassword = hashPass.Hash + ";" + hashPass.Salt, PhoneNumber = "1234567"
                };
                var nv2 = new User {
                    Id = Guid.NewGuid().ToString(), Age = 29, BirthDay = new DateTime(1991, 1, 1).ToUniversalTime(), CountLoginFailed = 0, FirstName = "nv2", LastName = "nv2", IsActived = 1, Email = "*****@*****.**", UserName = "******", HashPassword = hashPass.Hash, SaltPassword = hashPass.Salt, Gender = 1, OldPassword = hashPass.Hash + ";" + hashPass.Salt, PhoneNumber = "1234567"
                };
                var nv3 = new User {
                    Id = Guid.NewGuid().ToString(), Age = 29, BirthDay = new DateTime(1991, 1, 1).ToUniversalTime(), CountLoginFailed = 0, FirstName = "nv3", LastName = "nv3", IsActived = 1, Email = "*****@*****.**", UserName = "******", HashPassword = hashPass.Hash, SaltPassword = hashPass.Salt, Gender = 1, OldPassword = hashPass.Hash + ";" + hashPass.Salt, PhoneNumber = "1234567"
                };

                //// I create two UserToRole which I need them
                //// To map between the users and the role
                //var b2lib1 = new Library2Book();
                //var b2lib2 = new Library2Book();
                var userToRole1 = new UserToRole();
                var userToRole2 = new UserToRole();
                var userToRole3 = new UserToRole();
                var userToRole4 = new UserToRole();
                //// Mapping the first book to the library.
                //// Changed userToRole1.Role to userToRole2.Role
                //// Changed b2lib2.Library to b2lib1.Library
                //b2lib1.Book = book1;
                //b2lib1.Library = lib;
                userToRole1.Role = roleAdmin;
                userToRole1.User = user1;

                //// I map the second book to the library.
                //b2lib2.Book = book2;
                //b2lib2.Library = lib;
                userToRole2.Role = roleOrderUser;
                userToRole2.User = nv1;

                userToRole3.Role = roleCookieUser;
                userToRole3.User = nv2;

                userToRole4.Role = rolePayUser;
                userToRole4.User = nv3;

                //// Linking the books (Library2Book table) to the library
                //lib.Library2Books.Add(b2lib1);
                //lib.Library2Books.Add(b2lib2);
                roleAdmin.UserToRoles.Add(userToRole1);
                roleOrderUser.UserToRoles.Add(userToRole2);
                roleCookieUser.UserToRoles.Add(userToRole3);
                rolePayUser.UserToRoles.Add(userToRole4);

                //// Adding the data to the DbContext.
                //myDb.Libraries.Add(lib);
                databaseDbContext.Roles.Add(roleAdmin);
                databaseDbContext.Users.Add(user1);
                databaseDbContext.SaveChanges();

                databaseDbContext.Roles.Add(roleOrderUser);
                databaseDbContext.Users.Add(nv1);
                databaseDbContext.SaveChanges();

                databaseDbContext.Roles.Add(roleCookieUser);
                databaseDbContext.Users.Add(nv2);
                databaseDbContext.SaveChanges();

                databaseDbContext.Roles.Add(rolePayUser);
                databaseDbContext.Users.Add(nv3);
                databaseDbContext.SaveChanges();

                //myDb.Books.Add(book1);
                //myDb.Books.Add(book2);

                //// Save the changes and everything should be working!
                //myDb.SaveChanges();

                //await databaseDbContext.SaveChangesAsync();

                logger.LogInformation("DatabaseDbContext", "---initial data of Surveys success---");
            }

            if (databaseDbContext.Roles.Count() == 4)
            {
                var roleCustomerUser = new Role {
                    Id = Guid.NewGuid().ToString(), Code = Guid.NewGuid().ToString(), RoleName = RoleTypeHelper.RoleCustomerUser, Desc = "Role Account of Customer"
                };
                await databaseDbContext.Roles.AddAsync(roleCustomerUser);

                await databaseDbContext.SaveChangesAsync();
            }

            if (databaseDbContext.Roles.Count() == 5)
            {
                var roleSysAdmin = new Role {
                    Id = Guid.NewGuid().ToString(), Code = Guid.NewGuid().ToString(), RoleName = RoleTypeHelper.RoleSysAdmin, Desc = "Role SysAdmin"
                };
                await databaseDbContext.Roles.AddAsync(roleSysAdmin);

                await databaseDbContext.SaveChangesAsync();
            }

            if (!databaseDbContext.CategoryStores.Any())
            {
                var catStore = new CategoryStore {
                    Id = Guid.NewGuid().ToString(), Name = "Nhà hàng"
                };
                await databaseDbContext.CategoryStores.AddAsync(catStore);

                await databaseDbContext.SaveChangesAsync();

                var useradmin    = databaseDbContext.Users.FirstOrDefault(x => x.UserName.ToLower().Equals("admin01"));
                var store1       = new Store();
                var optionSize   = new StoreOption();
                var optionToping = new StoreOption();
                if (useradmin != null)
                {
                    if (!databaseDbContext.Stores.Any())
                    {
                        store1 = new Store
                        {
                            Id = Guid.NewGuid().ToString(),
                            CategoryStoreId = catStore.Id,
                            StatusStore     = 1,
                            StoreAddress    = "Số 1, Xuân thủy, Cầu Giấy, Việt Nam",
                            StoreName       = "Store 1",
                            CreateByUserId  = useradmin.Id,
                        };

                        var lstStoreTable = new List <StoreTable>()
                        {
                            new StoreTable
                            {
                                Id           = Guid.NewGuid().ToString(),
                                Location     = 1,
                                LocationUnit = 1,
                                StoreId      = store1.Id,
                                TableCode    = Guid.NewGuid().ToString(),
                                TableName    = "Bàn 1",
                                TableStatus  = 1
                            },
                            new StoreTable
                            {
                                Id           = Guid.NewGuid().ToString(),
                                Location     = 1,
                                LocationUnit = 1,
                                StoreId      = store1.Id,
                                TableCode    = Guid.NewGuid().ToString(),
                                TableName    = "Bàn 2",
                                TableStatus  = 1
                            },
                            new StoreTable
                            {
                                Id           = Guid.NewGuid().ToString(),
                                Location     = 1,
                                LocationUnit = 1,
                                StoreId      = store1.Id,
                                TableCode    = Guid.NewGuid().ToString(),
                                TableName    = "Bàn 3",
                                TableStatus  = 1
                            },
                            new StoreTable
                            {
                                Id           = Guid.NewGuid().ToString(),
                                Location     = 1,
                                LocationUnit = 1,
                                StoreId      = store1.Id,
                                TableCode    = Guid.NewGuid().ToString(),
                                TableName    = "Bàn 4",
                                TableStatus  = 1
                            },
                            new StoreTable
                            {
                                Id           = Guid.NewGuid().ToString(),
                                Location     = 1,
                                LocationUnit = 1,
                                StoreId      = store1.Id,
                                TableCode    = Guid.NewGuid().ToString(),
                                TableName    = "Bàn 5",
                                TableStatus  = 1
                            }
                        };

                        optionSize = new StoreOption {
                            OptionId = Guid.NewGuid().ToString(), StoreId = store1.Id, StoreOptionName = "size", StoreOptionDescription = "Kích thước"
                        };
                        optionToping = new StoreOption {
                            OptionId = Guid.NewGuid().ToString(), StoreId = store1.Id, StoreOptionName = "toping", StoreOptionDescription = "Toping"
                        };

                        var lstStoreOption = new List <StoreOption>()
                        {
                            optionSize,
                            optionToping,
                            new StoreOption {
                                OptionId = Guid.NewGuid().ToString(), StoreId = store1.Id, StoreOptionName = "color", StoreOptionDescription = "Màu sắc"
                            },
                            new StoreOption {
                                OptionId = Guid.NewGuid().ToString(), StoreId = store1.Id, StoreOptionName = "class", StoreOptionDescription = "Lớp"
                            },
                            new StoreOption {
                                OptionId = Guid.NewGuid().ToString(), StoreId = store1.Id, StoreOptionName = "devo", StoreOptionDescription = "Dễ vỡ"
                            },
                        };


                        store1.StoreTables  = lstStoreTable;
                        store1.StoreOptions = lstStoreOption;

                        await databaseDbContext.Stores.AddAsync(store1);

                        await databaseDbContext.SaveChangesAsync();
                    }

                    if (!databaseDbContext.CategoryProducts.Any())
                    {
                        var catProduct = new CategoryProduct
                        {
                            Id           = Guid.NewGuid().ToString(),
                            CategoryName = "Danh mục 1",
                            Slug         = "danh-muc-1",
                            Code         = "danhmuc1code",
                            ParentId     = null,
                        };

                        var lstProducts = new List <Product>()
                        {
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 1", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 02", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 03", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 04", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 05", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 06", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 07", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 08", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 09", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 10", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 11", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 12", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 13", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                            new Product {
                                Id = Guid.NewGuid().ToString(), CategoryId = catProduct.Id, ProductName = "Sản phẩm 14", CreateByUserId = useradmin.Id, StoreId = store1.Id
                            },
                        };
                        catProduct.Products = lstProducts;

                        await databaseDbContext.AddAsync(catProduct);

                        await databaseDbContext.SaveChangesAsync();
                    }
                }
            }

            if (!databaseDbContext.Permissions.Any())
            {
                await databaseDbContext.Permissions.AddRangeAsync(new List <Permission>() {
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.SysAdmin.ImportLocation
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.SysAdmin.ViewLogs
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.SysAdmin.DeleteLogs
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Account.Create
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Account.Delete
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Account.Edit
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Account.View
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Users.View
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Users.Create
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Users.Edit
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Users.Delete
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.SysAdmin.GetListCategoryStore
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.AdminStore.GetListStoreOption
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.AdminStore.GetMenuProduct
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.AdminStore.CreateProduct
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.AdminStore.DeleteProduct
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.AdminStore.UpdateProduct
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.AdminStore.GetListProduct
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Employee.ConfirmOrder
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Employee.ConfirmPayOrder
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Employee.CreateOrder
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Employee.GetCategoryProductsForEmployee
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Employee.GetListOrderWithTableOrProductName
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Employee.GetListProductsOfStoreForEmployee
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Employee.GetListProductsOfStoreForEmployeeV2
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Employee.GetListProductsOfStoreWithCategoryForEmployee
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Employee.GetListProductsOfStoreWithCategoryForEmployeeV2
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Employee.GetListTables
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Employee.GetOrderProductsWithTable
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Employee.GetOrderWithTableViewProductsWithTableId
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Employee.UpdateOrder
                    },
                    new Permission {
                        Id = Guid.NewGuid().ToString(), PermissionName = Permissions.Upload.UploadFile
                    },
                });

                await databaseDbContext.SaveChangesAsync();
            }

            if (!databaseDbContext.RoleToPermissions.Any())
            {
                // get role
                var roleSysadmin = await databaseDbContext.Roles.FirstOrDefaultAsync(x => x.RoleName == RoleTypeHelper.RoleSysAdmin);

                var roleAdminStore = await databaseDbContext.Roles.FirstOrDefaultAsync(x => x.RoleName == RoleTypeHelper.RoleAdmin);

                var roleOrderUser = await databaseDbContext.Roles.FirstOrDefaultAsync(x => x.RoleName == RoleTypeHelper.RoleOrderUser);

                var roleCookieUser = await databaseDbContext.Roles.FirstOrDefaultAsync(x => x.RoleName == RoleTypeHelper.RoleCookieUser);

                var rolePayUser = await databaseDbContext.Roles.FirstOrDefaultAsync(x => x.RoleName == RoleTypeHelper.RolePayUser);

                #region update roleSysAdmin
                var permissionsSysAdmin = databaseDbContext.Permissions
                                          .Where(x => x.PermissionName == Permissions.SysAdmin.ImportLocation ||
                                                 x.PermissionName == Permissions.SysAdmin.ViewLogs ||
                                                 x.PermissionName == Permissions.SysAdmin.DeleteLogs ||
                                                 x.PermissionName == Permissions.Account.Create ||
                                                 x.PermissionName == Permissions.Account.Delete ||
                                                 x.PermissionName == Permissions.Account.Edit ||
                                                 x.PermissionName == Permissions.Account.View ||
                                                 x.PermissionName == Permissions.SysAdmin.GetListStores ||
                                                 x.PermissionName == Permissions.SysAdmin.GetListCategoryStore
                                                 ).Select(x => x).ToList();

                foreach (var permission in permissionsSysAdmin)
                {
                    // add Permissions To Role
                    roleSysadmin.RoleToPermissions.Add(new RoleToPermission
                    {
                        Permission = permission,
                        Role       = roleSysadmin,
                    });
                }
                // save to db
                await databaseDbContext.SaveChangesAsync();

                #endregion

                #region Update RoleAdminStore
                var permissionsAdminStore = databaseDbContext.Permissions
                                            .Where(x => x.PermissionName == Permissions.AdminStore.GetMenuProduct ||
                                                   x.PermissionName == Permissions.AdminStore.GetListStoreOption ||
                                                   x.PermissionName == Permissions.AdminStore.GetListProduct ||
                                                   x.PermissionName == Permissions.AdminStore.CreateProduct ||
                                                   x.PermissionName == Permissions.AdminStore.UpdateProduct ||
                                                   x.PermissionName == Permissions.AdminStore.DeleteProduct ||
                                                   x.PermissionName == Permissions.Upload.UploadFile ||
                                                   x.PermissionName == Permissions.AdminStore.CreateCatProduct ||
                                                   x.PermissionName == Permissions.AdminStore.UpdateCatProduct ||
                                                   x.PermissionName == Permissions.AdminStore.DeleteCatProduct ||
                                                   x.PermissionName == Permissions.AdminStore.GetListCatProduct

                                                   ).Select(x => x).ToList();

                foreach (var permission in permissionsAdminStore)
                {
                    // add Permissions To Role
                    roleAdminStore.RoleToPermissions.Add(new RoleToPermission
                    {
                        Permission = permission,
                        Role       = roleAdminStore,
                    });
                }
                // save to db
                await databaseDbContext.SaveChangesAsync();

                #endregion

                #region Update RoleOrderUser
                var permissionsOrderUsers = databaseDbContext.Permissions
                                            .Where(x => x.PermissionName == Permissions.Employee.GetListTables ||
                                                   x.PermissionName == Permissions.Employee.GetCategoryProductsForEmployee ||
                                                   x.PermissionName == Permissions.Employee.GetListProductsOfStoreForEmployee ||
                                                   x.PermissionName == Permissions.Employee.GetListProductsOfStoreWithCategoryForEmployee ||
                                                   x.PermissionName == Permissions.Employee.GetListProductsOfStoreForEmployeeV2 ||
                                                   x.PermissionName == Permissions.Employee.GetListProductsOfStoreWithCategoryForEmployeeV2 ||
                                                   x.PermissionName == Permissions.Employee.CreateOrder ||
                                                   x.PermissionName == Permissions.Employee.UpdateOrder ||
                                                   x.PermissionName == Permissions.Employee.GetOrderProductsWithTable

                                                   ).Select(x => x).ToList();

                foreach (var permission in permissionsOrderUsers)
                {
                    // add Permissions To Role
                    roleOrderUser.RoleToPermissions.Add(new RoleToPermission
                    {
                        Permission = permission,
                        Role       = roleOrderUser,
                    });
                }
                // save to db
                await databaseDbContext.SaveChangesAsync();

                #endregion

                #region Update RoleCookieUser
                var permissionsOrderCookies = databaseDbContext.Permissions
                                              .Where(x => x.PermissionName == Permissions.Employee.GetOrderProductsWithTable ||
                                                     x.PermissionName == Permissions.Employee.GetListOrderWithTableOrProductName ||
                                                     x.PermissionName == Permissions.Employee.GetOrderWithTableViewProductsWithTableId ||
                                                     x.PermissionName == Permissions.Employee.ConfirmOrder ||
                                                     x.PermissionName == Permissions.Employee.UpdateOrderProductStatus
                                                     ).Select(x => x).ToList();

                foreach (var permission in permissionsOrderCookies)
                {
                    // add Permissions To Role
                    roleCookieUser.RoleToPermissions.Add(new RoleToPermission
                    {
                        Permission = permission,
                        Role       = roleCookieUser,
                    });
                }
                // save to db
                await databaseDbContext.SaveChangesAsync();

                #endregion

                #region Update rolePayUser
                var permissionsPayUsers = databaseDbContext.Permissions
                                          .Where(x => x.PermissionName == Permissions.Employee.ConfirmOrder ||
                                                 x.PermissionName == Permissions.Employee.ConfirmPayOrder
                                                 ).Select(x => x).ToList();

                foreach (var permission in permissionsPayUsers)
                {
                    // add Permissions To Role
                    rolePayUser.RoleToPermissions.Add(new RoleToPermission
                    {
                        Permission = permission,
                        Role       = rolePayUser,
                    });
                }
                // save to db
                await databaseDbContext.SaveChangesAsync();

                #endregion
            }

            if (!databaseDbContext.Users.Include(x => x.UserToRoles).ThenInclude(x => x.Role).Any(x => x.UserToRoles.Any(r => r.Role.RoleName == RoleTypeHelper.RoleSysAdmin)))
            {
                var roleSysAdmin = await databaseDbContext.Roles.FirstOrDefaultAsync(x => x.RoleName == RoleTypeHelper.RoleSysAdmin);

                string password     = "******";
                var    hashPass     = Helpers.SercurityHelper.GenerateSaltedHash(password);
                var    userSysAdmin = new User {
                    Id = Guid.NewGuid().ToString(), Age = 29, BirthDay = new DateTime(1991, 1, 1).ToUniversalTime(), CountLoginFailed = 0, FirstName = "sysadmin", LastName = "sysadmin", IsActived = 1, Email = "*****@*****.**", UserName = "******", HashPassword = hashPass.Hash, SaltPassword = hashPass.Salt, Gender = 1, OldPassword = hashPass.Hash + ";" + hashPass.Salt, PhoneNumber = "0349801673"
                };

                roleSysAdmin.UserToRoles.Add(new UserToRole
                {
                    Role = roleSysAdmin,
                    User = userSysAdmin,
                });

                // save to db
                await databaseDbContext.SaveChangesAsync();
            }
        }
Esempio n. 25
0
 /// <summary>
 /// 修改
 /// </summary>
 /// <returns>影响的行数</returns>
 public int Update(UserToRole userToRole)
 {
     return(dLUserToRole.Update(userToRole));
 }
Esempio n. 26
0
 public async Task <IActionResult> AddToRole([FromBody] UserToRole userToRole)
 {
     return(Ok(await _identityService.AddToRole(userToRole.Username, userToRole.roles)));
 }
Esempio n. 27
0
 public async Task <IActionResult> RemoveToRole(UserToRole userToRole)
 {
     return(Ok(await _identityService.RemoveToRole(userToRole.Username, userToRole.roles)));
 }
Esempio n. 28
0
        public async Task <UserLogined> SignInAndSignUpCustomerAsync(CustomerLoginDTO model)
        {
            // GET roleCustomerUser
            var roleCustomerUser = await _context.Roles.FirstOrDefaultAsync(role => role.RoleName.Equals(RoleTypeHelper.RoleCustomerUser));

            User userCreate = new User();

            // CheckUserExist
            var userExist = await _context.Users
                            .Include(u => u.UserToRoles)
                            .ThenInclude(x => x.Role)
                            .Where(u => u.UserToRoles.Any(x => x.RoleId == roleCustomerUser.Id))
                            .FirstOrDefaultAsync(u => u.Email.ToLower().Equals(model.Email.ToLower()) &&
                                                 u.UseExternalSignIns.Count > 0 && u.UserDevices.Count > 0);

            // case login lần sau:
            if (userExist != null)
            {
                // if exist then update user
                // update To UserDevices
                // update To UserExternalSignIns
                userCreate = userExist;
                _context.Entry(userCreate).State = EntityState.Modified;
                userCreate.LastLogin             = DateTime.UtcNow;
                // check appId & currentUserId Exist
                if (!_context.UserDevices.Any(uc => uc.CurrentUserId == userCreate.Id && uc.CodeDevice == model.AppId))
                {
                    // Add to UserDevices
                    var userDevice = new UserDevice
                    {
                        Id            = Guid.NewGuid().ToString(),
                        IsVerified    = (int)TypeVerified.Verified,
                        VerifiedCode  = (int)(DateTime.Now.Ticks >> 23),
                        CodeDevice    = model.AppId,
                        CurrentUserId = userCreate.Id,
                        LastLogin     = DateTime.UtcNow,
                        TimeCode      = 20
                    };
                    userCreate.UserDevices.Add(userDevice);
                }
                else
                {
                    // Update to UserDevices
                    var userDevice = _context.UserDevices.FirstOrDefault(uc => uc.CurrentUserId == userExist.Id && uc.CodeDevice == model.AppId);
                    if (userDevice != null)
                    {
                        _context.Entry(userDevice).State = EntityState.Modified;
                        userDevice.LastLogin             = DateTime.UtcNow;
                        // save tp db
                        await _context.SaveChangesAsync();
                    }
                }
                // check exist UseExternalSignIns
                if (!_context.ExternalSignIns.Any(ue => ue.UserId == userCreate.Id && ue.TypeLogin == model.TypeLogin))
                {
                    var newUSERExternalSignIn = new ExternalSignIn
                    {
                        Id            = Guid.NewGuid().ToString(),
                        IsVerified    = (int)TypeVerified.Verified,
                        LastLogin     = DateTime.UtcNow,
                        TimeLifeToken = 3600,
                        TokenLogin    = model.TokenLogin,
                        TypeLogin     = model.TypeLogin,
                        UserId        = userExist.Id
                    };
                    userCreate.UseExternalSignIns.Add(newUSERExternalSignIn);
                }
                else
                {
                    // update To UserExternalSignIns
                    var userExternalSignIn = _context.ExternalSignIns.FirstOrDefault(ue => ue.UserId == userExist.Id && ue.TypeLogin == model.TypeLogin);
                    if (userExternalSignIn != null)
                    {
                        _context.Entry(userExternalSignIn).State = EntityState.Modified;
                        userExternalSignIn.LastLogin             = DateTime.UtcNow;
                        // save tp db
                        await _context.SaveChangesAsync();
                    }
                }

                // save to db
                await _context.SaveChangesAsync();
            }
            else
            {
                // if not exist then create user
                userCreate.Id          = Guid.NewGuid().ToString();
                userCreate.FirstName   = model.FirstName;
                userCreate.LastLogin   = DateTime.UtcNow;
                userCreate.LastName    = model.LastName;
                userCreate.Email       = model.Email;
                userCreate.UserName    = model.Email;
                userCreate.PhoneNumber = model.PhoneNumber;

                var userDevice = new UserDevice
                {
                    Id            = Guid.NewGuid().ToString(),
                    CodeDevice    = model.AppId,
                    CurrentUserId = userCreate.Id,
                    IsVerified    = (int)TypeVerified.Verified,
                    LastLogin     = DateTime.UtcNow,
                    TimeCode      = 20,
                    VerifiedCode  = (int)(DateTime.Now.Ticks >> 23)
                };
                // Save to UserDevices
                userCreate.UserDevices.Add(userDevice);

                var externalSign = new ExternalSignIn
                {
                    Id            = Guid.NewGuid().ToString(),
                    IsVerified    = (int)TypeVerified.Verified,
                    LastLogin     = DateTime.UtcNow,
                    TimeLifeToken = 3600,
                    TokenLogin    = model.TokenLogin,
                    TypeLogin     = model.TypeLogin,
                    UserId        = userCreate.Id
                };
                // Save to ExternalSignIns
                userCreate.UseExternalSignIns.Add(externalSign);

                // Save to UserToRole
                var userToRole = new UserToRole();
                userToRole.Role = roleCustomerUser;
                userToRole.User = userCreate;
                roleCustomerUser.UserToRoles.Add(userToRole);
                _context.Users.Add(userCreate);

                // Save All To Database
                await _context.SaveChangesAsync();
            }
            // create token
            string currentUserId = Guid.NewGuid().ToString();
            var    userLogined   = CreateToken(userCreate, currentUserId);

            // save to login
            await SaveToUserLoginAsync(userCreate, userLogined, currentUserId);

            // save to login
            // return
            return(userLogined);
        }
Esempio n. 29
0
        public async Task <IActionResult> RegistrationUser([FromBody] RegistrationUserDTO model, string storeId)
        {
            _logger.Log(LogLevel.Information, "call registration/{@storeId}", storeId);
            await CheckIsSignoutedAsync();

            string messager = string.Empty;

            if (ModelState.IsValid)
            {
                // check store exist and open
                Store store = await _context.Stores.FindAsync(storeId);

                if (store == null)
                {
                    messager = "Không tìm thấy cửa hàng hoặc cửa hàng đã đóng.";
                    _logger.Log(LogLevel.Information, messager);
                    throw new ApiException(messager, (int)HttpStatusCode.BadRequest);
                }

                // get role
                Role role = await _context.Roles.FindAsync(storeId);

                if (role == null)
                {
                    messager = "Không tìm thấy role.";
                    _logger.Log(LogLevel.Information, messager);
                    throw new ApiException(messager, (int)HttpStatusCode.BadRequest);
                }

                // init user
                var  hashPass = Helpers.SercurityHelper.GenerateSaltedHash(model.Password);
                User user     = new User
                {
                    Id           = Guid.NewGuid().ToString(),
                    Age          = model.Age,
                    Email        = model.Email,
                    FirstName    = model.FirstName,
                    LastName     = model.LastName,
                    PhoneNumber  = model.PhoneNumber,
                    UserName     = model.Username,
                    StoreId      = store.Id,
                    Gender       = model.Gender,
                    IsActived    = (int)TypeVerified.Verified,
                    HashPassword = hashPass.Hash,
                    SaltPassword = hashPass.Salt
                };

                // Add user to Role
                UserToRole userToRole = new UserToRole();

                userToRole.Role = role;
                userToRole.User = user;

                role.UserToRoles.Add(userToRole);

                // save user create to database
                try
                {
                    _context.Roles.Add(role);
                    _context.Users.Add(user);
                    await _context.SaveChangesAsync();

                    messager = $"Đã khởi tạo nhân viên {role.Desc}: {user.FirstName} {user.LastName} cho cửa hàng của bạn.";
                }
                catch (Exception ex)
                {
                    _logger.Log(LogLevel.Warning, $"Log when RegistrationUser {ex.Message}");
#if !DEBUG
                    throw new ApiException($"Có lỗi xảy ra khi đăng ký {user.FirstName}", (int)HttpStatusCode.BadRequest);
#else
                    throw new ApiException(ex, (int)HttpStatusCode.BadRequest);
#endif
                }
            }

            _logger.Log(LogLevel.Information, messager);
            return(Ok(new { data = messager }));
        }
        public static void Initialize(MonitoringSystemContext context)
        {
            if (!context.Database.EnsureCreated())
            {
                context.Database.Migrate();
            }

            // Look for any BasicParameters.
            if (context.BasicParameters.Any())
            {
                return;   // DB has been seeded
            }

            var basicParameters = new BasicParameter[]
            {
                new BasicParameter {
                    SPNNameRu = "Время включения системы подачи газа", DataSource = "Отсутствует в J1339! (но есть Engine Total Hours of Gaseous Fuel Operation"
                },
                new BasicParameter {
                    Acronym = "GFC", SPNName = "Trip Gaseous", SPNNameRu = "Расход газа", DataSource = "CAN-шина, при наличии расходомера газа. Иначе-вычисляется через давление и проходное сечение форсунки впрыска газа"
                },
                new BasicParameter {
                    Acronym = "GP", SPNName = "Gas Pressure", SPNNameRu = "Давление газа", DataSource = "Внешний датчик давления"
                },
                new BasicParameter {
                    Acronym = "GFC", SPNName = "Trip Fuel", SPNNameRu = "Расход дизельного топлива", DataSource = "CAN шина, или датчик расхода"
                },
                new BasicParameter {
                    Acronym = "VD", SPNName = "Total Vehicle Distance", SPNNameRu = "Пробег автомобиля (пройденный путь)", DataSource = "CAN -шина"
                },
                new BasicParameter {
                    Acronym = "WBVS", SPNName = "Wheel-Based Vehicle Speed", SPNNameRu = "Скорость движения", DataSource = "CAN -шина"
                },
                new BasicParameter {
                    Acronym = "EEC1", SPNName = "Engine Speed", SPNNameRu = "Обороты двигателя", DataSource = "CAN -шина"
                },
                new BasicParameter {
                    Acronym = "ECT", SPNName = "Engine Coolant Temperature", SPNNameRu = "Температура двигателя", DataSource = "CAN -шина"
                },
                new BasicParameter {
                    Acronym = "TE", SPNName = "Exhaust Temperature", SPNNameRu = "Температура выхлопных газов", DataSource = "Дополнительный датчик на выхлопной  трубе"
                },
            };

            foreach (BasicParameter bp in basicParameters)
            {
                context.BasicParameters.Add(bp);
            }
            context.SaveChanges();



            /*if (context.Vehicles.Any())
             * {
             *  return;   // DB has been seeded
             * }*/


            var vehicles = new Vehicle[]
            {
                new Vehicle {
                    Mark = "BMW", ModelType = "E540", СarryingСapacity = 2000, YearIssue = 1998, UsefulVolume = 430, VehicleType = "ГР", OverallDimensions = "20x30x40"
                },
                new Vehicle {
                    Mark = "Mersedes", ModelType = "S230", СarryingСapacity = 4000, YearIssue = 1996, UsefulVolume = 930, VehicleType = "ГР", OverallDimensions = "50x70x60"
                },
            };

            foreach (Vehicle vh in vehicles)
            {
                context.Vehicles.Add(vh);
            }
            context.SaveChanges();

            // Table
            var vehiclegroups = new VehicleGroup[]
            {
                new VehicleGroup {
                    VehicleGroupName = "TestVehicleGroup1"
                },
                new VehicleGroup {
                    VehicleGroupName = "TestVehicleGroup2"
                },
                new VehicleGroup {
                    VehicleGroupName = "TestVehicleGroup3"
                },
            };

            foreach (VehicleGroup vhg in vehiclegroups)
            {
                context.VehicleGroups.Add(vhg);
            }
            context.SaveChanges();

            // Table
            var vehicletovehiclegroups = new VehicleToVehicleGroup[]
            {
                new VehicleToVehicleGroup {
                    VehicleGroupID = 2, VehicleID = 1
                },
                new VehicleToVehicleGroup {
                    VehicleGroupID = 2, VehicleID = 2
                },
                new VehicleToVehicleGroup {
                    VehicleGroupID = 3, VehicleID = 1
                },
            };

            foreach (VehicleToVehicleGroup vvg in vehicletovehiclegroups)
            {
                context.VehicleToVehicleGroups.Add(vvg);
            }
            context.SaveChanges();


            // Table
            var parameters = new Parameter[]
            {
                new Parameter {
                    VehicleID = 1, BasicParameterID = 2, BasicParameterValue = 112, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 54)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 3, BasicParameterValue = 113, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 54)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 4, BasicParameterValue = 114, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 54)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 5, BasicParameterValue = 115, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 54)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 6, BasicParameterValue = 116, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 54)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 7, BasicParameterValue = 117, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 54)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 8, BasicParameterValue = 118, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 54)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 9, BasicParameterValue = 119, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 54)
                },

                new Parameter {
                    VehicleID = 1, BasicParameterID = 2, BasicParameterValue = 122, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 56)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 3, BasicParameterValue = 123, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 56)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 4, BasicParameterValue = 124, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 56)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 5, BasicParameterValue = 125, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 56)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 6, BasicParameterValue = 126, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 56)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 7, BasicParameterValue = 127, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 56)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 8, BasicParameterValue = 128, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 56)
                },
                new Parameter {
                    VehicleID = 1, BasicParameterID = 9, BasicParameterValue = 129, BasicParameterTimeValue = new DateTime(2004, 10, 19, 10, 23, 56)
                },
            };

            foreach (Parameter p in parameters)
            {
                context.Parameters.Add(p);
            }
            context.SaveChanges();


            // Table
            var routes = new Route[]
            {
                new Route {
                    VehicleID = 1, CoordinateLatitude = 60.001, CoordinateLongitude = 30.001
                },
                new Route {
                    VehicleID = 1, CoordinateLatitude = 60.002, CoordinateLongitude = 30.002
                },
                new Route {
                    VehicleID = 1, CoordinateLatitude = 60.003, CoordinateLongitude = 30.003
                },
                new Route {
                    VehicleID = 1, CoordinateLatitude = 60.004, CoordinateLongitude = 30.004
                },
                new Route {
                    VehicleID = 1, CoordinateLatitude = 60.005, CoordinateLongitude = 30.005
                },
                new Route {
                    VehicleID = 2, CoordinateLatitude = 60.101, CoordinateLongitude = 30.101
                },
            };

            foreach (Route r in routes)
            {
                context.Routes.Add(r);
            }
            context.SaveChanges();


            // Table
            var users = new User[]
            {
                new User {
                    UserLogin = "******", UserPassword = "******", UserName = "******", UserSurname = "Шайтан", UserPhone = "7911", UserRole = 1
                },
                new User {
                    UserLogin = "******", UserPassword = "******", UserName = "******", UserSurname = "Иванов", UserPhone = "7921", UserRole = 2
                },
            };

            foreach (User u in users)
            {
                context.Users.Add(u);
            }
            context.SaveChanges();


            // Table
            var roles = new Role[]
            {
                new Role {
                    RoleName = "ADMIN"
                },
                new Role {
                    RoleName = "USER"
                },
            };

            foreach (Role r in roles)
            {
                context.Roles.Add(r);
            }
            context.SaveChanges();


            // Table
            var usertoroles = new UserToRole[]
            {
                new UserToRole {
                    UserID = 1, RoleID = 1
                },
                new UserToRole {
                    UserID = 2, RoleID = 2
                },
            };

            foreach (UserToRole ur in usertoroles)
            {
                context.UserToRoles.Add(ur);
            }
            context.SaveChanges();
        }