11import type { Params } from '@feathersjs/feathers'
2- import { AuthenticationService , JWTStrategy } from '@feathersjs/authentication'
2+ import { AuthenticationParams , AuthenticationRequest , AuthenticationService , JWTStrategy } from '@feathersjs/authentication'
3+ import { CloudAuthUser , createVerifier } from '@featherscloud/auth'
34import { LocalStrategy } from '@feathersjs/authentication-local'
45import { oauth , OAuthStrategy } from '@feathersjs/authentication-oauth'
56import type { OAuthProfile } from '@feathersjs/authentication-oauth'
67import type { Application } from './declarations'
8+ import { NotAuthenticated } from '@feathersjs/errors'
79
810declare module './declarations' {
911 interface ServiceTypes {
1012 authentication : AuthenticationService
1113 }
1214}
1315
16+ const verifier = createVerifier ( {
17+ appId : 'did:key:z6Mksc9d7DyrKFpyNcZHUy5G78vGFaFwdAuzJSBd9HHM9Msk' ,
18+ } )
19+
20+ class CloudAuthStrategy extends JWTStrategy {
21+ async findUser ( cloudUser : CloudAuthUser , params : AuthenticationParams ) {
22+ const result = await this . entityService . find ( {
23+ ...params ,
24+ query : {
25+ email : cloudUser . email
26+ }
27+ } )
28+ const [ user ] = Array . isArray ( result ) ? result : result . data ;
29+
30+ if ( ! user ) {
31+ return this . createUser ( cloudUser , params ) ;
32+ }
33+
34+ return user
35+ }
36+
37+ async createUser ( user : CloudAuthUser , params : AuthenticationParams ) {
38+ const entity = await this . entityService . create ( {
39+ email : user . email
40+ } , params ) ;
41+
42+ return entity ;
43+ }
44+
45+ async authenticate ( authentication : AuthenticationRequest , params : AuthenticationParams ) {
46+ const { accessToken } = authentication ;
47+ const { entity } = this . configuration ;
48+ if ( ! accessToken ) {
49+ throw new NotAuthenticated ( 'No access token' ) ;
50+ }
51+ const verified = await verifier . verify ( accessToken ) ;
52+ const result = {
53+ accessToken,
54+ authentication : {
55+ strategy : this . name || 'jwt' ,
56+ accessToken,
57+ ...verified
58+ }
59+ } ;
60+
61+ if ( entity === null || verified . user === null ) {
62+ return result ;
63+ }
64+
65+ return {
66+ ...result ,
67+ [ entity ] : await this . findUser ( verified . user , params )
68+ } ;
69+ }
70+ }
71+
1472class GitHubStrategy extends OAuthStrategy {
1573 async getEntityData ( profile : OAuthProfile , existing : any , params : Params ) {
1674 const baseData = await super . getEntityData ( profile , existing , params )
@@ -28,7 +86,7 @@ class GitHubStrategy extends OAuthStrategy {
2886export const authentication = ( app : Application ) => {
2987 const authentication = new AuthenticationService ( app )
3088
31- authentication . register ( 'jwt' , new JWTStrategy ( ) )
89+ authentication . register ( 'jwt' , new CloudAuthStrategy ( ) )
3290 authentication . register ( 'local' , new LocalStrategy ( ) )
3391 authentication . register ( 'github' , new GitHubStrategy ( ) )
3492
0 commit comments