@things-factory/auth-google 8.0.0-beta.9 → 8.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@things-factory/auth-google",
3
- "version": "8.0.0-beta.9",
3
+ "version": "8.0.2",
4
4
  "main": "dist-server/index.js",
5
5
  "browser": "dist-client/index.js",
6
6
  "things-factory": true,
@@ -27,13 +27,13 @@
27
27
  "migration:create": "node ../../node_modules/typeorm/cli.js migration:create ./server/migrations/migration"
28
28
  },
29
29
  "dependencies": {
30
- "@operato/graphql": "^8.0.0-beta",
31
- "@operato/shell": "^8.0.0-beta",
32
- "@things-factory/auth-base": "^8.0.0-beta.9",
33
- "@things-factory/shell": "^8.0.0-beta.9",
30
+ "@operato/graphql": "^8.0.0",
31
+ "@operato/shell": "^8.0.0",
32
+ "@things-factory/auth-base": "^8.0.2",
33
+ "@things-factory/shell": "^8.0.2",
34
34
  "googleapis": "^126.0.1",
35
35
  "passport": "^0.7.0",
36
36
  "passport-google-oauth20": "^2.0.0"
37
37
  },
38
- "gitHead": "86b1dfa26292926a2d5447fdc23bfa5a9e983245"
38
+ "gitHead": "39d60f56e142561233ddf6d47b539c637971357c"
39
39
  }
