public async Task<HttpResponseMessage> Login(LoginViewModel userModel) { var request = HttpContext.Current.Request; var tokenServiceUrl = request.Url.GetLeftPart(UriPartial.Authority) + request.ApplicationPath + "/token"; using (var client = new HttpClient()) { var requestParams = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("grant_type", "password"), new KeyValuePair<string, string>("username", userModel.Email), new KeyValuePair<string, string>("password", userModel.Password) }; var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams); var tokenServiceResponse = await client.PostAsync(tokenServiceUrl, requestParamsFormUrlEncoded); var responseString = await tokenServiceResponse.Content.ReadAsStringAsync(); var responseCode = tokenServiceResponse.StatusCode; var responseMsg = new HttpResponseMessage(responseCode) { Content = new StringContent(responseString, Encoding.UTF8, "application/json") }; if (responseMsg.StatusCode == HttpStatusCode.OK) { var auth = getAuthData(userModel, responseString); return await Ok<AuthModel>(auth).ExecuteAsync(new CancellationToken()); } return responseMsg; } }
public async Task<HttpResponseMessage> Register(RegisterViewModel registerViewModel) { if (!ModelState.IsValid) { return await this.BadRequest(this.ModelState).ExecuteAsync(new CancellationToken()); } Mapper.CreateMap<RegisterViewModel, User>(); var user = Mapper.Map<User>(registerViewModel); user.UserName = registerViewModel.Email; user.Role = "User"; IdentityResult result = userService.Register(user, registerViewModel.Password); IHttpActionResult errorResult = GetErrorResult(result); if (errorResult != null) { return await this.GetErrorResult(result).ExecuteAsync(new CancellationToken()); } var userLoginModel = new LoginViewModel { Email = registerViewModel.Email, Password = registerViewModel.Password }; var resultLogin = await Login(userLoginModel); return resultLogin; }
private AuthModel getAuthData(LoginViewModel userModel, string responseString) { var loginResponse = JsonConvert.DeserializeObject<LoginResponseModel>(responseString); var auth = new AuthModel(); var user = userService.GetUserByEmail(userModel.Email); auth.Token = loginResponse.access_token; auth.Role = user.Role; auth.FirstName = user.FirstName; auth.SecondName = user.SecondName; auth.IsAuthorized = true; return auth; }