public async Task <ActionResult> CreatePassword(string token, string password, string confirmPassword) { string url = _appSettings.ApiUrl + "/Login/UpdatePassword"; client.BaseAddress = new Uri(url); var accountToken = new AccountToken() { Token = token, }; var account = new Account() { Password = password, }; account.AccountTokens.Add(accountToken); HttpResponseMessage responseMessage = await client.PostAsJsonAsync(url, account); var responseData = new ResponseData <Account>(); if (responseMessage.IsSuccessStatusCode) { responseData = responseMessage.Content.ReadAsAsync <ResponseData <Account> >().Result; return(Json(new { success = true, responseText = responseData.Message, url = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host.Value + "/Login/Signin" })); } return(Json(new { success = false, responseText = responseData.Message })); }
private AccountResponse Authorize(Account acc) { List <Claim> claims = new List <Claim>() { new Claim(ClaimsIdentity.DefaultNameClaimType, acc.Login), new Claim(ClaimsIdentity.DefaultRoleClaimType, acc.Role), new Claim("id", acc.Id.ToString()) }; ClaimsIdentity identity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); AccountToken accountToken = new AccountToken() { AccountId = acc.Id, AccessToken = jwtService.GetJwt(identity), RefreshToken = Guid.NewGuid().ToString(), RefreshExpires = DateTime.Now.AddMinutes(authOptions.RefreshLifetime) }; accountRepository.DeleteAllTokens(acc.Id); accountRepository.Insert(accountToken); return(new AccountResponse() { Login = acc.Login, AccessToken = accountToken.AccessToken, RefreshToken = accountToken.RefreshToken }); }
public ResponseData <AccountToken> CheckAccountToken([FromBody] AccountToken accountToken) { try { var response = new ResponseData <AccountToken>(); var accToken = _accountTokenService.GetAccountTokenByToken(accountToken.Token); if (accToken == null || accountToken.Token != accToken.Token || accToken.Timestamp.Value.AddHours(24) < DateTime.UtcNow) { response.Data = accToken; response.Message = Constant.ResponseMessage.Error; response.Status = ResponseStatus.Error.ToString(); return(response); } response.Data = accToken; response.Message = ResponseMessage.Success; response.Status = ResponseStatus.Success.ToString(); return(response); } catch (Exception ex) { var response = new ResponseData <AccountToken>(); response.Message = ex.Message; response.Status = ResponseStatus.Error.ToString(); return(response); } }
public async Task <ActionResult> CreatePassword(string token) { string url = _appSettings.ApiUrl + "/Login/CheckAccountToken"; client.BaseAddress = new Uri(url); var accountToken = new AccountToken() { Token = token }; HttpResponseMessage responseMessage = await client.PostAsJsonAsync(url, accountToken); var responseData = new ResponseData <AccountToken>(); if (responseMessage.IsSuccessStatusCode) { responseData = responseMessage.Content.ReadAsAsync <ResponseData <AccountToken> >().Result; if (responseData.Status == ResponseStatus.Error.ToString()) { return(View("InvalidToken")); } } return(View()); }
public async Task <List <AccountInfo> > RefreshAllAccountsInfo() { var accounts = await GetAccounts(); var accountsInfo = accounts.Select(x => new AccountInfo() { Address = x }).ToList(); foreach (var accountInfo in accountsInfo) { try { accountInfo.Eth.Balance = await GetEthBalance(accountInfo.Address); foreach (var token in tokenRegistryService.GetRegisteredTokens()) { var accountToken = new AccountToken { Symbol = token.Symbol, Balance = await GetTokenBalance(token, accountInfo.Address) }; accountInfo.AccountTokens.Add(accountToken); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } return(accountsInfo); }
private async Task <(bool tokenSuccess, string token)> _TryGetTokenAsync(string accountId) { bool tokenSuccess = false; string token = null; DateTimeOffset tokenExpires = default; if (_accountTokens.TryGetValue(accountId, out AccountToken cachedToken)) { tokenSuccess = true; token = cachedToken.Token; tokenExpires = cachedToken.TokenExpires; } if (token == null || tokenExpires == default || DateTimeOffset.Now > (tokenExpires - TimeSpan.FromSeconds(30))) { GraphTokenResult result = await _authProvider.GetTokenAsync(accountId).ConfigureAwait(false); tokenSuccess = result.Success; if (result.Success) { token = result.AccessToken; tokenExpires = result.Expires; // cache the token _accountTokens[accountId] = new AccountToken(token, tokenExpires); } } return(tokenSuccess, token); }
public async Task Insert(AccountToken accountToken) { using (IDbConnection dbConnection = Connection) { dbConnection.Open(); await dbConnection.InsertAsync(accountToken); } }
/// <summary> /// Twitter クライアントと基になる JSON オブジェクトを指定し TwitterStreamEventArgs の新しいインスタンスを初期化します。 /// </summary> /// <param name="client">Twitter クライアント。</param> /// <param name="json">基になる JSON オブジェクト。</param> public TwitterStreamEventArgs(TwitterClient client, DynamicJson json) { this.json = json; this.Account = client.Account; this.Source = new User(client, this.json.source); this.Target = new User(client, this.json.target); this.TargetStatus = this.json.target_object() ? new Status(client, this.json.target_object, this.Target) : null; }
public async Task <bool> CheckUserHasTokenAsync(string email) { AccountToken token = await _context.AccountToken .Include(c => c.User) .Include(c => c.User.Credentials) .FirstOrDefaultAsync(act => act.User.Credentials.Email == email); return(token != null); }
public ResponseData <Account> Signup([FromBody] Account account) { try { var response = new ResponseData <Account>(); var CheckAccountIsExist = _accountService.GetAccountByEmail(account.Email); if (CheckAccountIsExist == null) { var acc = _accountService.Insert(account); if (acc == null) { response.Data = acc; response.Message = Constant.ResponseMessage.Error; response.Status = ResponseStatus.Error.ToString(); return(response); } var accToken = new AccountToken() { AccountId = acc.Id, IsSignupToken = true, Timestamp = DateTime.UtcNow, Token = Guid.NewGuid().ToString() }; acc.AccountTokens.Add(_accountTokenService.Insert(accToken)); var _event = new Event() { AccountId = acc.Id, EventTypeId = Constant.EventType.SigninSignoutOfWebPortal, EventDetail = Constant.ResponseMessage.Signin, Timestamp = DateTime.UtcNow, Message = Constant.ResponseMessage.Signin }; _eventService.Insert(_event); response.Data = acc; response.Message = Constant.ResponseMessage.Success; } else { response.Message = Constant.ResponseMessage.EmailExist; } response.Status = ResponseStatus.Success.ToString(); return(response); } catch (Exception ex) { var response = new ResponseData <Account>(); response.Message = ex.Message; response.Status = ResponseStatus.Error.ToString(); return(response); } }
public AccountResponse UpdateToken(string refreshToken) { AccountToken accToken = accountRepository.GetToken(refreshToken).Result; if (accToken == null || accToken.RefreshExpires <= DateTime.Now) { return(null); } Account acc = accountRepository.GetById(accToken.AccountId).Result; return(Authorize(acc)); }
async Task ISecurityLayer.RevokeToken(Guid user, AccountToken token) { await this.connectionManager.ExecuteSql( "auth.revoketoken", collection => { collection.AddWithValue("id", user); collection.AddWithValue("token", token.Bytes); }, CancellationToken.None); }
public AccountResponse UpdateToken(string refreshToken) { AccountToken accToken = accountTokens.Find(x => x.RefreshToken == refreshToken); if (accToken == null || accToken.RefreshExpires <= DateTime.Now) { return(null); } Account acc = accounts.Find(a => a.Id == accToken.AccountId); return(Authorize(acc)); }
public async Task <AccountToken> DeleteAccountTokenByUserIdAsync(Guid userId) { AccountToken accountToken = await _context.AccountToken.Include(c => c.User) .FirstOrDefaultAsync(с => с.UserId == userId); if (accountToken != null) { _context.AccountToken.Remove(accountToken); _context.SaveChanges(); } return(accountToken); }
public async Task <IActionResult> VerifyAccountToken([FromBody] dynamic param = null) { string tokenValue = null; AccountToken accountToken = null; object result = null; try { tokenValue = param.tokenValue; AccountTokenType type = (AccountTokenType)((short)param.accountType); accountToken = await GetAccountToken(tokenValue, type); switch (type) { case AccountTokenType.EmailChange: accountToken.Account.RegisterForRecordStateChange(); accountToken.Account.Email = accountToken.AddData; accountToken.Account.EmailConfirmed = true; accountToken.Account.UnregisterForRecordStateChange(); accountToken.RecordState = RecordState.Deleted; _dbi.ManageIdentityModels(accountToken.Account, accountToken); break; case AccountTokenType.SignUp: result = accountToken.Account.ToModel(); break; } return(Json(new { Ok = true, result = result })); } catch (Exception ex) { return(InternalServerError(ex)); } finally { tokenValue = null; accountToken = null; result = null; } }
async Task <User> ISecurityLayer.GetUser(AccountToken token, IPAddress ip, TimeSpan expiration) { var result = await this.connectionManager.ExecuteSql( "auth.getUser", parameters => { parameters.AddWithValue("token", token.Bytes); parameters.AddWithValue("ip", PasswordHelper.GetIPAddressInSqlForm(ip)); parameters.AddWithValue("expiration", (int)expiration.TotalMinutes); }, reader => { if (false == reader.Read()) { return(null); } else { var user = new User { Id = (Guid)reader["id"], FirstName = (string)reader["first"], LastName = (string)reader["last"], Created = (DateTime)reader["created"] }; reader.NextResult(); var roles = default(UserRoles); while (reader.Read()) { roles |= (UserRoles)Enum.Parse(typeof(UserRoles), (string)reader["claim"]); } user.Roles = roles; return(user); } }, this.tokenSource.Token); if (null == result) { throw new UnauthorizedAccessException("Could not find user."); } return(result); }
public JsonResult RefreshCache() { var jsonm = new ResultJson(); try { using (var db = SugarBase.GetIntance()) { //刷新配置项 //RedisHelper.StringSet(KeyHelper.CACHE_SITE_CONFIG, LoadConfig(Utils.GetXmlMapPath(KeyHelper.FILE_SITE_XML_CONFING))); BasicConfigHelper.setBasicConfig(); //刷新菜单 setMenuCache(); //刷新当前登录权限 var usermodel = db.Queryable <SysUser>().Where(m => m.SysUserID == SysUserModel.UserID).First(); if (usermodel != null) { var userModel = new AccountToken(); userModel.UserID = usermodel.SysUserID; userModel.UserName = usermodel.SysNickName; var menu_list = db.Queryable <SysModule, SysRoleModule, SysRole, SysUserRole>((sm, srm, sr, sur) => new object[] { JoinType.Left, sm.ID == srm.ModuleID, JoinType.Left, srm.RoleID == sr.RoleID, JoinType.Left, sr.RoleID == sur.RoleID, }) .Where((sm, srm, sr, sur) => sur.UserID == usermodel.SysUserID) .OrderBy((sm, srm, sr, sur) => sm.Sort, OrderByType.Desc) .Select(sm => new SysModule { ID = sm.ID, Href = sm.Href, Business = sm.Business, Icon = sm.Icon, Name = sm.Name, Sort = sm.Sort, Type = sm.Type, ParentID = sm.ParentID }).ToList(); userModel.MenuList = menu_list; var daySpan = TimeSpan.FromMinutes(30); RedisHelper.StringSet("system:SysToken:" + userModel.UserID, MD5CryptHelper.Encrypt(JsonConvert.Serialize(userModel)), daySpan); } } } catch (Exception ex) { jsonm.status = 500; jsonm.msg = "清理失败"; LogProvider.Error("清理缓存", ex.StackTrace, ex.Message); } return(Json(jsonm)); }
private void InitialiseTokenBalanceSummary() { TokenBalanceSummary = new List <AccountToken>(); var tokens = AccountsInfo.SelectMany(x => x.AccountTokens); var symbols = tokens.Select(x => x.Symbol).Distinct(); foreach (var symbol in symbols) { var tokenSummary = new AccountToken() { Symbol = symbol }; tokenSummary.Balance = tokens.Where(x => x.Symbol == symbol).Sum(x => x.Balance); TokenBalanceSummary.Add(tokenSummary); } }
public async Task ResendConfirmationEmail([FromBody] AppUser user) // user is just the container for .Email, the rest of the properties aren't filled out { var userWithEmail = await DbSession.LoadAsync <AppUser>("AppUsers/" + user.Email); if (userWithEmail?.EmailConfirmed == false) { var confirmToken = new AccountToken { Id = $"AccountTokens/Confirm/{userWithEmail.Email}", ApplicationUserId = userWithEmail.Id, Token = Guid.NewGuid().ToString() }; await DbSession.StoreAsync(confirmToken); DbSession.SetRavenExpiration(confirmToken, DateTime.UtcNow.AddDays(14)); emailSender.QueueConfirmEmail(userWithEmail.Email, confirmToken.Token, appOptions); } }
public async Task <List <AccountInfo> > GetAccountsInfo() { var web3 = GetWeb3(); var accounts = await GetAccounts(); var accountsInfo = accounts.Select(x => new AccountInfo() { Address = x }).ToList(); foreach (var accountInfo in accountsInfo) { try { var weiBalance = await web3.Eth.GetBalance.SendRequestAsync(accountInfo.Address).ConfigureAwait(false); var balance = (decimal)weiBalance.Value / (decimal)Math.Pow(10, 18); accountInfo.Eth.Balance = balance; foreach (var token in tokenRegistryService.GetRegisteredTokens()) { var service = new StandardTokenEIP20.StandardTokenService(web3, token.Address); var accountToken = new AccountToken { Symbol = token.Symbol }; var wei = await service.GetBalanceOfAsync <BigInteger>(accountInfo.Address); balance = (decimal)wei / (decimal)Math.Pow(10, token.NumberOfDecimalPlaces); accountToken.Balance = balance; accountInfo.AccountTokens.Add(accountToken); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } return(accountsInfo); }
public LoginResponse UpdateToken(string refreshToken) { AccountToken accountToken = accountTokens.Find(at => at.RefreshToken == refreshToken); if (accountToken == null) { return(null); } if (accountToken.Expires <= DateTime.Now) { return(null); } Account account = accounts.Find(a => a.Id == accountToken.AccountId); if (account == null) { return(null); } return(Authentication(account)); }
public async void ConnectPin() { if (!string.IsNullOrEmpty(_pinInput)) { var userCredentials = CredentialsCreator.GetCredentialsFromVerifierCode(PinInput, TwitterConnectionInfoSingleton.getInstance().GetAppCredentials()); if (userCredentials != null) { Auth.SetCredentials(userCredentials); var account = new Token(userCredentials.AccessToken, userCredentials.AccessTokenSecret); AccountToken.SaveAccountData(account); this.NavigationService.Navigate(typeof(Views.TimeLine)); } else { var msgDialogue = new MessageDialog("Pin code invalid", "Connection error"); await msgDialogue.ShowAsync(); } return; } if (File.Exists(ApplicationData.Current.LocalFolder.Path + "\\config.json")) { var tokens = AccountToken.ReadTokens(); var userCredentials = Auth.CreateCredentials(TwitterConnectionInfoSingleton.getInstance().getConsumerKey(), TwitterConnectionInfoSingleton.getInstance().getConsumerSecret(), tokens.token, tokens.tokenSecret); Auth.SetCredentials(userCredentials); this.NavigationService.Navigate(typeof(Views.TimeLine)); } else { var msgDialogue = new MessageDialog("No account registered", "Connection error"); await msgDialogue.ShowAsync(); } }
/// <summary> /// Consumer key、 Consumer secret およびアカウントを指定し OAuthAuthorization の新しいインスタンスを初期化します。 /// </summary> /// <param name="consumerKey">Consumer key。</param> /// <param name="consumerSecret">Consumer secret。</param> /// <param name="token">アカウント。</param> public OAuthAuthorization(string consumerKey, string consumerSecret, AccountToken token) { this.ConsumerKey = consumerKey; this.ConsumerSecret = consumerSecret; this.Token = token; }
/// <summary> /// アカウントを指定し OAuthAuthorization の新しいインスタンスを初期化します。 /// </summary> /// <param name="token">アカウント。</param> public OAuthAuthorization(AccountToken token) : this("P3nbsIMxxYBubPOviQg", "96kDHNIWPkfb0POch4vuAjwHPXitxg9OqfYvnoXktY", token) { }
public async Task <IActionResult> SaveActiveProfile([FromBody] AccountProfileViewModel vm = null) { Account activeAccount = null; string fullName = null; AccountToken toSend = null; List <IdentityModel> toSave = null; Exception ex1 = null, ex2 = null; ClaimsIdentity claimsIdentity = null; try { if (vm == null) { throw new NullReferenceException(); } if (!string.IsNullOrEmpty(vm.Email) && !Helper.IsEmailValid(vm.Email)) { throw new ExceptionID(MessageIdentifier.INVALID_EMAIL); } activeAccount = _dbi.GetActiveAccount(); if (activeAccount == null || activeAccount.UID != vm.UID) { throw new NullReferenceException(); } toSave = new List <IdentityModel>(); if (!string.IsNullOrEmpty(vm.Email) && activeAccount.GetEmailValue()?.ToLower() != vm.Email.ToLower()) { string emailValue = activeAccount.GetEmailValue(); if (Helper.IsEmailValid(emailValue)) { toSave.AddRange(from t in activeAccount.AccountTokens where t.Type == AccountTokenType.EmailChange select t.SetRecordState(RecordState.Deleted)); } toSend = new AccountToken() { RecordState = RecordState.Added, Value = _dbi.GenerateTokenValue(), Type = AccountTokenType.EmailChange, EmailSentStatus = EmailSatus.NotSent, AddData = vm.Email, Account_Id = activeAccount.ID }; activeAccount.RegisterForRecordStateChange(); activeAccount.Email = activeAccount.UID; activeAccount.EmailConfirmed = false; activeAccount.UnregisterForRecordStateChange(); } activeAccount.RegisterForRecordStateChange(); activeAccount.AccountName = vm.AccountName; activeAccount.FName = vm.FName; activeAccount.LName = vm.LName; activeAccount.UnregisterForRecordStateChange(); if (activeAccount.RecordState != RecordState.None) { toSave.Add(activeAccount); } if (toSend == null) { if (toSave.Count > 0) { _dbi.ManageIdentityModels(toSave.ToArray()); } } else { await Task.WhenAll( Helper.GetFunc(() => { try { if (toSave.Count > 0) { _dbi.ManageIdentityModels(toSave.ToArray()); } } catch (Exception ex) { ex1 = ex; } return(Task.CompletedTask); })(), Helper.GetFunc(() => { try { toSend = _dbi.ManageModel(toSend); } catch (Exception ex) { ex2 = ex; } return(Task.CompletedTask); })()); if (ex1 != null) { throw ex1; } if (ex2 != null) { throw ex2; } string lang = this.GetSelectedLanguage(); using (var mailService = this.GetMailService()) { await Task.WhenAll( Helper.GetFunc(() => { try { toSend.RegisterForRecordStateChange(); toSend.EmailSentStatus = EmailSatus.Sending; toSend.UnregisterForRecordStateChange(); if (toSend.RecordState != RecordState.None) { toSend = _dbi.ManageModel(toSend); } } catch (Exception ex) { ex1 = ex; } return(Task.CompletedTask); })(), Helper.GetFunc(async() => { string link = null; try { link = Url.Action("xxXxx", "confirmemail", null, this.Request.Scheme); link += (link.EndsWith("/") ? "" : "/") + toSend.Value; link = link.Replace("/xxXxx/", "/"); await mailService.SendEmailAsync( $"{LanguageManager.GetLabel("AppTitle", lang)} {LanguageManager.GetLabel("lbl_CnfrmEmailAddr", lang)}", LanguageManager.GetOther("email_ChngEmail", lang) .Replace("{1}", LanguageManager.GetLabel("AppTitle", lang)) .Replace("{2}", link), toEmail: toSend.AddData, fromName: LanguageManager.GetLabel("AppTitle", lang), replyToEmail: "*****@*****.**", replyToName: "NO REPLY"); } catch (Exception ex) { ex2 = new ExceptionID(MessageIdentifier.INVALID_EMAIL, ex, false); } finally { link = null; } })()); if (ex1 != null) { throw ex1; } if (ex2 != null) { _dbi.ManageModel(toSend.SetRecordState(RecordState.Deleted)); throw ex2; } toSend.RegisterForRecordStateChange(); toSend.EmailSentStatus = EmailSatus.Sent; toSend.UnregisterForRecordStateChange(); if (toSend.RecordState != RecordState.None) { toSend = _dbi.ManageModel(toSend); } } } fullName = DbInteractor.GetAccountFullName(activeAccount); claimsIdentity = new ClaimsIdentity(BaseController.APP_ID); claimsIdentity.AddClaims(this.User.Claims.Where(l => l.Type != USER_FULL_NAME)); claimsIdentity.AddClaim(new Claim(USER_FULL_NAME, fullName)); if (GetRememberUser(this.User)) { await this.HttpContext.Authentication.SignInAsync( BaseController.APP_ID, new ClaimsPrincipal(claimsIdentity), new AuthenticationProperties { IsPersistent = true, ExpiresUtc = GetClaimExpDate(this.User) }); } else { await this.HttpContext.Authentication.SignInAsync(BaseController.APP_ID, new ClaimsPrincipal(claimsIdentity)); } return(Json(new { Ok = true, FullName = fullName, profile = this.GetActiveProfileViewModel() })); } catch (Exception ex) { return(InternalServerError(ex)); } finally { activeAccount = null; claimsIdentity = null; toSave?.Clear(); toSave = null; } }
public async Task <IActionResult> ForgotPasswordGenToken([FromBody] dynamic vm = null) { string email = null, tempStr = null; Account account = null; AccountToken accountToken = null; Exception ex1 = null, ex2 = null; try { tempStr = vm?.accountIdentifier; if (string.IsNullOrEmpty(tempStr)) { throw new ExceptionID(MessageIdentifier.INVALID_EMAIL); } if (Helper.IsEmailValid(tempStr)) { email = tempStr; tempStr = null; } account = _dbi.GetAccount(0, null, email, tempStr); if (account == null || !Helper.IsEmailValid(account.Email)) { throw new ExceptionID(MessageIdentifier.USER_NOT_FOUND); } await Task.WhenAll( Helper.GetFunc(() => { AccountToken[] toDeleteTokens = null; try { toDeleteTokens = _dbi.GetAccountTokens(accountID: account.ID, type: AccountTokenType.ResetPassword) .Select(l => l.SetRecordState <AccountToken>(RecordState.Deleted)) .ToArray(); if (toDeleteTokens.Length > 0) { _dbi.ManageIdentityModels(toDeleteTokens); } } catch (Exception ex) { ex1 = ex; } finally { toDeleteTokens = null; } return(Task.CompletedTask); })(), Helper.GetFunc(() => { try { tempStr = _dbi.GenerateTokenValue(); accountToken = _dbi.ManageModel( new AccountToken() { RecordState = RecordState.Added, Account_Id = account.ID, Type = AccountTokenType.ResetPassword, EmailSentStatus = EmailSatus.NotSent, Value = tempStr }); } catch (Exception ex) { ex2 = ex; } return(Task.CompletedTask); })()); if (ex1 != null) { throw ex1; } if (ex2 != null) { throw ex2; } string link = null, lang = null; try { lang = this.GetSelectedLanguage(); link = Url.Action("xxXxx", "resetpassword", null, this.Request.Scheme); link += (link.EndsWith("/") ? "" : "/") + accountToken.Value; link = link.Replace("/xxXxx/", "/"); using (var mailService = this.GetMailService()) { await mailService.SendEmailAsync( $"{LanguageManager.GetLabel("AppTitle", lang)} {LanguageManager.GetLabel("lbl_RstPsswrd", lang)}", LanguageManager.GetOther("email_RstPsswrd", lang) .Replace("{1}", LanguageManager.GetLabel("AppTitle", lang)) .Replace("{2}", link), toEmail : account.Email, fromName : LanguageManager.GetLabel("AppTitle", lang), replyToEmail : "*****@*****.**", replyToName : "NO REPLY"); } } catch (Exception ex) { _dbi.ManageModel(accountToken.SetRecordState(RecordState.Deleted)); throw ex; } finally { link = null; lang = null; } return(Json(new { Ok = true, token = "" })); } catch (Exception ex) { return(InternalServerError(ex)); } finally { email = null; tempStr = null; account = null; ex1 = null; ex2 = null; } }
/// <summary> /// Revoke a token /// </summary> /// <param name="user">The user to revoke for</param> /// <param name="token">The token to revoke</param> /// <returns>An async task</returns> public static Task RevokeToken(Guid user, AccountToken token) { return(DataLayer.Security.RevokeToken(user, token)); }
public ResponseData <Account> ForgotPassword([FromBody] Account account) { try { var acc = _accountService.GetAccountByEmail(account.Email); var response = new ResponseData <Account>(); if (acc == null) { response.Data = acc; response.Message = Constant.ResponseMessage.EmailIsNotExist; response.Status = ResponseStatus.Success.ToString(); return(response); } var token = _accountTokenService.GetAccountTokenByAccountId(acc.Id); if (token != null) { token.Token = Guid.NewGuid().ToString(); token.Timestamp = DateTime.UtcNow; _accountTokenService.Update(token); acc.AccountTokens.Add(token); } else { var accToken = new AccountToken() { AccountId = acc.Id, IsSignupToken = false, Timestamp = DateTime.UtcNow, Token = Guid.NewGuid().ToString() }; _accountTokenService.Insert(accToken); acc.AccountTokens.Add(accToken); } var _event = new Event() { AccountId = acc.Id, EventTypeId = Constant.EventType.PasswordReset, EventDetail = Constant.ResponseMessage.ForgotPassword, Timestamp = DateTime.UtcNow, Message = Constant.ResponseMessage.ForgotPassword }; _eventService.Insert(_event); //string linkResetPassword = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host.Value + "/Login/CreatePassword"; //var parametersToAdd = new System.Collections.Generic.Dictionary<string, string> { { "accountid", acc.Id.ToString() }, { "token", acc.AccountTokens.FirstOrDefault().Token} }; //var content = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(linkResetPassword, parametersToAdd); //_helperService.sendEmail("*****@*****.**", Configuration.MailSubject, content); response.Data = acc; response.Message = ResponseMessage.Success; response.Status = ResponseStatus.Success.ToString(); return(response); } catch (Exception ex) { var response = new ResponseData <Account>(); response.Message = ex.Message; response.Status = ResponseStatus.Error.ToString(); return(response); } }
public async Task <AccountToken> LoginAccount(AccountLogin accountLogin) { AccountToken result = await _service.PostRequest <AccountToken>(string.Format("{0}/authenticate", Constants.ApiUrlBase), accountLogin); return(result); }
public HubIdentity(User user, AccountToken token) { this.user = user; this.token = token; }
public async Task <IActionResult> SendSignupEmail([FromBody] dynamic param) { string link = null; AccountToken accountToken = null; Exception ex1 = null, ex2 = null; try { accountToken = Helper.JSonCamelDeserializeObject <AccountToken>(param); if (accountToken == null || accountToken.ID <= 0 || string.IsNullOrEmpty(accountToken.Value)) { throw new NullReferenceException(); } await Task.WhenAll( Helper.GetFunc(async() => { string lang = null; try { lang = LanguageManager.DEFAULT_LANGUAGE; link = Url.Action("xxXxx", "completeregistration", null, this.Request.Scheme); link += (link.EndsWith("/") ? "" : "/") + accountToken.Value; link = link.Replace("/xxXxx/", "/"); using (var mailService = this.GetMailService()) { await mailService.SendEmailAsync( $"{LanguageManager.GetLabel("AppTitle", lang)} {LanguageManager.GetLabel("lbl_CompleteReg", lang)}", LanguageManager.GetOther("email_SignUp", lang) .Replace("{1}", LanguageManager.GetLabel("AppTitle", lang)) .Replace("{2}", link), toEmail: accountToken.AddData, fromName: LanguageManager.GetLabel("AppTitle", lang), replyToEmail: "*****@*****.**", replyToName: "NO REPLY"); } } catch (Exception ex) { ex1 = ex; } finally { lang = null; } })(), Helper.GetFunc(() => { try { accountToken.RegisterForRecordStateChange(); accountToken.EmailSentStatus = EmailSatus.Sending; accountToken.UnregisterForRecordStateChange(); accountToken = _dbi.ManageModel(accountToken); } catch (Exception ex) { ex2 = ex; } return(Task.CompletedTask); })()); if (ex1 != null || ex2 != null) { accountToken.RegisterForRecordStateChange(); accountToken.EmailSentStatus = EmailSatus.SendFail; accountToken.UnregisterForRecordStateChange(); accountToken = _dbi.ManageModel(accountToken); if (ex1 != null) { throw ex1; } if (ex2 != null) { throw ex2; } } accountToken.RegisterForRecordStateChange(); accountToken.EmailSentStatus = EmailSatus.Sent; accountToken.UnregisterForRecordStateChange(); accountToken = _dbi.ManageModel(accountToken); return(Json(accountToken.Simplify())); } catch (Exception ex) { return(InternalServerError(ex)); } finally { link = null; } }
/// <summary>Executes the authorization filter to synchronize.</summary> /// <returns>The authorization filter to synchronize.</returns> /// <param name="actionContext">The action context.</param> /// <param name="cancellationToken">The cancellation token associated with the filter.</param> /// <param name="continuation">The continuation.</param> public async Task <HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func <Task <HttpResponseMessage> > continuation) { //var isHttps = actionContext.Request.RequestUri.Scheme == Uri.UriSchemeHttps; var isHttps = true; // Get the custom auth header. YEA THATS RIGHT CUSTOM. SCREW THE SYSTEM var containsAuth = actionContext.Request.Headers.Contains(RequireCredentialsAttribute.AuthorizationHeaderName); // If they didnt include the header, clearly they cant touch stuff if (false == containsAuth) { // If they didnt use https yell at them for being stupid return(RequireCredentialsAttribute.UnauthorizedResponse()); } // Get the header var header = actionContext.Request.Headers.GetValues(RequireCredentialsAttribute.AuthorizationHeaderName).FirstOrDefault(); if (false == isHttps) { return(new HttpResponseMessage(HttpStatusCode.UpgradeRequired) { Content = new StringContent( $"HTTPS REQUIRED. THE TOKEN \'{header}\' HAS BEEN REVOKED BECAUSE WE CAN'T GUARANTEE SOMEONE WONT BE MESSING WITH YOUR STUFF NOW."), ReasonPhrase = "HTTPS REQUIRED" }); } User user = null; // Get ip to log var ip = IPAddressHelper.GetIPAddress(actionContext.Request); var token = new AccountToken(header); try { user = await DataLayer.Security.GetUser(token, ip, TimeSpan.FromDays(5)); } catch (UnauthorizedAccessException) { return(RequireCredentialsAttribute.UnauthorizedResponse()); } var identity = new HubIdentity(user, token); var principal = new HubPrincipal(identity); // This is mostly here to screw with justin if (principal.IsInRole(UserRoles.BLACKLISTED)) { return (RequireCredentialsAttribute.BlacklistedResponse( "This account has been blacklisted. All requests will be rejected.")); } Thread.CurrentPrincipal = principal; HttpContext.Current.User = principal; return(await continuation()); }
public JsonResult LoginSubmit(string username, string password, string vercode = "") { var jsonm = new ResultJson(); try { ; var sessionid = CookieHelper.GetCookie("sessionid"); var result = false; if (RedisHelper.KeyExists("imgcode:" + sessionid)) { var code = RedisHelper.StringGet("imgcode:" + sessionid); if (code.Trim().ToUpper() == vercode.Trim().ToUpper()) { result = true; } else { jsonm.status = 500; jsonm.msg = "验证码错误"; } } if (result) { using (var db = SugarBase.GetIntance()) { if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { var model = db.Queryable <SysUser>().Where(m => m.Status == 1 && m.SysUserName.Equals(username.Trim()) && m.SysUserPwd.Equals(SHACryptHelper.SHA256Encrypt(password))).First(); if (model != null) { var userModel = new AccountToken(); userModel.UserID = model.SysUserID; userModel.UserName = model.SysNickName; var menu_list = db.Queryable <SysModule, SysRoleModule, SysRole, SysUserRole>((sm, srm, sr, sur) => new object[] { JoinType.Left, sm.ID == srm.ModuleID, JoinType.Left, srm.RoleID == sr.RoleID, JoinType.Left, sr.RoleID == sur.RoleID, }) .Where((sm, srm, sr, sur) => sur.UserID == model.SysUserID && sm.Status) .OrderBy((sm, srm, sr, sur) => sm.Sort, OrderByType.Desc) .OrderBy((sm, srm, sr, sur) => sm.CreateTime, OrderByType.Asc) .Select(sm => new SysModule { ID = sm.ID, Href = sm.Href, Business = sm.Business, Icon = sm.Icon, Name = sm.Name, Sort = sm.Sort, Type = sm.Type, ParentID = sm.ParentID }).ToList(); CookieHelper.WriteCookie("systoken", MD5CryptHelper.Encrypt(JsonConvert.Serialize(userModel)), 30); var claims = new[] { new Claim("UserID", model.SysUserID), new Claim("UserName", model.SysNickName) }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); ClaimsPrincipal user = new ClaimsPrincipal(claimsIdentity); //var identity = new ClaimsIdentity(); //identity.AddClaim(new Claim(ClaimTypes.Sid, userModel.UserID)); //identity.AddClaim(new Claim(ClaimTypes.Name, userModel.UserName)); HttpContextHelper.Current.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user); userModel.MenuList = menu_list; var daySpan = TimeSpan.FromMinutes(30); RedisHelper.StringSet("system:SysToken:" + userModel.UserID, MD5CryptHelper.Encrypt(JsonConvert.Serialize(userModel)), daySpan); setMenuCache(); SetSysLog("【系统登录】" + userModel.UserName, 1, 1); //HttpContext.Session.SetString("SysToken", MD5CryptHelper.Encrypt(JsonConvert.Serialize(userModel))); jsonm.status = 200; jsonm.msg = "登录成功"; } else { jsonm.status = 500; jsonm.msg = "账号或密码错误"; } } else { jsonm.status = 500; jsonm.msg = "请填写账号信息"; } } } } catch (Exception ex) { jsonm.status = 500; jsonm.msg = "登录失败"; LogProvider.Error("登录", ex.StackTrace, ex.Message); } return(Json(jsonm)); }