public async void TestCreateUser()
        {
            var now  = DateTimeOffset.UtcNow;
            var body = new UserNewDto()
            {
                UserName = "******", Password = "******"
            };
            var response = await this.client.PostAsJsonAsync("/api/users", body);

            var responseString = await response.Content.ReadAsStringAsync();

            Assert.True(response.IsSuccessStatusCode, responseString);

            var json = JsonConvert.DeserializeObject <UserDto>(responseString);

            Assert.True(json.Id > 0);
            Assert.Equal(body.UserName, json.UserName);
            Assert.True(json.LastLogin > now);
            Assert.True(json.CreatedAt > now);
            Assert.True(json.UpdatedAt > now);

            var dbuser = this.factory.CreateDbContext().Users.Find(json.Id);

            Assert.NotNull(dbuser);
            Assert.Equal(body.UserName, dbuser.UserName);
            Assert.NotNull(dbuser.PasswordHash);
            Assert.Equal(json.LastLogin, dbuser.LastLogin);
            Assert.Equal(json.CreatedAt, dbuser.CreatedAt);
            Assert.Equal(json.UpdatedAt, dbuser.UpdatedAt);

            // TODO: パスワードハッシュが正しいものであるかも確認する
            // TODO: 新規ユーザーで認証されたことも確認する
        }
        /// <summary>
        /// 新規ユーザーのHTTPクライアントを生成する。
        /// </summary>
        /// <param name="name">新規ユーザーの名前。未指定時はランダム生成。</param>
        /// <param name="password">新規ユーザーのパスワード。</param>
        /// <returns>HTTPクライアントと新規ユーザーのID。</returns>
        public (HttpClient, int) CreateNewUserClient(string name = null, string password = "******")
        {
            // 名前が被るとエラーになるので、未指定時は動的に設定
            if (string.IsNullOrEmpty(name))
            {
                name = "NEW_USER_" + Guid.NewGuid();
            }

            // 指定された条件でユーザーを作成して、そのセッションを持つHTTPクライアントを返す
            var client = this.CreateClient();
            var body   = new UserNewDto()
            {
                UserName = name, Password = password
            };
            var response       = client.PostAsJsonAsync("/api/users", body).Result;
            var responseString = response.Content.ReadAsStringAsync().Result;

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception(responseString);
            }

            using (var doc = JsonDocument.Parse(responseString))
            {
                return(client, doc.RootElement.GetProperty("id").GetInt32());
            }
        }
예제 #3
0
        /// <summary>
        /// 添加新用户
        /// </summary>
        /// <remarks>
        /// 注意,Access token 中必须包含 iamApi 这个 scope
        /// </remarks>
        /// <param name="model">用于新增用户的数据模型</param>
        /// <param name="accessToken">当前登陆用户的 access token,默认不需要提供,如果需要使用其他 access token 才需要提供</param>
        /// <returns></returns>
        public async Task <ApiResult <UserNewRespDto> > CreateUserAsync(UserNewDto model, string accessToken = null)
        {
            if (model == null)
            {
                return(new ApiResult <UserNewRespDto>
                {
                    IsSucceed = false,
                    Message = "model 参数为空"
                });
            }

            if (accessToken == null)
            {
                accessToken = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");

                if (accessToken == null)
                {
                    return(new ApiResult <UserNewRespDto>
                    {
                        IsSucceed = false,
                        Message = "Access Token 为空"
                    });
                }
            }

            _httpClient.SetBearerToken(accessToken);

            int statusCode = -1;

            try
            {
                StringContent body = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
                var           resp = await _httpClient.PostAsync($"{_options.Authority.TrimEnd('/')}/admin/api/users", body);

                statusCode = (int)resp.StatusCode;

                var result = await resp.WhenResponseSuccess(resp =>
                {
                    return(JsonConvert.DeserializeObject <UserNewRespDto>(resp));
                });

                return(new ApiResult <UserNewRespDto>
                {
                    IsSucceed = true,
                    StatusCode = (int)resp.StatusCode,
                    Data = result
                });
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, $"调用 IamApi 的 {nameof(CreateUserAsync)} 失败");
                return(new ApiResult <UserNewRespDto>
                {
                    IsSucceed = false,
                    StatusCode = statusCode,
                    Message = ex.Message
                });
            }
        }
예제 #4
0
        public async Task <ActionResult <UserDto> > CreateUser(UserNewDto body)
        {
            // ユーザーを登録し、ログイン中の状態にする
            var user = await this.userService.CreateUser(body);

            await this.signInManager.SignInAsync(user, false);

            return(this.CreatedAtAction(nameof(this.GetUser), new { id = user.Id }, this.mapper.Map <UserDto>(user)));
        }
예제 #5
0
        /// <summary>
        /// ユーザーを新規登録する。
        /// </summary>
        /// <param name="param">ユーザー登録情報。</param>
        /// <returns>登録したユーザー。</returns>
        /// <exception cref="BadRequestException">入力値が不正な場合。</exception>
        public async Task <User> CreateUser(UserNewDto param)
        {
            using (var transaction = this.unitOfWork.BeginTransaction())
            {
                var user = await this.userRepository.CreateBy(param.UserName, param.Password);

                transaction.Commit();
                return(user);
            }
        }
예제 #6
0
        public async Task <string> CreateAsync(UserNewDto model)
        {
            var existed = await _userMgr.FindByNameAsync(model.Username);

            if (existed != null)
            {
                throw new IamException(HttpStatusCode.BadRequest, "该用户名已经被使用!");
            }

            model.JobNo = model.JobNo?.Trim();

            await ValidateUserAsync(model.JobNo, model.Phone);

            var user = new ApplicationUser(model.Username, model.JobNo, model.Email, model.HomeAddress, model.IdCard, model.Phone, model.FirstName, model.LastName, model.Nickname, model.Position, model.Gender, model.IsActive, model.Motto, model.Avatar, model.Cover, model.Github, model.Twitter, model.SinaWeibo, model.Note);

            // 注册自动激活,便于游客使用
            user.Switch(true);

            IdentityResult result = await _userMgr.CreateAsync(user, model.Password ?? "111111");

            if (result.Succeeded)
            {
                if (!String.IsNullOrWhiteSpace(model.OrgIds))
                {
                    var orgIdColl = model.OrgIds.Split(",").Select(itm => itm.Trim());

                    foreach (var org in orgIdColl)
                    {
                        user.AddOrganizations(org);
                    }
                }

                await _userMgr.UpdateAsync(user);

                if (!String.IsNullOrWhiteSpace(model.JobNo))
                {
                    await _userMgr.AddClaimsAsync(user, new[]
                    {
                        new Claim(Constants.CLAIM_TYPES_SALER, model.JobNo)
                    });
                }
                return(user.Id);
            }

            throw new IamException(HttpStatusCode.BadRequest, String.Join(";", result.Errors.Select(err => err.Description)));
        }