private AccessTokenViewModel getToken(LoginViewModel model) { var url = Request.RequestUri.Scheme + "://" + Request.RequestUri.Authority; WebRequest myWebRequest = WebRequest.Create(url + "/token"); myWebRequest.ContentType = "application/x-www-form-urlencoded"; myWebRequest.Method = "POST"; var request = string.Format("grant_type=password&userName={0}&Password={1}", HttpUtility.UrlEncode(model.userName), HttpUtility.UrlEncode(model.Password)); byte[] bytes = Encoding.ASCII.GetBytes(request); myWebRequest.ContentLength = bytes.Length; using (Stream outputStream = myWebRequest.GetRequestStream()) { outputStream.Write(bytes, 0, bytes.Length); } using (WebResponse webResponse = myWebRequest.GetResponse()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AccessTokenViewModel)); //Get deserialized object from JSON stream AccessTokenViewModel token = (AccessTokenViewModel)serializer.ReadObject(webResponse.GetResponseStream()); return(token); } }
private async Task <AccessTokenViewModel> GenerateAccessTokenAsync(ApplicationUser user) { string refreshToken = Guid.NewGuid().ToString(); var dtIssued = DateTime.UtcNow; var dtExpired = dtIssued.AddMinutes(SWCmsConstants.AuthConfiguration.AuthCookieExpiration); var dtRefreshTokenExpired = dtIssued.AddDays(SWCmsConstants.AuthConfiguration.AuthCookieExpiration); RefreshTokenViewModel vmRefreshToken = new RefreshTokenViewModel( new RefreshTokens() { Id = refreshToken, Email = user.Email, IssuedUtc = dtIssued, ClientId = SWCmsConstants.AuthConfiguration.Audience, Username = user.UserName, //Subject = SWCmsConstants.AuthConfiguration.Audience, ExpiresUtc = dtRefreshTokenExpired }); var saveRefreshTokenResult = await vmRefreshToken.SaveModelAsync(); AccessTokenViewModel token = new AccessTokenViewModel() { Access_token = await GenerateTokenAsync(user, dtExpired, refreshToken), Refresh_token = saveRefreshTokenResult.Data.Id, Token_type = SWCmsConstants.AuthConfiguration.TokenType, Expires_in = SWCmsConstants.AuthConfiguration.AuthCookieExpiration, //UserData = user, Issued = dtIssued, Expires = dtExpired, }; return(token); }
//[Route("logOut/{refreshTokenId}")] //[HttpGet] //public async Task<RepositoryResponse<bool>> Logout(string refreshTokenId) //{ // var result = await RefreshTokenViewModel.Repository.RemoveListModelAsync(t => t.Id == refreshTokenId); // return result; //} //[Route("logOutOther/{refreshTokenId}")] //[HttpGet] //public async Task<RepositoryResponse<bool>> LogoutOther(string refreshTokenId) //{ // return await RefreshTokenViewModel.LogoutOther(refreshTokenId); //} /* * [HttpGet] * [AllowAnonymous] * public async Task<IActionResult> LoginWith2fa(bool rememberMe, string returnUrl = null) * { * // Ensure the user has gone through the username & password screen first * var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); * * if (user == null) * { * throw new ApplicationException($"Unable to load two-factor authentication user."); * } * * var model = new LoginWith2faViewModel { RememberMe = rememberMe }; * ViewData["ReturnUrl"] = returnUrl; * * return View(model); * } * * [HttpPost] * [AllowAnonymous] * public async Task<IActionResult> LoginWith2fa(LoginWith2faViewModel model, bool rememberMe, string returnUrl = null) * { * if (!ModelState.IsValid) * { * return View(model); * } * * var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); * if (user == null) * { * throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); * } * * var authenticatorCode = model.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty); * * var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, model.RememberMachine); * * if (result.Succeeded) * { * _logger.LogInformation("User with ID {UserId} logged in with 2fa.", user.Id); * return RedirectToLocal(returnUrl); * } * else if (result.IsLockedOut) * { * _logger.LogWarning("User with ID {UserId} account locked out.", user.Id); * return RedirectToAction(nameof(Login)); * } * else * { * _logger.LogWarning("Invalid authenticator code entered for user with ID {UserId}.", user.Id); * ModelState.AddModelError(string.Empty, "Invalid authenticator code."); * return View(); * } * } * * [HttpGet] * [AllowAnonymous] * public async Task<IActionResult> LoginWithRecoveryCode(string returnUrl = null) * { * // Ensure the user has gone through the username & password screen first * var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); * if (user == null) * { * throw new ApplicationException($"Unable to load two-factor authentication user."); * } * * ViewData["ReturnUrl"] = returnUrl; * * return View(); * } * * [HttpPost] * [AllowAnonymous] * public async Task<IActionResult> LoginWithRecoveryCode(LoginWithRecoveryCodeViewModel model, string returnUrl = null) * { * if (!ModelState.IsValid) * { * return View(model); * } * * var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); * if (user == null) * { * throw new ApplicationException($"Unable to load two-factor authentication user."); * } * * var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty); * * var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode); * * if (result.Succeeded) * { * _logger.LogInformation("User with ID {UserId} logged in with a recovery code.", user.Id); * return RedirectToLocal(returnUrl); * } * if (result.IsLockedOut) * { * _logger.LogWarning("User with ID {UserId} account locked out.", user.Id); * return RedirectToAction(nameof(Login)); * } * else * { * _logger.LogWarning("Invalid recovery code entered for user with ID {UserId}", user.Id); * ModelState.AddModelError(string.Empty, "Invalid recovery code entered."); * return View(); * } * } * * [HttpPost] * [AllowAnonymous] * [ValidateAntiForgeryToken] * public IActionResult ExternalLogin(string provider, string returnUrl = null) * { * // Request a redirect to the external login provider. * var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl }); * var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); * return Challenge(properties, provider); * } * * [HttpGet] * [AllowAnonymous] * public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) * { * if (remoteError != null) * { * ErrorMessage = $"Error from external provider: {remoteError}"; * return RedirectToAction(nameof(Login)); * } * var info = await _signInManager.GetExternalLoginInfoAsync(); * if (info == null) * { * return RedirectToAction(nameof(Login)); * } * * // Sign in the user with this external login provider if the user already has a login. * var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true); * if (result.Succeeded) * { * _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider); * return RedirectToLocal(returnUrl); * } * if (result.IsLockedOut) * { * return RedirectToAction(nameof(Login)); // LogOut * } * else * { * // If the user does not have an account, then ask the user to create an account. * ViewData["ReturnUrl"] = returnUrl; * ViewData["LoginProvider"] = info.LoginProvider; * var email = info.Principal.FindFirstValue(ClaimTypes.Email); * return View("ExternalLogin", new ExternalLoginViewModel { Email = email }); * } * } * * [HttpPost] * [AllowAnonymous] * [ValidateAntiForgeryToken] * public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel model, string returnUrl = null) * { * if (ModelState.IsValid) * { * // Get the information about the user from the external login provider * var info = await _signInManager.GetExternalLoginInfoAsync(); * if (info == null) * { * throw new ApplicationException("Error loading external login information during confirmation."); * } * var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; * var result = await _userManager.CreateAsync(user); * if (result.Succeeded) * { * result = await _userManager.AddLoginAsync(user, info); * if (result.Succeeded) * { * await _signInManager.SignInAsync(user, isPersistent: false); * _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); * return RedirectToLocal(returnUrl); * } * } * AddErrors(result); * } * * ViewData["ReturnUrl"] = returnUrl; * return View(nameof(ExternalLogin), model); * } * * [HttpGet] * [AllowAnonymous] * public async Task<IActionResult> ConfirmEmail(string userId, string code) * { * if (userId == null || code == null) * { * return RedirectToAction("Index", "Home"); * } * var user = await _userManager.FindByIdAsync(userId); * if (user == null) * { * throw new ApplicationException($"Unable to load user with ID '{userId}'."); * } * var result = await _userManager.ConfirmEmailAsync(user, code); * return View(result.Succeeded ? "ConfirmEmail" : "Error"); * } * * [HttpGet] * [AllowAnonymous] * public IActionResult ForgotPassword() * { * return View(); * } * * [HttpPost] * [AllowAnonymous] * [ValidateAntiForgeryToken] * public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model) * { * if (ModelState.IsValid) * { * var user = await _userManager.FindByEmailAsync(model.Email); * if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) * { * // Don't reveal that the user does not exist or is not confirmed * return RedirectToAction(nameof(ForgotPasswordConfirmation)); * } * * // For more information on how to enable account confirmation and password reset please * // visit https://go.microsoft.com/fwlink/?LinkID=532713 * var code = await _userManager.GeneratePasswordResetTokenAsync(user); * var callbackUrl = ""; * await _emailSender.SendEmailAsync(model.Email, "Reset Password", * $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>"); * return RedirectToAction(nameof(ForgotPasswordConfirmation)); * } * * // If we got this far, something failed, redisplay form * return View(model); * } * * [HttpGet] * [AllowAnonymous] * public IActionResult ForgotPasswordConfirmation() * { * return View(); * } * * [HttpGet] * [AllowAnonymous] * public IActionResult ResetPassword(string code = null) * { * if (code == null) * { * throw new ApplicationException("A code must be supplied for password reset."); * } * var model = new ResetPasswordViewModel { Code = code }; * return View(model); * } * * [HttpPost] * [AllowAnonymous] * [ValidateAntiForgeryToken] * public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model) * { * if (!ModelState.IsValid) * { * return View(model); * } * var user = await _userManager.FindByEmailAsync(model.Email); * if (user == null) * { * // Don't reveal that the user does not exist * return RedirectToAction(nameof(ResetPasswordConfirmation)); * } * var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); * if (result.Succeeded) * { * return RedirectToAction(nameof(ResetPasswordConfirmation)); * } * AddErrors(result); * return View(); * } * * [HttpGet] * [AllowAnonymous] * public IActionResult ResetPasswordConfirmation() * { * return View(); * } * * [HttpGet] * public IActionResult AccessDenied() * { * return View(); * } * #region Helpers * * private void AddErrors(IdentityResult result) * { * foreach (var error in result.Errors) * { * ModelState.AddModelError(string.Empty, error.Description); * } * } * * private IActionResult RedirectToLocal(string returnUrl) * { * if (Url.IsLocalUrl(returnUrl)) * { * return Redirect(returnUrl); * } * else * { * return RedirectToAction("Index", "Home"); * } * } * #endregion Helpers * * //[AllowAnonymous] * [HttpPost] * public async Task<JsonResult> GenerateToken([FromBody] LoginViewModel model) * { * if (ModelState.IsValid) * { * var user = await _userManager.FindByEmailAsync(model.Email); * * if (user != null) * { * var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false); * if (result.Succeeded) * { * var claims = new[] * { * new Claim(JwtRegisteredClaimNames.Sub, user.Email), * new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), * }; * * var creds = SWCmsConstants.AuthConfiguration.SigningCredentials; * * var token = new JwtSecurityToken(SWCmsConstants.AuthConfiguration.AuthTokenIssuer, * SWCmsConstants.AuthConfiguration.AuthTokenIssuer, * claims, * expires: DateTime.Now.AddMinutes(30), * signingCredentials: creds); * * return new JsonResult(new { token = new JwtSecurityTokenHandler().WriteToken(token) }); * } * } * } * return new JsonResult("Could not create token"); * } * */ private AccessTokenViewModel GenerateAccessToken(ApplicationUser user) { //string refreshToken = Guid.NewGuid().ToString(); //var dtIssued = DateTime.UtcNow; //var dtExpired = dtIssued.AddSeconds(SWCmsConstants.AuthConfiguration.AuthCookieExpiration); //var dtRefreshTokenExpired = dtIssued.AddSeconds(SWCmsConstants.AuthConfiguration.AuthCookieExpiration); //RefreshTokenViewModel vmRefreshToken = new RefreshTokenViewModel( // new RefreshToken() // { // Id = refreshToken, // Email = user.Email, // IssuedUtc = dtIssued, // ClientId = SWCmsConstants.AuthConfiguration.Audience, // //Subject = SWCmsConstants.AuthConfiguration.Audience, // ExpiresUtc = dtRefreshTokenExpired // }); //var saveRefreshTokenResult = await vmRefreshToken.SaveModelAsync(); //if (saveRefreshTokenResult.IsSucceed) //{ // AccessTokenViewModel token = new AccessTokenViewModel() // { // Access_token = GenerateToken(user, dtExpired, refreshToken), // //Refresh_token = vmRefreshToken.Id, // Token_type = SWCmsConstants.AuthConfiguration.TokenType, // Expires_in = SWCmsConstants.AuthConfiguration.AuthCookieExpiration, // //UserData = user, // Issued = dtIssued, // Expires = dtExpired, // }; // return token; //} //else //{ // return null; //} var token = new JwtTokenBuilder() .AddSecurityKey(JwtSecurityKey.Create(SWCmsConstants.JWTSettings.SECRET_KEY)) .AddSubject(user.UserName) .AddIssuer(SWCmsConstants.JWTSettings.ISSUER) .AddAudience(SWCmsConstants.JWTSettings.AUDIENCE) //.AddClaim("MembershipId", "111") .AddExpiry(SWCmsConstants.JWTSettings.EXPIRED_IN) .Build(); AccessTokenViewModel access_token = new AccessTokenViewModel() { Access_token = token.Value, //GenerateToken(user, dtExpired, refreshToken), //Refresh_token = vmRefreshToken.Id, Token_type = SWCmsConstants.AuthConfiguration.TokenType, Expires_in = SWCmsConstants.AuthConfiguration.AuthCookieExpiration, //UserData = user, Issued = DateTime.UtcNow, Expires = token.ValidTo }; return(access_token); }
public AuthData ValidateAuth(IIdentity identity, string userId, string refreshtoken) { AccessTokenViewModel auth = null; string culture = string.Empty; bool isAuth = identity.IsAuthenticated; //Logger.Info("Auth => " + refreshtoken + " || " + userId); if (!isAuth) { var token = GetNewAccessToken(refreshtoken); if (token != null && !string.IsNullOrWhiteSpace(token.AccessToken)) { isAuth = string.IsNullOrWhiteSpace(userId) || userId == token.UserId; var user = FindUserById(token.UserId); auth = new AccessTokenViewModel() { access_token = token.TokenType + " " + token.AccessToken, token_type = token.TokenType, refresh_token = token.RefreshToken ?? string.Empty, expires_in = token.ExpiresIn, client_id = token.ClientId, deviceId = token.DeviceId, issued = token.Issued.ToLocalTime().ToString("dd-MM-yyyy hh:mm:ss"), expires = token.Expires.ToLocalTime().ToString("dd-MM-yyyy hh:mm:ss"), userData = CreateUserViewModel(user, null) }; refreshtoken = token.RefreshToken; culture = auth != null && auth.userData != null ? auth.userData.Culture : CommonHelper.AppConfig(TTXConstants.AppConfig.DefaultCulture.ToString()); } } else { try { var claimsIdentity = identity as ClaimsIdentity; culture = claimsIdentity.FindFirst("culture").Value; } catch { culture = CommonHelper.AppConfig(TTXConstants.AppConfig.DefaultCulture.ToString()); } } //cheat temp //isAuth = true; AuthData result = new AuthData() { IsAuth = isAuth, accessToken = auth, UserId = userId, Culture = culture, RefreshToken = refreshtoken ?? string.Empty }; //Logger.Info("Current Token => " + result.RefreshToken + " || " + result.UserId); return(result); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.activity_welcome); FindViewById <TextView>(Resource.Id.btnLogin).Click += async(o, e) => { StringBuilder archonUrlSb = new StringBuilder(UrlConstants.ARCHON_AUTH_URL); archonUrlSb.Append("?appId=") .Append(LocalProperties.APP_ID) .Append("&appSecret=") .Append(LocalProperties.APP_SECRET); string result = await HttpClientUtils.GetJson(archonUrlSb.ToString()); AccessTokenViewModel requestToken = JsonConvert.DeserializeObject <AccessTokenViewModel>(result); var memes = PreferenceManager.GetDefaultSharedPreferences(ApplicationContext).Edit(); memes.PutString("ACCESS_TOKEN", requestToken.AccessToken).Apply(); memes.Commit(); StringBuilder gatewayUrlSb = new StringBuilder(UrlConstants.GATEWAY_AUTH_URL); gatewayUrlSb.Append("?appId=") .Append(LocalProperties.APP_ID) .Append("&redirect_uri=") .Append(UrlConstants.APP_URL) .Append("&state=/"); StartActivity(new Intent(Intent.ActionView, Uri.Parse(gatewayUrlSb.ToString()))); }; FindViewById <TextView>(Resource.Id.btnRegister).Click += (o, e) => { StringBuilder gatewayUrlSb = new StringBuilder(UrlConstants.GATEWAY_REGISTER_URL); gatewayUrlSb.Append("?appId=") .Append(LocalProperties.APP_ID) .Append("&redirect_uri=") .Append(UrlConstants.APP_URL) .Append("&state=/"); StartActivity(new Intent(Intent.ActionView, Uri.Parse(gatewayUrlSb.ToString()))); }; }
private async Task <AccessTokenViewModel> GenerateAccessTokenAsync(ApplicationUser user, bool isRemember) { var dtIssued = DateTime.UtcNow; var dtExpired = dtIssued.AddMinutes(MixService.GetAuthConfig <int>("CookieExpiration")); var dtRefreshTokenExpired = dtIssued.AddMinutes(MixService.GetAuthConfig <int>("RefreshTokenExpiration")); string refreshTokenId = string.Empty; string refreshToken = string.Empty; if (isRemember) { refreshToken = Guid.NewGuid().ToString(); RefreshTokenViewModel vmRefreshToken = new RefreshTokenViewModel( new RefreshTokens() { Id = refreshToken, Email = user.Email, IssuedUtc = dtIssued, ClientId = MixService.GetAuthConfig <string>("Audience"), Username = user.UserName, //Subject = SWCmsConstants.AuthConfiguration.Audience, ExpiresUtc = dtRefreshTokenExpired }); var saveRefreshTokenResult = await vmRefreshToken.SaveModelAsync(); refreshTokenId = saveRefreshTokenResult.Data?.Id; } AccessTokenViewModel token = new AccessTokenViewModel() { Access_token = await GenerateTokenAsync(user, dtExpired, refreshToken), Refresh_token = refreshTokenId, Token_type = MixService.GetAuthConfig <string>("TokenType"), Expires_in = MixService.GetAuthConfig <int>("CookieExpiration"), //UserData = user, Issued = dtIssued, Expires = dtExpired, LastUpdateConfiguration = MixService.GetConfig <DateTime?>("LastUpdateConfiguration") }; return(token); }
public async Task <IActionResult> LoginAsync([FromBody] LoginViewModel userCredentials) { var response = await _authenticationService.CreateAccessTokenAsync(userCredentials.UserName, userCredentials.Password); if (!response.Success) { return(BadRequest(new ErrorResource(response.Message))); } //TODO: why automapper is not working //var accessTokenResource = _mapper.Map<AccessToken, AccessTokenViewModel>(response.Token); var accessTokenResource = new AccessTokenViewModel() { AccessToken = response.Token.Token, RefreshToken = response.Token.RefreshToken.Token, Expiration = response.Token.Expiration }; return(Ok(accessTokenResource)); }
public AuthData ValidateAuth(IAuthenticationManager Authentication, string refreshtoken) { AccessTokenViewModel auth = null; string culture = string.Empty; string deviceId = string.Empty; DateTime expiredDate;// = DateTime.Now.AddMinutes(int.Parse(CommonHelper.AppConfig("ExpiredTokenTime"))); bool isAuth = Authentication.User.Identity.IsAuthenticated; string userId = Authentication.User.Identity.GetUserId(); //var objExpiredDate = Authentication.User.Claims.FirstOrDefault(c => c.Type == "expiredDate"); //string strExpiredDate = objExpiredDate != null ? objExpiredDate.Value : string.Empty; //bool isHaveExpiredDate = DateTime.TryParseExact(strExpiredDate, "dd-MM-yyyy hh:mm:ss", CultureInfo.CurrentCulture, DateTimeStyles.None, out expiredDate); //Logger.Info("Auth => " + refreshtoken + " || " + userId); if (!isAuth && !string.IsNullOrEmpty(refreshtoken))// || (objExpiredDate != null && isHaveExpiredDate && DateTime.UtcNow.AddSeconds(10) > expiredDate)) { var token = GetNewAccessToken(refreshtoken); expiredDate = token.Expires; if (token != null && !string.IsNullOrWhiteSpace(token.AccessToken)) { isAuth = string.IsNullOrWhiteSpace(userId) || userId == token.UserId; var user = FindUserById(token.UserId); auth = new AccessTokenViewModel() { access_token = token.TokenType + " " + token.AccessToken, token_type = token.TokenType, refresh_token = token.RefreshToken ?? string.Empty, expires_in = token.ExpiresIn, client_id = token.ClientId, deviceId = token.DeviceId, issued = token.Issued.ToLocalTime().ToString("dd-MM-yyyy hh:mm:ss"), expires = token.Expires.ToLocalTime().ToString("dd-MM-yyyy hh:mm:ss"), userData = CreateUserViewModel(user, null) }; refreshtoken = token.RefreshToken; culture = auth != null && auth.userData != null ? auth.userData.Culture : CommonHelper.AppConfig(TTXConstants.AppConfig.DefaultCulture.ToString()); deviceId = token.DeviceId; } } else { try { culture = Authentication.User.Claims.FirstOrDefault(c => c.Type == "culture").Value; deviceId = Authentication.User.Claims.FirstOrDefault(c => c.Type == "deviceId").Value; } catch { culture = CommonHelper.AppConfig(TTXConstants.AppConfig.DefaultCulture.ToString()); } } //cheat temp //isAuth = true; AuthData result = new AuthData() { IsAuth = isAuth, accessToken = auth, UserId = userId, Culture = culture, DeviceId = deviceId, RefreshToken = refreshtoken ?? string.Empty }; //Logger.Info("Current Token => " + result.RefreshToken + " || " + result.UserId); return(result); }
public async Task <ApiResult <UserViewModel> > UpdateUser(UpdateUserModel userModel, AuthData authData) { ApiResult <UserViewModel> result = null; int status = 0; string errorMsg = string.Empty; string responseKey = string.Empty; string message = string.Empty; var user = _userManager.FindById(userModel.UserId); UserViewModel vmUser = null; switch (userModel.FieldType.ToLower()) { case "username": if (userModel.Value.Length > 12) { responseKey = "InvalidUserName"; message = GlobalConfigurations.Instance.GetConfigValue("ErrorMessages", "InvalidUserName"); } else { //var userByName = UserInfoDAL.Instance.GetSingleModel(u => u.NickName == userModel.Value); var userByName = TTXUserInfoDAL.Instance.GetSingleModel(u => u.NickName == userModel.Value); if (userByName == null) { //user.UserInfo.NickName = userModel.Value; userByName = new TTX.Data.TTX_UserInfo() { UserId = user.Id, NickName = userModel.Value }; status = TTXUserInfoDAL.Instance.SaveModel(userByName) != null ? 1 : 0; user.IsActived = status == 1; } else { responseKey = "UserNameExisted"; message = string.Format(GlobalConfigurations.Instance.GetConfigValue("ErrorMessages", "UserNameExisted"), userModel.Value); } } break; case "email": var userByEmail = await _userManager.FindByEmailAsync(userModel.Value); if (userByEmail == null) { status = 1; user.Email = userModel.Value; } else { responseKey = "EmailExisted"; message = GlobalConfigurations.Instance.GetConfigValue("ErrorMessages", "EmailExisted"); } break; case "avatar": Image imgAvatar = CommonHelper.LoadImage(userModel.Value); if (imgAvatar != null) { string filePath = GetUserFilePath(userModel.UserId); string fileName = CommonHelper.UploadPhoto(filePath, imgAvatar); if (!string.IsNullOrEmpty(fileName)) { var info = TTXUserInfoDAL.Instance.GetSingleModel(u => u.UserId == userModel.UserId); if (!string.IsNullOrEmpty(info.Avatar)) { CommonHelper.RemoveFile(info.Avatar); } info.Avatar = string.Format("{0}/{1}", filePath, fileName); TTXUserInfoDAL.Instance.SaveModel(info); status = 1; message = GlobalConfigurations.Instance.GetConfigValue("AlertMessages", "UpdateAvatarSucceed"); info.Avatar = string.Format("{0}/{1}", filePath, fileName); } } else { responseKey = "InvalidImage"; } break; case "dob": var dobInfo = TTXUserInfoDAL.Instance.GetSingleModel(u => u.UserId == userModel.UserId); dobInfo.AgeGroup = CommonHelper.GetAgeGroup(userModel.DOB); TTXUserInfoDAL.Instance.SaveModel(dobInfo); status = 1; message = GlobalConfigurations.Instance.GetConfigValue("AlertMessages", "UpdateDOBSucceed"); break; } AccessTokenViewModel auth = null; if (status == 1) { var updResult = _userManager.Update(user); status = updResult.Succeeded ? 1 : 0; responseKey = updResult.Succeeded ? "Succeed" : "Unknown"; var token = GetNewAccessToken(authData.RefreshToken); if (token != null && !string.IsNullOrWhiteSpace(token.AccessToken)) { //user = FindUserById(token.UserId); auth = new AccessTokenViewModel() { access_token = token.TokenType + " " + token.AccessToken, token_type = token.TokenType, refresh_token = token.RefreshToken, expires_in = token.ExpiresIn, client_id = token.ClientId, issued = token.Issued.ToLocalTime().ToString("dd-MM-yyyy hh:mm:ss"), expires = token.Expires.ToLocalTime().ToString("dd-MM-yyyy hh:mm:ss"), userData = CreateUserViewModel(user, null) }; } vmUser = CreateUserViewModel(user, null); } result = new ApiResult <UserViewModel>() { status = status, responseKey = responseKey, data = vmUser, authData = auth, error = errorMsg, message = !string.IsNullOrEmpty(message) ? message : responseKey }; return(result); }
public ApiResult <UserViewModel> UpdateUserInfo(UpdateUserModel userModel, AuthData authData) { ApiResult <UserViewModel> result = null; int status = 0; string errorMsg = string.Empty; string responseKey = string.Empty; string message = string.Empty; ApplicationUser user = _userManager.FindById(userModel.UserId); UserViewModel vmUser = null; string strCulture = !string.IsNullOrEmpty(userModel.Culture) ? userModel.Culture : CommonHelper.AppConfig(TTXConstants.AppConfig.DefaultCulture.ToString()); if (user != null) { var info = TTXUserInfoDAL.Instance.GetSingleModel(u => u.UserId == user.Id); if (!string.IsNullOrWhiteSpace(userModel.Gender)) { info.Gender = userModel.Gender.Trim(); info.LastGenderRank = -1; } if (userModel.CountryId.HasValue) { info.CountryId = userModel.CountryId.Value; info.LastCountryRank = -1; } if (userModel.DOB.HasValue) { info.DOB = userModel.DOB; info.LastAgeGroupRank = -1; info.AgeGroup = CommonHelper.GetAgeGroup(info.DOB); } if (!string.IsNullOrEmpty(userModel.Culture)) { info.Culture = userModel.Culture; } TTXUserInfoDAL.Instance.SaveModel(info, out errorMsg); vmUser = CreateUserViewModel(user, null, info, info.Culture); status = string.IsNullOrEmpty(errorMsg) ? 1 : 0; responseKey = string.IsNullOrEmpty(errorMsg) ? "UpdateUserSucceed" : "UpdateUserFail"; } else { responseKey = "UserNotFound"; } AccessTokenViewModel auth = null; if (status == 1) { var updResult = _userManager.Update(user); status = updResult.Succeeded ? 1 : 0; LoginModel login = new LoginModel() { Culture = vmUser.Culture, DeviceId = authData.DeviceId, Email = vmUser.Email, FacebookId = vmUser.FacebookId, WeiboId = vmUser.WeiboId }; var token = GetNewAccessToken(authData.RefreshToken); if (token != null && !string.IsNullOrWhiteSpace(token.AccessToken)) { //user = FindUserById(token.UserId); auth = new AccessTokenViewModel() { access_token = token.TokenType + " " + token.AccessToken, token_type = token.TokenType, refresh_token = token.RefreshToken, expires_in = token.ExpiresIn, client_id = token.ClientId, deviceId = token.DeviceId, issued = token.Issued.ToLocalTime().ToString("dd-MM-yyyy hh:mm:ss"), expires = token.Expires.ToLocalTime().ToString("dd-MM-yyyy hh:mm:ss"), userData = CreateUserViewModel(user, null, vmUser.Culture) }; } } result = new ApiResult <UserViewModel>() { status = status, responseKey = responseKey, data = vmUser, authData = auth, error = errorMsg, message = !string.IsNullOrEmpty(message) ? message : responseKey }; return(result); }
public async Task <IActionResult> Post([FromBody] AccessTokenViewModel model, [FromRoute] string platform) { if (!ModelState.IsValid) { return(Ok(new Response { IsError = true, Status = 400, Message = "Sai dữ liệu đầu vào" })); } if (platform == "google") { var userInfoResponse = await Client.GetStringAsync($"https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={model.AccessToken}"); var userInfo = JsonConvert.DeserializeObject <UserData>(userInfoResponse); if (!string.Equals(userInfo.ClientId, _ggAuthSettings.ClientId)) { return(Ok(new Response { IsError = true, Status = 404, Message = "Đăng nhập thất bại" })); } var user = await _userManager.FindByEmailAsync(userInfo.Email); if (user == null) { var appUser = new User { Email = userInfo.Email, UserName = userInfo.Email, }; var result = await _userManager.CreateAsync(appUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8)); if (!result.Succeeded) { return(Ok(new Response { IsError = true, Status = 409, Message = "Lỗi khi thêm tài khoản" })); } await _appDbContext.UserInfo.AddAsync(new UserInfo { UserId = appUser.Id, FullName = userInfo.Name, BirthDate = DateTime.Now }); await _appDbContext.SaveChangesAsync(); await _userManager.AddToRoleAsync(appUser, "Member"); } // generate the jwt for the local user... var localUser = await _userManager.FindByNameAsync(userInfo.Email); if (localUser == null) { return(Ok(new Response { IsError = true, Status = 409, Message = "lỗi khi thêm tài khoản" })); } var localUserInfo = await _appDbContext.UserInfo.FindAsync(localUser.Id); var jwt = await Tokens.GenerateJwt(localUser, localUserInfo?.FullName ?? "noname", _jwtOptions, _userManager); return(Ok(new Response { Status = 200, Module = jwt })); } else if (platform == "facebook") { // 1.generate an app access token var appAccessTokenResponse = await Client.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={_fbAuthSettings.AppId}&client_secret={_fbAuthSettings.AppSecret}&grant_type=client_credentials"); var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse); // 2. validate the user access token var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={model.AccessToken}&access_token={appAccessToken.AccessToken}"); var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse); if (!userAccessTokenValidation.Data.IsValid) { return(Ok(new Response { IsError = true, Status = 400, Message = "Invalid facebook token" })); } // 3. we've got a valid token so we can request user data from fb var userInfoResponse = await Client.GetStringAsync($"https://graph.facebook.com/v3.2/me?fields=id,email,name,gender,birthday&access_token={model.AccessToken}"); var userInfo = JsonConvert.DeserializeObject <UserData>(userInfoResponse); var user = await _userManager.FindByEmailAsync(userInfo.Email); if (user == null) { var appUser = new User { Email = userInfo.Email, UserName = userInfo.Email, }; var result = await _userManager.CreateAsync(appUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8)); if (!result.Succeeded) { return(Ok(new Response { IsError = true, Status = 409, Message = "lỗi khi thêm tài khoản" })); } await _appDbContext.UserInfo.AddAsync(new UserInfo { UserId = appUser.Id, FullName = userInfo.Name, BirthDate = DateTime.Now }); await _appDbContext.SaveChangesAsync(); await _userManager.AddToRoleAsync(appUser, "Member"); } // generate the jwt for the local user... var localUser = await _userManager.FindByNameAsync(userInfo.Email); if (localUser == null) { return(Ok(new Response { IsError = true, Status = 409, Message = "lỗi khi thêm tài khoản" })); } var localUserInfo = await _appDbContext.UserInfo.FindAsync(localUser.Id); var jwt = await Tokens.GenerateJwt(localUser, localUserInfo?.FullName ?? "noname", _jwtOptions, _userManager); return(Ok(new Response { Status = 200, Module = jwt })); } return(Ok(new Response { IsError = true, Status = 400, Message = "chỉ hỗ trợ google facebook" })); }