@@ -0,0 +1,22 @@
1
+ import { google } from 'googleapis'
2
+
3
+ import { AuthProvider } from '@things-factory/auth-base'
4
+
5
+ export async function getOauth2Client(authProvider: AuthProvider): Promise<any> {
6
+ try {
7
+ const { privateKey } = authProvider
8
+
9
+ const serviceAccount = JSON.parse(privateKey)
10
+
11
+ const client = new google.auth.JWT(serviceAccount.client_email, null, serviceAccount.private_key, [
12
+ 'https://www.googleapis.com/auth/admin.directory.user'
13
+ ])
14
+
15
+ await client.authorize()
16
+
17
+ return client
18
+ } catch (error) {
19
+ console.error('Error fetching oauth2 client:', error)
20
+ return null
21
+ }
22
+ }
@@ -0,0 +1,35 @@
1
+ import fetch from 'node-fetch'
2
+
3
+ import { getOauth2Client } from './get-oauth2-client'
4
+ import { AuthProvider } from '@things-factory/auth-base'
5
+
6
+ /* TODO Implement with google */
7
+ var clientState
8
+
9
+ export function getClientState() {
10
+ return clientState
11
+ }
12
+
13
+ export async function googleSubscriptions(authProvider: AuthProvider) {
14
+ const client = await getOauth2Client(authProvider)
15
+ // const expirationDateTime = new Date(Date.now() + 3 * 24 * 60 * 60 * 1000)
16
+
17
+ // clientState = `${authProvider.domainId}:${authProvider.id}` // TODO make secure
18
+
19
+ // const response = await fetch('https://graph.microsoft.com/v1.0/subscriptions', {
20
+ // method: 'POST',
21
+ // headers: {
22
+ // Authorization: `Bearer ${accessToken}`,
23
+ // 'Content-Type': 'application/json'
24
+ // },
25
+ // body: JSON.stringify({
26
+ // changeType: 'created,updated',
27
+ // notificationUrl: 'YOUR_WEBHOOK_ENDPOINT_BASE' + '/webhook/google-users',
28
+ // resource: '/users',
29
+ // expirationDateTime: expirationDateTime.toISOString() /* 최대 3일 이내, UTC 타임으로 설정 */,
30
+ // clientState
31
+ // })
32
+ // })
33
+
34
+ // const data = await response.json()
35
+ }
@@ -0,0 +1,156 @@
1
+ import fetch from 'node-fetch'
2
+ import { google } from 'googleapis'
3
+
4
+ import {
5
+ AuthProvider,
6
+ User,
7
+ UserStatus,
8
+ UsersAuthProviders,
9
+ encryptState,
10
+ decryptState
11
+ } from '@things-factory/auth-base'
12
+ import { config } from '@things-factory/env'
13
+ import { getOauth2Client } from './get-oauth2-client'
14
+
15
+ export async function syncAllUserInfo(authProvider: AuthProvider, context: ResolverContext) {
16
+ const oauth2Client = await getOauth2Client(authProvider)
17
+
18
+ const service = google.admin({ version: 'directory_v1', auth: oauth2Client })
19
+
20
+ const res = await service.users.list({
21
+ customer: 'my_customer' /* 'my_customer'는 G Suite 도메인의 모든 사용자를 나타내는 특수 문자열입니다 */,
22
+ maxResults: 10,
23
+ orderBy: 'email'
24
+ })
25
+
26
+ const users = res.data.users
27
+
28
+ if (users && users.length) {
29
+ for (const user of users) {
30
+ await updateUserInfo(authProvider, user, context)
31
+ }
32
+ } else {
33
+ console.log('No users found.')
34
+ }
35
+ }
36
+
37
+ export async function updateUserInfo(authProvider: AuthProvider, userInfo, context: ResolverContext) {
38
+ const { tx, domain, user } = context.state
39
+
40
+ // {
41
+ // "kind": "admin#directory#user",
42
+ // "id": "user's unique ID",
43
+ // "etag": "etag of this resource",
44
+ // "primaryEmail": "user@example.com",
45
+ // "name": {
46
+ // "givenName": "First",
47
+ // "familyName": "Last",
48
+ // "fullName": "First Last"
49
+ // },
50
+ // "isAdmin": false,
51
+ // "isDelegatedAdmin": false,
52
+ // "lastLoginTime": "2021-04-05T12:07:41.000Z",
53
+ // "creationTime": "2017-05-26T10:57:00.000Z",
54
+ // "agreedToTerms": true,
55
+ // "suspended": false,
56
+ // "archived": false,
57
+ // "changePasswordAtNextLogin": false,
58
+ // "ipWhitelisted": false,
59
+ // "emails": [
60
+ // {
61
+ // "address": "user@example.com",
62
+ // "type": "work",
63
+ // "customType": "",
64
+ // "primary": true
65
+ // }
66
+ // ],
67
+ // "organizations": [
68
+ // {
69
+ // "name": "Department Name",
70
+ // "title": "Job Title",
71
+ // "type": "work",
72
+ // "primary": true
73
+ // }
74
+ // ],
75
+ // "phones": [
76
+ // {
77
+ // "value": "+1 xxx-xxx-xxxx",
78
+ // "type": "work",
79
+ // "primary": true
80
+ // }
81
+ // ],
82
+ // "aliases": ["alias@example.com"],
83
+ // // ... 다른 필드들
84
+ // }
85
+ const { id, name, primaryEmail } = userInfo
86
+
87
+ const repository = tx.getRepository(User)
88
+
89
+ // 1. 사용자를 찾는다.(email 정보로)
90
+ const existingUser = await repository.findOne({
91
+ where: { email: primaryEmail },
92
+ relations: ['domains']
93
+ })
94
+
95
+ if (!existingUser) {
96
+ // 2. 사용자가 없다면, 생성한다.
97
+ const salt = User.generateSalt()
98
+
99
+ /* normally they don't login with this password. */
100
+ const password = salt
101
+
102
+ const createdUser = await repository.save({
103
+ id,
104
+ name: name.fullName,
105
+ email: primaryEmail,
106
+ creator: user,
107
+ updater: user,
108
+ domains: domain ? [domain] : [],
109
+ roles: [],
110
+ salt,
111
+ userType: 'user',
112
+ // locale: preferredLanguage,
113
+ status: UserStatus.ACTIVATED,
114
+ passwordUpdatedAt: new Date(),
115
+ password: User.encode(password, salt)
116
+ })
117
+
118
+ await tx.getRepository(UsersAuthProviders).save({
119
+ domain,
120
+ user: createdUser,
121
+ authProvider,
122
+ ssoId: id
123
+ })
124
+
125
+ return createdUser
126
+ } else {
127
+ // 3. 사용자가 있다면, 업데이트한다.
128
+ const { domains } = existingUser
129
+
130
+ if (!domains.find(existing => existing.id == domain.id)) {
131
+ domains.push(domain)
132
+ }
133
+
134
+ const updatedUser = await repository.save({
135
+ ...existingUser,
136
+ name: name.fullName,
137
+ domains,
138
+ // locale: preferredLanguage,
139
+ updater: user
140
+ })
141
+
142
+ const usersAuthProviders = await tx.getRepository(UsersAuthProviders).findOne({
143
+ where: { domain: { id: domain.id }, user: { id: updatedUser.id }, authProvider: { id: authProvider.id } }
144
+ })
145
+
146
+ await tx.getRepository(UsersAuthProviders).save({
147
+ ...usersAuthProviders,
148
+ domain,
149
+ user: updatedUser,
150
+ authProvider,
151
+ ssoId: id
152
+ })
153
+
154
+ return updatedUser
155
+ }
156
+ }
@@ -0,0 +1,18 @@
1
+ export * from './middlewares'
2
+ export * from './service'
3
+
4
+ import './routes'
5
+
6
+ import { AuthProvider } from '@things-factory/auth-base'
7
+ import { syncAllUserInfo } from './controllers/sync-user-info'
8
+
9
+ AuthProvider.register('google', {
10
+ type: 'google',
11
+ description: 'Authentication Provider for Google',
12
+ help: '',
13
+ parameterSpec: null,
14
+ async synchronizeUsers(authProvider: AuthProvider, context: ResolverContext): Promise<boolean> {
15
+ await syncAllUserInfo(authProvider, context)
16
+ return true
17
+ }
18
+ })
@@ -0,0 +1,78 @@
1
+ import passport from 'koa-passport'
2
+ import { Strategy as GoogleStrategy } from 'passport-google-oauth20'
3
+
4
+ import { config } from '@things-factory/env'
5
+ import { User } from '@things-factory/auth-base'
6
+
7
+ const SSOGoogleConfig = config.get('sso/google/config')
8
+
9
+ if (SSOGoogleConfig) {
10
+ passport.use(
11
+ new GoogleStrategy(
12
+ {
13
+ ...SSOGoogleConfig,
14
+ scope: ['profile', 'https://www.googleapis.com/auth/userinfo.email']
15
+ },
16
+ async (token, tokenSecret, profile, done) => {
17
+ if (!profile) {
18
+ return done(new Error('No profile found'), null)
19
+ }
20
+
21
+ try {
22
+ const { emails, photos } = profile
23
+ const email = emails?.[0].value
24
+ const photo = photos?.[0].value
25
+
26
+ const user = await User.checkAuthWithEmail({ email })
27
+
28
+ const { id, userType, status } = user
29
+
30
+ return done(null, {
31
+ id,
32
+ userType,
33
+ status
34
+ })
35
+ } catch (error) {
36
+ return done(error)
37
+ }
38
+ }
39
+ )
40
+ )
41
+ }
42
+
43
+ export async function authGoogleMiddleware(context, next) {
44
+ const { path } = context
45
+ const { user } = context.state
46
+
47
+ if (user) {
48
+ return await next()
49
+ }
50
+
51
+ await passport.authenticate('google', {
52
+ failureRedirect: '/auth/signin',
53
+ successRedirect: '/auth/checkin'
54
+ })(context, next)
55
+ }
56
+
57
+ export async function googleSubscriptionMiddleware(context, next) {
58
+ const { path } = context
59
+ const { user } = context.state
60
+
61
+ if (user) {
62
+ return await next()
63
+ }
64
+
65
+ await passport.authenticate('google', {
66
+ failureRedirect: '/auth/signin',
67
+ successRedirect: '/auth/checkin'
68
+ })(context)
69
+
70
+ /* 다음은, websocket 에서 인증을 처리하기 위한 작업임. */
71
+ const passportObject = context.session?.passport
72
+ if (passportObject) {
73
+ const userEntity = await User.checkAuth(passportObject?.user)
74
+ context.state.user = userEntity
75
+ }
76
+
77
+ return await next()
78
+ }
@@ -0,0 +1,13 @@
1
+ import { config } from '@things-factory/env'
2
+
3
+ const SSOGoogleConfig = config.get('sso/google/config')
4
+
5
+ import { googleSubscriptionMiddleware } from './google-authenticate-middleware'
6
+
7
+ if (SSOGoogleConfig) {
8
+ process.on('bootstrap-module-subscription' as any, (app, subscriptionMiddleware) => {
9
+ subscriptionMiddleware.unshift(googleSubscriptionMiddleware)
10
+ })
11
+ }
12
+
13
+ export * from './google-authenticate-middleware'
@@ -0,0 +1,16 @@
1
+ import Router from 'koa-router'
2
+
3
+ import passport from 'koa-passport'
4
+ import { authGoogleMiddleware } from '../middlewares'
5
+
6
+ import { encryptState, decryptState } from '@things-factory/auth-base'
7
+
8
+ export const authGoogleRouter = new Router()
9
+
10
+ authGoogleRouter.get(
11
+ '/auth/callback-auth-google',
12
+ passport.authenticate('google', { failureRedirect: '/auth/signin', successRedirect: '/auth/checkin' }),
13
+ ctx => {
14
+ ctx.redirect('/auth/checkin')
15
+ }
16
+ )
@@ -0,0 +1,97 @@
1
+ import Router from 'koa-router'
2
+ import fetch from 'node-fetch'
3
+
4
+ import { getRepository, getDataSource } from '@things-factory/shell'
5
+
6
+ import { updateUserInfo } from '../controllers/sync-user-info'
7
+ import { getOauth2Client } from '../controllers/get-oauth2-client'
8
+ import { AuthProvider } from '@things-factory/auth-base'
9
+
10
+ export const authGoogleWebhookRouter = new Router()
11
+
12
+ // Microsoft Graph에서 발송되는 알림을 처리하기 위한 타입 정의
13
+ // TODO implement with google
14
+ // interface Notification {
15
+ // resourceData: {
16
+ // id: string
17
+ // }
18
+ // }
19
+
20
+ authGoogleWebhookRouter.post('/webhook/google-users', async context => {
21
+ const notifications: Notification[] = context.request.body.value
22
+ const clientState = context.request.body.clientState
23
+ const [domainId, authProviderId] = clientState?.split(':') || []
24
+
25
+ if (!domainId || !authProviderId) {
26
+ context.status = 401 // unauthorized
27
+ context.body = 'Invalid ClientState'
28
+ return
29
+ }
30
+
31
+ await getDataSource('tx').transaction(async tx => {
32
+ const wrap = context.app.createContext(context.req || {}, context.res || {})
33
+
34
+ wrap.state = {
35
+ ...context.state,
36
+ domain: null,
37
+ tx
38
+ }
39
+ wrap.t = context.t
40
+
41
+ const authProvider = await tx.getRepository(AuthProvider).findOne({
42
+ where: {
43
+ domain: { id: domainId },
44
+ id: authProviderId
45
+ }
46
+ })
47
+
48
+ if (!authProvider) {
49
+ context.status = 401 // unauthorized
50
+ context.body = 'Invalid ClientState'
51
+ return
52
+ }
53
+
54
+ const oauth2Client = await getOauth2Client(authProvider)
55
+
56
+ // for (const notification of notifications) {
57
+ // const userId = notification.resourceData.id
58
+
59
+ // try {
60
+ // const userResponse = await fetch(`https://graph.microsoft.com/v1.0/users/${userId}`, {
61
+ // headers: {
62
+ // Authorization: `Bearer ${accessToken}`
63
+ // }
64
+ // })
65
+
66
+ // if (!userResponse.ok) {
67
+ // throw new Error(`Failed to fetch user data: ${userResponse.statusText}`)
68
+ // }
69
+
70
+ // const userInfo = await userResponse.json()
71
+
72
+ // // {
73
+ // // "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
74
+ // // "businessPhones": ["+1 412 555 0109"],
75
+ // // "displayName": "Megan Bowen",
76
+ // // "givenName": "Megan",
77
+ // // "jobTitle": "Auditor",
78
+ // // "mail": "MeganB@M365x214355.onmicrosoft.com",
79
+ // // "mobilePhone": "+1 412 555 0109",
80
+ // // "officeLocation": "12/1110",
81
+ // // "preferredLanguage": "en-US",
82
+ // // "surname": "Bowen",
83
+ // // "userPrincipalName": "MeganB@M365x214355.onmicrosoft.com",
84
+ // // "id": "48d31887-5fad-4d73-a9f5-3c356e68a038"
85
+ // // }
86
+
87
+ // // webhook 호출로부터 호출한 tenant를 알 수 있다면, 매핑된 도메인 정보를 포함할 수 있을 것 같은데..
88
+
89
+ // await updateUserInfo(authProvider, userInfo, wrap)
90
+ // } catch (error) {
91
+ // console.error('Error fetching user data from Microsoft Graph:', error)
92
+ // }
93
+ // }
94
+ })
95
+
96
+ context.status = 202
97
+ })
@@ -0,0 +1,2 @@
1
+ export * from './auth-google-router'
2
+ export * from './auth-google-webhook-router'
@@ -0,0 +1,28 @@
1
+ import passport from 'koa-passport'
2
+ import { config } from '@things-factory/env'
3
+ import { setAccessTokenCookie } from '@things-factory/auth-base'
4
+
5
+ const SSOGoogleConfig = config.get('sso/google/config')
6
+
7
+ import { authGoogleMiddleware } from './middlewares'
8
+ import { authGoogleRouter, authGoogleWebhookRouter } from './router'
9
+
10
+ if (SSOGoogleConfig) {
11
+ process.on('bootstrap-collect-sso-middleware' as any, (_, ssoMiddlewares) => {
12
+ ssoMiddlewares.push(authGoogleMiddleware)
13
+ })
14
+
15
+ process.on('bootstrap-module-domain-public-route' as any, (app, domainPublicRouter) => {
16
+ domainPublicRouter.use(authGoogleRouter.routes(), authGoogleRouter.allowedMethods())
17
+ domainPublicRouter.use(authGoogleWebhookRouter.routes(), authGoogleWebhookRouter.allowedMethods())
18
+ })
19
+
20
+ process.on('bootstrap-module-global-public-route' as any, (app, globalPublicRouter) => {
21
+ globalPublicRouter.get(
22
+ '/auth/signin-with-google',
23
+ passport.authenticate('google', {
24
+ scope: ['profile', 'https://www.googleapis.com/auth/userinfo.email']
25
+ })
26
+ )
27
+ })
28
+ }
@@ -0,0 +1,24 @@
1
+ import { Resolver, Mutation, Arg, Ctx, Directive } from 'type-graphql'
2
+
3
+ import { syncAllUserInfo } from '../../controllers/sync-user-info'
4
+
5
+ @Resolver()
6
+ export class AuthGoogleMutation {
7
+ // @Directive('@transaction')
8
+ // @Directive('@privilege(superUserGranted:true)')
9
+ // @Mutation(returns => Boolean, { description: 'To synchronize google users' })
10
+ // async synchronizeGoogleUsers(@Ctx() context: ResolverContext): Promise<boolean> {
11
+ // syncAllUserInfo(context)
12
+
13
+ // return true
14
+ // }
15
+
16
+ @Directive('@transaction')
17
+ @Directive('@privilege(superUserGranted:true)')
18
+ @Mutation(returns => Boolean, { description: 'To subscribe google users' })
19
+ async subscribeGoogleUsers(@Ctx() context: ResolverContext): Promise<boolean> {
20
+ const { domain, user, tx } = context.state
21
+
22
+ return true
23
+ }
24
+ }
@@ -0,0 +1,3 @@
1
+ import { AuthGoogleMutation } from './auth-google-mutation'
2
+
3
+ export const resolvers = [AuthGoogleMutation]
@@ -0,0 +1,19 @@
1
+ /* EXPORT ENTITY TYPES */
2
+
3
+ /* IMPORT ENTITIES AND RESOLVERS */
4
+ import { resolvers as AuthGoogleResolvers } from './auth-google'
5
+
6
+ export const entities = [
7
+ /* ENTITIES */
8
+ ]
9
+
10
+ export const subscribers = [
11
+ /* SUBSCRIBERS */
12
+ ]
13
+
14
+ export const schema = {
15
+ resolverClasses: [
16
+ /* RESOLVER CLASSES */
17
+ ...AuthGoogleResolvers
18
+ ]
19
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "../../tsconfig-base.json",
3
+ "compilerOptions": {
4
+ "strict": false,
5
+ "module": "commonjs",
6
+ "outDir": "../dist-server",
7
+ "baseUrl": "./"
8
+ },
9
+ "include": ["./**/*"]
10
+ }