@@ -257,6 +257,43 @@ describe("auth", function () {
257
257
expect ( res . headers [ "set-cookie" ] [ 1 ] ) . to . include ( "SameSite=Lax" ) ;
258
258
} ) ;
259
259
260
+ it ( "should redirect to the correct URL and update user email when GitHub API returns primary email" , async function ( ) {
261
+ // Define a fake GitHub API response for user emails (primary email)
262
+ const rdsUrl = new URL ( config . get ( "services.rdsUi.baseUrl" ) ) . href ;
263
+ const fakeEmails = [
264
+ { primary :
true , email :
"[email protected] " } ,
265
+ { primary :
false , email :
"[email protected] " } ,
266
+ ] ;
267
+
268
+ // Stub fetch to resolve with the fake email response
269
+ const fetchStub = sinon . stub ( global , "fetch" ) . resolves ( new Response ( JSON . stringify ( fakeEmails ) ) ) ;
270
+
271
+ // Stub passport.authenticate to simulate a successful authentication
272
+ sinon . stub ( passport , "authenticate" ) . callsFake ( ( strategy , options , callback ) => {
273
+ callback ( null , "accessToken" , {
274
+ username : "github-user" ,
275
+ displayName : "GitHub User" ,
276
+ _json : { email : null , created_at : "2022-01-01" } ,
277
+ id : 12345 ,
278
+ } ) ;
279
+ return ( req , res , next ) => { } ;
280
+ } ) ;
281
+
282
+ const res = await chai
283
+ . request ( app )
284
+ . get ( `/auth/github/callback` )
285
+ . query ( { code : "codeReturnedByGithub" , state : rdsUrl } )
286
+ . redirects ( 0 ) ;
287
+ expect ( res ) . to . have . status ( 302 ) ;
288
+
289
+ // Verify that the fetch function was called with the correct GitHub API URL
290
+ const fetchArgs = fetchStub . getCall ( 0 ) . args ;
291
+ expect ( fetchArgs [ 0 ] ) . to . equal ( "https://api.github.com/user/emails" ) ;
292
+ expect ( fetchArgs [ 1 ] . headers . Authorization ) . to . equal ( "token accessToken" ) ; // Ensure the token is passed correctly
293
+ // Check if the user data was updated with the primary email returned by GitHub API
294
+ // expect(userData.email).to.equal('[email protected] '); // Make sure the email was updated from the API response
295
+ } ) ;
296
+
260
297
it ( "should return google call back URL" , async function ( ) {
261
298
const googleOauthURL = generateGoogleAuthRedirectUrl ( { } ) ;
262
299
const res = await chai . request ( app ) . get ( "/auth/google/login" ) . redirects ( 0 ) ;
@@ -408,11 +445,7 @@ describe("auth", function () {
408
445
409
446
expect ( res ) . to . have . status ( 401 ) ;
410
447
expect ( res . body ) . to . be . an ( "object" ) ;
411
- expect ( res . body ) . to . eql ( {
412
- statusCode : 401 ,
413
- error : "Unauthorized" ,
414
- message : "User cannot be authenticated" ,
415
- } ) ;
448
+ expect ( res . body . message ) . to . equal ( "User cannot be authenticated" ) ;
416
449
417
450
return done ( ) ;
418
451
} ) ;
0 commit comments