예제 #1
0
        public async Task <ActionResult <AppUserModel> > Update(
            [FromRoute] long id,
            [FromBody] AppUserModel model
            )
        {
            try {
                var user = await userMgr.FindByIdAsync(id.ToString());

                if (user == null)
                {
                    return(NotFound());
                }
                var claims = user.UpdateFromUserModel(mapper, model);
                await AddOrReplaceClaims(user, claims);

                var result = await userMgr.UpdateAsync(user);

                if (result.Succeeded)
                {
                    mapper.Map(user, model);
                    return(model);
                }
                return(BadRequest(result.GetErrorsString()));
            }
            catch (Exception ex) {
                logger.LogError(ex, $"Can not update user by id {id} with {model.ToJson()}");
                return(this.InternalServerError(ex));
            }
        }
예제 #2
0
        public async Task <ActionResult <AppUserModel> > Create(
            [FromBody] AppUserModel model
            )
        {
            try {
                var user = await userMgr.FindByNameAsync(model.UserName);

                if (user != null)
                {
                    return(BadRequest($"User with {model.UserName} exists!"));
                }
                user = await userMgr.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    return(BadRequest($"User with {model.Email} exists!"));
                }
                user = new AppUser();
                var claims = user.UpdateFromUserModel(mapper, model);
                var result = await userMgr.CreateAsync(user);

                // add default roles to new created user;
                var defaultRoles = await roleMgr.Roles
                                   .Where(r => r.IsDefault == true)
                                   .Select(r => r.Name)
                                   .ToListAsync();

                await userMgr.AddToRolesAsync(user, defaultRoles);
                await AddOrReplaceClaims(user, claims);

                if (result.Succeeded)
                {
                    mapper.Map(user, model);
                    return(model);
                }
                return(BadRequest(result.GetErrorsString()));
            }
            catch (Exception ex) {
                logger.LogError(ex, $"Can not create user with {model.ToJson()}");
                return(this.InternalServerError(ex));
            }
        }