@@ -27,11 +27,12 @@ public IActionResult Index()
2727 _settings . ClientId = _configuration [ "JDeere:ClientId" ] ;
2828 _settings . ClientSecret = _configuration [ "JDeere:ClientSecret" ] ;
2929 _settings . WellKnown = _configuration [ "JDeere:WellKnown" ] ;
30- _settings . CallbackUrl = _configuration [ "JDeere:CallbackUrl" ] ;
30+ _settings . ServerUrl = _configuration [ "JDeere:ServerUrl" ] ;
31+ _settings . CallbackUrl = _settings . ServerUrl + _configuration [ "JDeere:Callback" ] ;
3132 _settings . Scopes = _configuration [ "JDeere:Scopes" ] ;
3233 _settings . State = _configuration [ "JDeere:State" ] ;
3334 _settings . APIURL = _configuration [ "JDeere:ApiUrl" ] ;
34-
35+
3536 ViewBag . Settings = _settings ;
3637
3738 return View ( ) ;
@@ -87,6 +88,12 @@ public async Task<IActionResult> Callback(string code, string state)
8788 var responseContent = await response . Content . ReadAsStringAsync ( ) ;
8889 _settings . AccessToken = JsonConvert . DeserializeObject < Token > ( responseContent ) ;
8990
91+ string organizationAccessUrl = await NeedsOrganizationAccess ( ) ;
92+ if ( organizationAccessUrl != null )
93+ {
94+ return Redirect ( organizationAccessUrl ) ;
95+ }
96+
9097 ViewBag . Settings = _settings ;
9198
9299 return View ( "Index" ) ;
@@ -165,6 +172,36 @@ private async Task<HttpResponseMessage> SecuredApiGetRequest(string url)
165172
166173 return await client . GetAsync ( url ) ;
167174 }
175+
176+ /// <summary>Check to see if the 'connections' rel is present for any organization.
177+ /// If the rel is present it means the oauth application has not completed it's
178+ /// access to an organization and must redirect the user to the uri provided
179+ /// in the link.</summary>
180+ /// <returns>A redirect uri if the <code>connections</code>
181+ /// connections rel is present or <null> if no redirect is
182+ /// required to finish the setup.</returns>
183+ private async Task < string > NeedsOrganizationAccess ( )
184+ {
185+ var response = await SecuredApiGetRequest ( _settings . APIURL + "/organizations" ) ;
186+
187+ response . EnsureSuccessStatusCode ( ) ;
188+ var responseContent = await response . Content . ReadAsStringAsync ( ) ;
189+ var dynorg = JsonConvert . DeserializeObject < dynamic > ( responseContent ) ;
190+
191+ foreach ( var organization in dynorg . values )
192+ {
193+ foreach ( var link in organization . links )
194+ {
195+ string rel = link . rel ;
196+ if ( rel == "connections" )
197+ {
198+ string connectionsLink = link . uri ;
199+ return QueryHelpers . AddQueryString ( connectionsLink , "redirect_uri" , _settings . ServerUrl ) ;
200+ }
201+ }
202+ }
203+ return null ;
204+ }
168205 }
169206}
170207
0 commit comments