예제 #1
0
        public async Task <SaveUsersResponse> UpdateAsync(string id, UpdateUsersResource resource)
        {
            var Users = _mapper.Map <UpdateUsersResource, UsersModels>(resource);

            var existingUsers = await _UsersRepository.ReadOneAsync(id);

            if (existingUsers == null)
            {
                return(new SaveUsersResponse("Category not found."));
            }

            //判斷是否要更改密碼
            if (resource.UpdatePasswordChecked == true)
            {
                //將密碼加密
                MD5HashUtils MD5         = new MD5HashUtils();
                string       Md5Password = MD5.MD5Hash(Users.password);

                existingUsers.password = Md5Password;
            }
            else
            {
                existingUsers.password = existingUsers.password;
            }

            //將要儲存要更新的值
            existingUsers.user_name        = Users.user_name;
            existingUsers.role_id          = Users.role_id;
            existingUsers.phone            = Users.phone;
            existingUsers.email            = Users.email;
            existingUsers.gender           = Users.gender;
            existingUsers.due_date         = Users.due_date;
            existingUsers.resignation_date = Users.resignation_date;

            try
            {
                await _UsersRepository.UpdateAsync(existingUsers);

                return(new SaveUsersResponse(existingUsers));
            }
            catch (Exception ex)
            {
                // Do some logging stuff
                return(new SaveUsersResponse($"An error occurred when updating the category: {ex.Message}"));
            }
        }
 public UsersSeeder(CustomContext context)
 {
     if (!context.users.Any())
     {
         Task.Run(async() =>
         {
             Guid UUID          = Guid.NewGuid();
             MD5HashUtils MD5   = new MD5HashUtils();
             string Md5Password = MD5.MD5Hash("admin");
             await context.users.AddAsync(new UsersModels()
             {
                 user_id = UUID.ToString(), account_number = "admin", password = Md5Password, user_name = "管理者", role_id = 1, phone = null, email = null, gender = "男", due_date = DateTime.Now, resignation_date = null, create_date = DateTime.Now
             });
             await context.SaveChangesAsync();
         }).Wait();
     }
 }
예제 #3
0
        public async Task <SaveUsersResponse> CreateAsync(InsertUsersResource resource)
        {
            try
            {
                var Users = _mapper.Map <InsertUsersResource, UsersModels>(resource);
                //生成GUID
                Guid UUID = Guid.NewGuid();
                while (await _UsersRepository.ReadOneAsync(UUID.ToString()) != null)
                {
                    UUID = Guid.NewGuid();
                }

                //將密碼加密
                MD5HashUtils MD5         = new MD5HashUtils();
                string       Md5Password = MD5.MD5Hash(Users.password);

                var NewUsers = new UsersModels
                {
                    user_id        = UUID.ToString(),
                    account_number = Users.account_number,
                    password       = Md5Password,
                    user_name      = Users.user_name,
                    role_id        = Users.role_id,
                    phone          = Users.phone,
                    email          = Users.email,
                    gender         = Users.gender,
                    due_date       = Users.due_date,
                    create_date    = DateTime.Now
                };

                //將處理完的ID值儲存起來,並將其傳送至Repository儲存置資料庫
                await _UsersRepository.CreateAsync(NewUsers);

                return(new SaveUsersResponse(NewUsers));
            }
            catch (Exception ex)
            {
                // Do some logging stuff
                return(new SaveUsersResponse($"An error occurred when saving the category: {ex.Message}"));
            }
        }
        public async Task <LoginOutputResource> LoginAsync(LoginResource resource)
        {
            LoginOutputResource Result = new LoginOutputResource();

            //將密碼加密
            MD5HashUtils MD5         = new MD5HashUtils();
            string       Md5Password = MD5.MD5Hash(resource.password);

            //比對這組帳號密碼是否有人存在
            var Users = await _UsersRepository.ReadOneAsync(resource.account_number, Md5Password);

            if (Users != null)
            {
                //撈取該帳號的權限
                var RolePermissions = await _RolePermissionsRepository.ReadAllAsync(Users.roles.role);

                var FunctionNamesCount = (from r in RolePermissions
                                          where (r.role_id == Users.role_id)
                                          select new { r.permissions.function_names }
                                          ).Distinct().ToList();

                Result.user_id   = Users.user_id;
                Result.user_name = Users.user_name;
                Result.role      = Users.roles.role;

                Result.Permissions = new PermissionsResource[FunctionNamesCount.Count()];
                int count = 0;

                foreach (var f in FunctionNamesCount)
                {
                    Result.Permissions[count] = new PermissionsResource();
                    Result.Permissions[count].function_names = new FunctionNamesResource();
                    Result.Permissions[count].actions        = new List <ActionsResource>();

                    Result.Permissions[count].function_names.function_name_id      = f.function_names.function_name_id;
                    Result.Permissions[count].function_names.function_name         = f.function_names.function_name;
                    Result.Permissions[count].function_names.function_name_chinese = f.function_names.function_name_chinese;

                    var ActionsList = (from r in RolePermissions
                                       where (r.role_id == Users.role_id && r.permissions.function_names.function_name == f.function_names.function_name.ToString())
                                       select new { r.permissions.actions }
                                       ).Distinct().ToList();

                    foreach (var a in ActionsList)
                    {
                        Result.Permissions[count].actions.Add(new ActionsResource()
                        {
                            action_id = a.actions.action_id,
                            action    = a.actions.action
                        });
                    }


                    count++;
                }

                var userClaims = new ClaimsIdentity(new[] {
                    //使用者識別碼
                    new Claim(JwtRegisteredClaimNames.NameId, resource.account_number),
                    //JWT的唯一ID,防止JWT重複使用
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim("Role", Users.roles.role)
                });

                // 取得對稱式加密 JWT Signature 的金鑰
                // 這部分是選用,但此範例在 Startup.cs 中有設定 ValidateIssuerSign ingKey = true 所以這裡必填
                var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
                //建立 JWT TokenHandler 以及用於描述 JWT 的 TokenDescriptor
                var tokenHandler = new JwtSecurityTokenHandler();


                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Issuer   = _config["Jwt:Issuer"],
                    Audience = _config["Jwt:Issuer"],
                    Subject  = userClaims,
                    // Expires = DateTime.Now.AddMinutes(30), //到期時間
                    SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
                };


                // 產出所需要的 JWT Token 物件
                var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                // 產出序列化的 JWT Token 字串
                var serializeToken = tokenHandler.WriteToken(securityToken);

                Result.JWTKey = serializeToken;
            }

            return(Result);
        }