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); }
public Token GetNewAccessToken(string refreshToken) { using (var client = new HttpClient()) { string baseAddress = CommonHelper.CurrentDomain; var form = new Dictionary <string, string> { { "grant_type", "refresh_token" }, { "refresh_token", refreshToken }, { "Client_id", CommonHelper.AppConfig("AppId") }, }; var tokenResponse = client.PostAsync(baseAddress + "token", new FormUrlEncodedContent(form)).Result; return(tokenResponse.Content.ReadAsAsync <Token>(new[] { new JsonMediaTypeFormatter() }).Result); } }
public Token GetAccessToken(LoginModel login) { using (var client = new HttpClient()) { string baseAddress = CommonHelper.CurrentDomain; var form = new Dictionary <string, string> { { "grant_type", "password" }, { "client_id", CommonHelper.AppConfig("AppId") }, { "email", login.Email }, { "weiboId", login.WeiboId }, { "facebookId", login.FacebookId }, { "deviceId", login.DeviceId }, { "password", login.Password }, { "culture", login.Culture } }; var tokenResponse = client.PostAsync(Path.Combine(baseAddress, "token"), new FormUrlEncodedContent(form)).Result; return(tokenResponse.Content.ReadAsAsync <Token>(new[] { new JsonMediaTypeFormatter() }).Result); } }
public UserViewModel CreateBackendUserViewModel(ApplicationUser appUser, List <IdentityRole> lstRole) { string strCulture = CommonHelper.AppConfig(TTXConstants.AppConfig.DefaultCulture.ToString()); var info = TTXUserInfoDAL.Instance.GetSingleModel(u => u.UserId == appUser.Id); List <RoleViewModel> lstVMRole = new List <RoleViewModel>(); foreach (var role in lstRole) { var vmRole = new RoleViewModel() { Id = role.Id, Name = role.Name, IsUserInRole = role.Users.FirstOrDefault(u => u.UserId == appUser.Id) != null }; lstVMRole.Add(vmRole); } CountryViewModel country = null; if (info != null) { country = new CountryViewModel(TTXCountryDAL.Instance.GetSingleModel(c => c.Id == info.CountryId)); } else { info = new TTX.Data.TTX_UserInfo() { InviteCode = Guid.NewGuid().ToString("N"), UserId = appUser.Id }; TTXUserInfoDAL.Instance.SaveModel(info); } return(new UserViewModel(info, appUser, lstVMRole, strCulture)); //{ // //Url = _UrlHelper.Link("GetUserById", new { id = appUser.Id }), // Id = appUser.Id, // IsActived = appUser.IsActived, // IsSetPassword = appUser.IsSetPassword, // //NickName = appUser.UserInfo.NickName, // //FirstName = appUser.UserInfo.FirstName, // //LastName = appUser.UserInfo.LastName, // //FullName = string.Format("{0} {1}", appUser.UserInfo.FirstName, appUser.UserInfo.LastName), // //Avatar = string.IsNullOrWhiteSpace(appUser.UserInfo.Avatar) ? "" : string.Format("{0}{1}", CommonHelper.CurrentDomain, appUser.UserInfo.Avatar), // ELO = info.ELO, // NickName = info.NickName, // Gender = info.Gender, // DOB = info.DOB.HasValue ? info.DOB.Value.ToString("yyyy-MM-dd") : null, // AgeGroup = info.AgeGroup, // CountryId = info.CountryId, // Country = country, // Avatar = string.IsNullOrWhiteSpace(info.Avatar) ? null : string.Format("{0}{1}", CommonHelper.CurrentDomain, info.Avatar), // Email = appUser.Email, // EmailConfirmed = appUser.EmailConfirmed, // //Level = appUser.Level, // JoinDate = appUser.JoinDate, // LastActiveDate = info.LastActiveDate.HasValue ? info.LastActiveDate.Value.ToLocalTime() : info.LastActiveDate, // Roles = lstVMRole, // RoleNames = _userManager.GetRolesAsync(appUser.Id).Result.ToList(), // //Claims = _AppUserManager.GetClaimsAsync(appUser.Id).Result.ToList(), // Devices = appUser.Devices, //}; }
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 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); }