1
+ import { Octokit } from "@octokit/core" ;
2
+ import type { Account } from 'next-auth'
3
+
4
+ const getOrgs = async ( accessToken : string ) => {
5
+ const octokit = new Octokit ( { auth : accessToken } ) ;
6
+ const { data} = await octokit . request ( 'GET /user/orgs' , {
7
+ headers : {
8
+ 'X-GitHub-Api-Version' : '2022-11-28'
9
+ }
10
+ } )
11
+
12
+ return data ;
13
+ }
14
+
15
+ /**
16
+ * Check if user is in org
17
+ * @param allowedOrgs
18
+ * @param email
19
+ * @param account
20
+ */
21
+ export const isUserInOrg = async ( allowedOrgs : string [ ] , email : string | null , account : Account | null ) => {
22
+ try {
23
+ if ( account && account . access_token ) {
24
+ const data = await getOrgs ( account . access_token ) ;
25
+ if ( data ) {
26
+ const orgs = data . map ( ( org : any ) => org . login ) ;
27
+ if ( orgs . some ( ( org ) => allowedOrgs . includes ( org ) ) ) {
28
+ return true ;
29
+ }
30
+ }
31
+ }
32
+ } catch ( e ) {
33
+ console . log ( e ) ;
34
+ }
35
+ return false ;
36
+ }
37
+
38
+ export type WhiteListedEmail = {
39
+ email : string ;
40
+ }
41
+
42
+ /**
43
+ * Check if user is whitelisted
44
+ * @param emails
45
+ * @param email
46
+ */
47
+ export const isWhitelisted = async ( emails : WhiteListedEmail [ ] , email : string | null ) => {
48
+ try {
49
+ if ( email && emails . find ( ( w ) => w . email === email ) ) {
50
+ return true ;
51
+ }
52
+ } catch ( e ) {
53
+ console . log ( e ) ;
54
+ }
55
+ return false ;
56
+ }
57
+
58
+ /**
59
+ * Check if user is allowed to access the page
60
+ * @param allowedOrgs
61
+ * @param emails
62
+ * @param email
63
+ * @param account
64
+ */
65
+ export const isUserAllowed = async ( allowedOrgs : string [ ] , emails : WhiteListedEmail [ ] , email : string | null , account : Account | null ) => {
66
+ const isInOrg = await isUserInOrg ( allowedOrgs , email , account ) ;
67
+ const whitelisted = await isWhitelisted ( emails , email ) ;
68
+
69
+ return isInOrg || whitelisted ;
70
+ }
0 commit comments