public async Task <IActionResult> EditUserAsync(UserModelDto model)
        {
            try
            {
                ApplicationUser user = await this.userManager
                                       .FindByIdAsync(model.Id);

                user.Email       = model.Email;
                user.UserName    = model.UserName;
                user.PhoneNumber = model.PhoneNumber;

                await this.userManager.UpdateAsync(user);

                return(this.RedirectToAction(nameof(GetAllUsers)));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(this.Content(ex.Message));
            }
            catch (DbUpdateException ex)
            {
                return(this.Content(ex.Message));
            }
            catch (Exception ex)
            {
                return(this.Content(ex.Message));
            }
        }
Esempio n. 2
0
        public static async Task <HttpResponseMessage> NewUser(UserModelDto model)
        {
            Configuration.Setup();

            var url = $"{Configuration.Instance.BaseURL}api/auth/newuser";

            var filter = new HttpBaseProtocolFilter();

            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);

            var client = new HttpClient(filter);

            client.DefaultRequestHeaders.Accept.Add(new Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue("application/json"));
            var request = new HttpRequestMessage(HttpMethod.Post, new Uri(url));

            request.Content = new HttpStringContent(JsonConvert.SerializeObject(model),
                                                    Windows.Storage.Streams.UnicodeEncoding.Utf8,
                                                    "application/json");

            HttpResponseMessage result = new HttpResponseMessage();

            try
            {
                result = await client.SendRequestAsync(request);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"An exception occured on Authentication: {ex}");
            }
            return(result);
        }
        //Get Access Token
        public async Task <UserModelDto> GetAccessToken(string token, string oauthVerifier)
        {
            var client         = _clientFactory.CreateClient("twitter");
            var consumerKey    = _twitterConfig.Value.AppId;
            var consumerSecret = _twitterConfig.Value.AppSecret;

            var accessTokenResponse = new UserModelDto();

            client.DefaultRequestHeaders.Accept.Clear();

            var oauthClient = new OAuthRequest
            {
                Method          = "POST",
                Type            = OAuthRequestType.AccessToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = consumerKey,
                ConsumerSecret  = consumerSecret,
                RequestUrl      = "https://api.twitter.com/oauth/access_token",
                Token           = token,
                Version         = "1.0a",
                Realm           = "twitter.com"
            };

            string auth = oauthClient.GetAuthorizationHeader();

            client.DefaultRequestHeaders.Add("Authorization", auth);


            try
            {
                var content = new FormUrlEncodedContent(new[] {
                    new KeyValuePair <string, string>("oauth_verifier", oauthVerifier)
                });

                using (var response = await client.PostAsync(oauthClient.RequestUrl, content))
                {
                    response.EnsureSuccessStatusCode();

                    //twiiter responds with a string concatenated by &
                    var responseString = response.Content.ReadAsStringAsync()
                                         .Result.Split("&");

                    //split by = to get acual values
                    accessTokenResponse = new UserModelDto
                    {
                        Token       = responseString[0].Split("=")[1],
                        TokenSecret = responseString[1].Split("=")[1],
                        UserId      = responseString[2].Split("=")[1],
                        Username    = responseString[3].Split("=")[1]
                    };
                }
            }
            catch (Exception ex)
            {
            }

            return(accessTokenResponse);
        }
Esempio n. 4
0
 public async Task <IActionResult> Login(UserModelDto input)
 {
     if (ModelState.IsValid)
     {
         var dd = await _loginService.VerificationUserLogin(input);
     }
     //return BadRequest("没有该用户");
     return(RedirectToAction("Home", "Index"));
 }
 public async Task <HeaderResult <string> > GetSignatureToken([FromBody] UserModelDto input)
 {
     if (ModelState.IsValid)
     {
         return(await _loginService.VerificationUserLogin(input));
     }
     return(new HeaderResult <string>
     {
         Message = "错误",
         IsSucceed = false
     });
 }
Esempio n. 6
0
        public async Task <HeaderResult <string> > GetSignatureToken([FromBody] UserModelDto input)
        {
            if (ModelState.IsValid)
            {
                return(await _loginService.VerificationUserLogin(input));
            }

            //if (ModelState.IsValid) //判断是否合法
            //{
            //    JwtClaimConfiguration configuration = new JwtClaimConfiguration();
            //    var claim = new Claim[]
            //    {
            //        new Claim(ClaimTypes.Name, "lbb"),
            //        new Claim(ClaimTypes.Role, "admin"),
            //        new Claim(configuration.UserId, Guid.NewGuid().ToString()),
            //        new Claim(configuration.UserName, "李锋")

            //    };

            //    //对称秘钥
            //    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
            //    //签名证书(秘钥,加密算法)
            //    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //    //生成token  [注意]需要nuget添加Microsoft.AspNetCore.Authentication.JwtBearer包,并引用System.IdentityModel.Tokens.Jwt命名空间
            //    var token = new JwtSecurityToken(_jwtSettings.Issuer, _jwtSettings.Audience, claim, DateTime.Now,
            //        DateTime.Now.AddMinutes(30), creds);
            //    var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
            //    var jwtSecurityToken = new JwtSecurityTokenHandler().ReadJwtToken(jwtToken);


            //    List<UserDto> u=new List<UserDto>();
            //    var cacheRedis = RedisHelper.RedisDatabase();

            //    cacheRedis.StringSet("li", 11);
            //    var c = cacheRedis.StringGet("li");
            //    return new HeaderResult<string>
            //    {
            //        Result = jwtToken,
            //        IsSucceed = true
            //    };


            //}
            return(new HeaderResult <string>
            {
                Message = "错误",
                IsSucceed = false
            });
        }
