public static async Task <HerokuAuthToken> QueryAccessToken(IQueryCollection parameters) { HerokuAuthToken authToken = null; try { var request = mFactory.CreateRequest(); request.Resource = "/oauth/token"; request.Method = Method.POST; request.AddObject(new { code = parameters["code"], client_id = ConfigVars.Instance.ClientId, client_secret = ConfigVars.Instance.ClientSecret, redirect_uri = ConfigVars.Instance.RedirectUri, grant_type = "authorization_code" }); var client = mFactory.CreateClient(); client.BaseUrl = ConfigVars.Instance.AuthServerBaseUrl; var httpResponse = await client.RestExecuteAsync(request); if (httpResponse != null && (httpResponse.StatusCode == HttpStatusCode.OK || httpResponse.StatusCode == HttpStatusCode.Created)) { authToken = (new RestSharp.Deserializers.JsonDeserializer()).Deserialize <HerokuAuthToken>(httpResponse); } } catch (Exception ex) { throw ex; } return(authToken); }
/// <summary> /// Method: Add /// Description: It is used to add new resource to resources table when provisioning the addon /// </summary> /// <param name="item"></param> public void Add(Resources item, int expiryInDays, bool isPrivatePlan, HerokuAuthToken authToken) { using (var transaction = _context.Database.BeginTransaction()) { try { //Get vendor app info Console.WriteLine("Get vendor app info starts"); var appInfo = HerokuApi.GetAppInfo(item.app_name, authToken.access_token); Console.WriteLine("Get vendor app info ended"); if (appInfo.IsNull()) { throw new ArgumentNullException("Main app info is null"); } item.app_name = appInfo.name; item.heroku_id = appInfo.id; if (!appInfo.owner.IsNull()) { item.user_email = appInfo.owner.email; } if (appInfo.organization.HasValue) { item.user_organization = appInfo.organization.Value.name; } if (!appInfo.region.IsNull()) { item.region = appInfo.region.name; } if (isPrivatePlan && (!appInfo.space.HasValue || (appInfo.space.HasValue && string.IsNullOrEmpty(appInfo.space.Value.name)))) { throw new Exception(string.Format("The {0} plan is not supported for the user account.", item.plan)); } //set plan expiry date based on plan configured in addon_plans.json which is in app root item.expired_at = DateTime.UtcNow.AddDays(expiryInDays); _context.Resources.Add(item); AuthTokens authTokens = authToken.ToAuthToken(); _context.AuthTokens.Add(authTokens); _context.SaveChanges(); transaction.Commit(); //Update addon app config-var if (!authToken.IsNull()) { var task = HerokuApi.UpdateVendorAppConfigVarByResourceId(item.uuid, authToken.access_token); task.Wait(); } } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); transaction.Rollback(); throw; } } }
/// <summary> /// Method: Add /// Description: It is used to add new resource to resources table when provisioning the addon /// </summary> /// <param name="item"></param> public void Add(Resources item, OauthGrant?oauthGrant) { using (var transaction = _context.Database.BeginTransaction()) { try { Console.WriteLine("Resource: " + JsonConvert.SerializeObject(item)); Console.WriteLine("Resource add starts"); _context.Resources.Add(item); Console.WriteLine("Resource add ended"); HerokuAuthToken authToken = default(HerokuAuthToken); if (oauthGrant.HasValue) { Console.WriteLine("Auth-Token get starts"); authToken = HerokuApi.GetAddonAccessTokenSync(oauthGrant.Value.code, oauthGrant.Value.type); if (!authToken.IsNull()) { Console.WriteLine("Auth-Token=> {0}:{1}", authToken.access_token, authToken.refresh_token); } else { throw new ArgumentNullException("Heroku access token not able to get"); } Console.WriteLine("Auth-Token get ended"); } else { Console.WriteLine("OAuth-Grant is null"); throw new ArgumentNullException("OAuth-Grant is null"); } authToken.auth_id = item.uuid; PartnerAuthTokens pAuthToken = authToken.ToPartnerAuthToken(); pAuthToken.oauth_code = oauthGrant.Value.code; pAuthToken.oauth_type = oauthGrant.Value.type; pAuthToken.oauth_expired_in = DateTime.Now.AddSeconds(280); Console.WriteLine("AuthToken: " + JsonConvert.SerializeObject(pAuthToken)); Console.WriteLine("AuthToken add starts"); _context.PartnerAuthTokens.Add(pAuthToken); Console.WriteLine("AuthToken add ended"); _context.SaveChanges(); transaction.Commit(); if (!authToken.IsNull()) { var task = HerokuApi.AddUpdateMainAppConfigByResourceId(item.uuid, authToken.access_token); task.Wait(); } } catch (Exception ex) { transaction.Rollback(); throw ex; } } }
public async Task <ActionResult> refreshtoken(string returnUrl = "") { Console.WriteLine("Login Controller- refreshtoken"); //Get heroku auth token HerokuAuthToken authToken = await HerokuApi.GetAddonAccessToken(HttpContext.GetClaimValue(Constants.HEROKU_REFRESH_TOKEN), AuthGrantType.refresh_token).ConfigureAwait(false); if (authToken.IsNull()) { return(RedirectToAction("herokuauth", "login", new { returnUrl = HttpUtility.UrlEncode(returnUrl) })); } else { //assign current resourceId as auth_id authToken.auth_id = HttpContext.GetClaimValue(ClaimTypes.NameIdentifier); //update heroku auth token var partnerAuthToken = authToken.ToPartnerAuthToken(); partnerAuthToken = _partnerAuthTokenRepository.Add(partnerAuthToken); if (partnerAuthToken.Resource != null) { var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, partnerAuthToken.Resource.uuid)); claims.Add(new Claim(ClaimTypes.Version, partnerAuthToken.Resource.plan.ToString())); claims.Add(new Claim(ClaimTypes.Country, partnerAuthToken.Resource.region)); if (!string.IsNullOrEmpty(partnerAuthToken.Resource.user_email)) { claims.Add(new Claim(Constants.HEROKU_USER_EMAIL, partnerAuthToken.Resource.user_email)); } if (!string.IsNullOrEmpty(partnerAuthToken.Resource.app_name)) { claims.Add(new Claim(Constants.HEROKU_MAIN_APP_NAME, partnerAuthToken.Resource.app_name)); } claims.Add(new Claim(Constants.HEROKU_ACCESS_TOKEN, partnerAuthToken.access_token)); claims.Add(new Claim(Constants.HEROKU_REFRESH_TOKEN, partnerAuthToken.refresh_token)); claims.Add(new Claim(Constants.HEROKU_AUTH_USERID, partnerAuthToken.user_id)); if (partnerAuthToken.expires_in.HasValue) { claims.Add(new Claim(Constants.HEROKU_TOKEN_EXPIREDIN, partnerAuthToken.expires_in.Value.ToString())); } HttpContext.AddUpdateClaims(claims); } } //redirect to url if (string.IsNullOrEmpty(returnUrl) || (!string.IsNullOrEmpty(returnUrl) && (returnUrl.Contains("localhost")) || !Uri.IsWellFormedUriString(returnUrl, UriKind.RelativeOrAbsolute))) { return(RedirectToAction("index", "home")); } else { //Redirect to home page return(Redirect(HttpUtility.UrlDecode(returnUrl))); } }
public static PartnerAuthTokens ToPartnerAuthToken(this HerokuAuthToken authToken) { if (authToken.IsNull()) { return(default(PartnerAuthTokens)); } return(new PartnerAuthTokens { auth_id = authToken.auth_id, access_token = authToken.access_token, expires_in = DateTime.Now.AddSeconds(authToken.expires_in - 120), refresh_token = authToken.refresh_token, token_type = authToken.token_type, user_id = authToken.user_id, session_nonce = authToken.session_nonce }); }
public async Task <ActionResult> Index(string returnUrl = "") { Console.WriteLine("Login Controller- Index"); string resourceId = HttpContext.GetClaimValue(ClaimTypes.NameIdentifier); if (string.IsNullOrEmpty(resourceId)) { TempData["httpStatusCode"] = HttpStatusCode.Unauthorized; TempData["errorMessage"] = "You are not authenticated due to heroku auth token not accessed."; return(RedirectToAction("forbidden", "home")); } HerokuAuthToken authToken = default(HerokuAuthToken); OauthGrant oathGrant = default(OauthGrant); var partnerAuthToken = _partnerAuthTokenRepository.Find(resourceId); if (partnerAuthToken == null || (partnerAuthToken != null && (partnerAuthToken.expires_in == DateTime.MinValue || (partnerAuthToken.expires_in != DateTime.MinValue && partnerAuthToken.expires_in?.AddSeconds(-300) < DateTime.Now)))) { oathGrant = await HerokuApi.GetOauthGrant(resourceId).ConfigureAwait(false); if (oathGrant.IsNull()) { TempData["httpStatusCode"] = HttpStatusCode.Unauthorized; TempData["errorMessage"] = "You are not authenticated due to heroku auth token not accessed."; return(RedirectToAction("forbidden", "home")); } //update heroku auth token partnerAuthToken = oathGrant.ToPartnerAuthToken(resourceId); partnerAuthToken = _partnerAuthTokenRepository.Add(partnerAuthToken); //Get heroku auth token authToken = await HerokuApi.GetAddonAccessToken(partnerAuthToken.oauth_code, partnerAuthToken.oauth_type).ConfigureAwait(false); if (authToken.IsNull()) { Response.StatusCode = (int)HttpStatusCode.Unauthorized; TempData["httpStatusCode"] = HttpStatusCode.Unauthorized; TempData["errorMessage"] = "You are not authenticated due to heroku auth token not received."; return(RedirectToAction("forbidden", "home")); } //assign current resourceId as auth_id authToken.auth_id = resourceId; partnerAuthToken = authToken.ToPartnerAuthToken(); if (partnerAuthToken != null) { //update heroku auth token partnerAuthToken = _partnerAuthTokenRepository.Add(partnerAuthToken); } } if (partnerAuthToken == null) { Response.StatusCode = (int)HttpStatusCode.Unauthorized; TempData["httpStatusCode"] = HttpStatusCode.Unauthorized; TempData["errorMessage"] = "You are not authenticated due to heroku auth token not received."; return(RedirectToAction("forbidden", "home")); } else if (partnerAuthToken.Resource != null) { var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, partnerAuthToken.Resource.uuid)); claims.Add(new Claim(ClaimTypes.Version, partnerAuthToken.Resource.plan.ToString())); claims.Add(new Claim(ClaimTypes.Country, partnerAuthToken.Resource.region)); if (!string.IsNullOrEmpty(partnerAuthToken.Resource.user_email)) { claims.Add(new Claim(Constants.HEROKU_USER_EMAIL, partnerAuthToken.Resource.user_email)); } if (!string.IsNullOrEmpty(partnerAuthToken.Resource.app_name)) { claims.Add(new Claim(Constants.HEROKU_MAIN_APP_NAME, partnerAuthToken.Resource.app_name)); } claims.Add(new Claim(Constants.HEROKU_ACCESS_TOKEN, partnerAuthToken.access_token)); claims.Add(new Claim(Constants.HEROKU_REFRESH_TOKEN, partnerAuthToken.refresh_token)); claims.Add(new Claim(Constants.HEROKU_AUTH_USERID, partnerAuthToken.user_id)); if (partnerAuthToken.expires_in.HasValue) { claims.Add(new Claim(Constants.HEROKU_TOKEN_EXPIREDIN, partnerAuthToken.expires_in.Value.ToString())); } HttpContext.AddUpdateClaims(claims); } //redirect to url if (string.IsNullOrEmpty(returnUrl) || (!string.IsNullOrEmpty(returnUrl) && (returnUrl.Contains("localhost")) || !Uri.IsWellFormedUriString(returnUrl, UriKind.RelativeOrAbsolute))) { return(RedirectToAction("index", "home")); } else { //Redirect to home page return(Redirect(HttpUtility.UrlDecode(returnUrl))); } }