//Adding Token into the DB public bool AddUserTokenIntoDB(UserTokenMaster userTokenMaster) { //First Check the existance of the Token in the DB var tokenMaster = context.UserTokenMasters.FirstOrDefault(x => x.UserName == userTokenMaster.UserName && x.UserPassword == userTokenMaster.UserPassword); if (tokenMaster != null) { context.UserTokenMasters.Remove(tokenMaster); } context.UserTokenMasters.Add(userTokenMaster); bool isAdded = context.SaveChanges() > 0; return(isAdded); }
public Token GetTokenFromDB(string username, string password) { UserTokenMaster userMaster = context.UserTokenMasters.FirstOrDefault(user => user.UserName.Equals(username, StringComparison.OrdinalIgnoreCase) && user.UserPassword == password); Token token = null; if (userMaster != null) { token = new Token() { AccessToken = userMaster.AccessToken, RefreshToken = userMaster.RefreshToken, ExpiredDateTime = (DateTime)userMaster.TokenExpiredTime }; } return(token); }
//In this method we need to implement the logic whether we need get a brand new access token // or we need the access token based on the Refresh Token private static Token GetTokens(string clientId, string clientSecret, string RefreshToken) { Token token = null; if (string.IsNullOrEmpty(RefreshToken)) { token = GetAccessToken(clientId, clientSecret, Username, Password); } else { token = GetAccessTokenByRefreshToken(clientId, clientSecret, RefreshToken); // The Refresh token can become invalid for several reasons // such as invalid cliendid and secret or the user's password has changed. // In Such cases issue a brand new access token if (!string.IsNullOrEmpty(token.Error)) { token = GetAccessToken(clientId, clientSecret, Username, Password); } } if (!string.IsNullOrEmpty(token.Error)) { throw new Exception(token.Error); } else { //Need to store the token in any presistent storage token.ExpiredDateTime = DateTime.Now.AddSeconds(token.ExpiresIn); //Create an object of type UserTokenMaster UserTokenMaster userTokenMaster = new UserTokenMaster() { UserName = Username, UserPassword = Password, AccessToken = token.AccessToken, RefreshToken = token.RefreshToken, TokenExpiredTime = token.ExpiredDateTime }; bool IsAddeded = (new UserTokenRepository()).AddUserTokenIntoDB(userTokenMaster); if (IsAddeded) { token.Error = "Error Occurred while saving the Token into the DB"; } } return(token); }