Esempio n. 7
0
        public Result <ApplicationUser> UserByEmail([FromBody] UserModelDto input)
        {
            Result <ApplicationUser> response = new Result <ApplicationUser>();
            ApplicationUser          user;

            try
            {
                user = _context.Users.Select(user => new ApplicationUser
                {
                    FirstName      = user.FirstName,
                    LastName       = user.LastName,
                    UserName       = user.UserName,
                    Email          = user.Email,
                    PhoneNumber    = user.PhoneNumber,
                    EmailConfirmed = user.EmailConfirmed,
                    CreatedAt      = user.CreatedAt
                }).Where(u => u.Email == input.Email).FirstOrDefault();

                if (user != null)
                {
                    response.IsSuccess = true;
                    response.Data      = user;
                    _logger.LogInformation(1, "Se envia la informacion del usuario " + input.Email);
                }
                else
                {
                    response.IsSuccess = false;
                    response.Message   = "Usuario no encontrado en la base de datos";
                    response.Data      = null;
                    _logger.LogInformation("EUsuario no encontrado" + input.Email);
                }
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.Message   = "Error en el Servidor " + ex.Message;
                response.Data      = null;
                _logger.LogError("Error inesperado en el servidor" + ex.Message);
            }

            return(response);
        }
Esempio n. 8
0
        public async Task <UserModelDto> RetrieveUserByUserId(long Id)
        {
            var model = await _userProfileDbContext.UserModel.FirstOrDefaultAsync(x => x.Id == Id);

            var dtoUser = new UserModelDto();

            dtoUser = new UserModelDto
            {
                Id           = model.Id,
                Firstname    = model.Firstname,
                Lastname     = model.Lastname,
                EmailAddress = model.EmailAddress,
                DateCreated  = model.DateCreated,
                PhoneNo      = model.PhoneNo,
                IsActivated  = model.IsActivated,
                IsActive     = model.IsActive,
                ReferredBy   = model.ReferredBy
            };
            return(dtoUser);
        }
Esempio n. 9
0
        public async Task <IActionResult> UpdateAsync([FromRoute] string userId, UserModelDto user)
        {
            var result = await Mediator.Send(new UpdateUserCommand(userId, user, UserName));

            return(Ok(result.Data));
        }
Esempio n. 10
0
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task <HeaderResult <string> > VerificationUserLogin(UserModelDto input)
        {
            var result = await _loginDomainService.VerificationUserLogin(input.Username, input.Password);

            return(result);
        }
Esempio n. 11
0
        private async void Submit_Click(object sender, RoutedEventArgs e)
        {
            if (Name.Text.Equals(""))
            {
                Name.PlaceholderForeground = new SolidColorBrush(Colors.Red);
                NameNotFilled.Visibility   = Visibility.Visible;
            }
            else if (UserId.Text.Length < 5)
            {
                NameNotFilled.Visibility = Visibility.Collapsed;

                UserId.PlaceholderForeground     = new SolidColorBrush(Colors.Red);
                UsernameNotLongEnough.Visibility = Visibility.Visible;
            }
            //Also check for email being real
            else if (Email.Text.Equals(""))
            {
                UsernameNotLongEnough.Visibility = Visibility.Collapsed;

                Email.PlaceholderForeground = new SolidColorBrush(Colors.Red);
                EmailNotEmail.Visibility    = Visibility.Visible;
            }
            else if (Password.Password.Length < 8)
            {
                EmailNotEmail.Visibility = Visibility.Collapsed;

                Password.Password = "";
                PasswordNotLongEnough.Visibility = Visibility.Visible;
            }
            else if (!(Password.Password == ConfirmPassword.Password))
            {
                PasswordNotLongEnough.Visibility = Visibility.Collapsed;

                ConfirmPassword.Password   = "";
                PasswordNotSame.Visibility = Visibility.Visible;
            }
            else
            {
                PasswordNotLongEnough.Visibility = Visibility.Collapsed;
                EmailNotEmail.Visibility         = Visibility.Collapsed;
                UsernameNotLongEnough.Visibility = Visibility.Collapsed;
                NameNotFilled.Visibility         = Visibility.Collapsed;
                PasswordNotSame.Visibility       = Visibility.Collapsed;

                var x = new UserModelDto()
                {
                    Email    = Email.Text,
                    Name     = Name.Text,
                    Password = Password.Password,
                    UserName = UserId.Text,
                    Credit   = 0
                };
                try
                {
                    var response = await Authentication.NewUser(x);

                    if (response.StatusCode == Windows.Web.Http.HttpStatusCode.Created)
                    {
                        FailedMessage.Visibility = Visibility.Collapsed;
                        Frame.Navigate(typeof(MainPage), x);
                    }
                    else
                    {
                        FailedMessage.Visibility = Visibility.Visible;
                        FailedMessage.Text       = $"There was a problem creating the user: {response.ReasonPhrase}";
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"An exception occurred on creating a new user: {ex}");
                }
                return;
            }
        }