Class: AuthingRuby::AuthenticationClient

Inherits:
Object
  • Object
show all
Defined in:
lib/authing_ruby/authentication/AuthenticationClient.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ AuthenticationClient

Returns a new instance of AuthenticationClient.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 9

def initialize(options = {})
  @options = options

  @appId = options.fetch(:appId, nil) # 应用 ID
  @secret = options.fetch(:secret, nil) # 应用密钥
  @appHost = options.fetch(:appHost, nil) # 该应用的域名
  @redirectUri = options.fetch(:redirectUri, nil) # 业务回调地址
  @protocol = options.fetch(:protocol, 'oidc') # 协议类型,可选值为 oidc、oauth、saml、cas

  # 公钥加密
  @publicKeyManager = AuthingRuby::Common::PublicKeyManager.new(options)

  # 负责发送 GraphQL (其实就是 http) 请求的工具
  graphqlEndpoint = "#{@appHost}/graphql/v2"
  @graphqlClient = AuthingRuby::Common::GraphqlClient.new(graphqlEndpoint, @options)
  
  # tokenProvider 只是存取一下 user 和 token
  @tokenProvider = Authentication::AuthenticationTokenProvider.new()

  @httpClient = AuthingRuby::Common::HttpClient.new(options, @tokenProvider)
  @naiveHttpClient = AuthingRuby::Common::NaiveHttpClient.new(options, @tokenProvider)

  # 把 GraphQL 文件夹路径放这里, 这些是私有变量
  @folder_graphql = "./lib/graphql"
  @folder_graphql_mutation = "#{@folder_graphql}/mutations"
  @folder_graphql_query = "#{@folder_graphql}/queries"

  @baseClient = Authentication::BaseAuthenticationClient.new(options)

  # 以下几个参数主要用于 "标准协议认证模块"
  @tokenEndPointAuthMethod = options.fetch(:tokenEndPointAuthMethod, 'client_secret_post')
  @introspectionEndPointAuthMethod = options.fetch(:introspectionEndPointAuthMethod, 'client_secret_post')
  @revocationEndPointAuthMethod = options.fetch(:revocationEndPointAuthMethod, 'client_secret_post')
end

Instance Method Details

#_buildOidcAuthorizeUrl(options = {}) ⇒ Object

私有函数,用于 buildAuthorizeUrl 处理 OIDC 协议写法是完全参照的 JS SDK



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 306

def _buildOidcAuthorizeUrl(options = {})
  # 名字的映射
  map = {
    appId: 'client_id',
    scope: 'scope',
    state: 'state',
    nonce: 'nonce',
    responseMode: 'response_mode',
    responseType: 'response_type',
    redirectUri: 'redirect_uri',
    codeChallenge: 'code_challenge',
    codeChallengeMethod: 'code_challenge_method'
  };
  # 用来构造 url
  res = {
    nonce: AuthingRuby::Utils.randomNumberString(16),
    state: AuthingRuby::Utils.randomNumberString(16),
    scope: 'openid profile email phone address',
    client_id: @appId,
    redirect_uri: @redirectUri,
    response_type: 'code',
  };

  map.each do |key, value|
    if options[key.to_sym]
      # 如果 scope 的值里有 offline_access
      if value == 'scope' && options.fetch(:scope, []).split(' ').include?("offline_access")
        res[:prompt] = 'consent'
      end
      res[value.to_sym] = options[key]
    end
  end

  authorizeUrl = @baseClient.appHost + '/oidc/auth?' + URI::QueryParams.dump(res)
  return authorizeUrl
end

#_generateTokenRequest(params) ⇒ Object

逻辑参照 JS SDK 目的: 把 params 这个 hash 里 value 为空的值全部删掉最后返回一个 url params 字符串



370
371
372
373
374
375
376
377
378
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 370

def _generateTokenRequest(params)
  ret = {}
  params.each do |key, value|
    if value
      ret[key] = value
    end
  end
  return URI::QueryParams.dump(ret)
end

#_getAccessTokenByCodeWithClientSecretPost(code, options = {}) ⇒ Object



380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 380

def _getAccessTokenByCodeWithClientSecretPost(code, options = {})
  codeVerifier = options.fetch(:codeVerifier, nil)
  qstr = _generateTokenRequest({
    client_id: @appId,
    client_secret: @secret,
    grant_type: 'authorization_code',
    code: code,
    redirect_uri: @redirectUri,
    code_verifier: codeVerifier,
  })

  api = ''
  if @protocol == 'oidc'
    api = "#{@baseClient.appHost}/oidc/token"
  elsif @protocol == 'oauth'
    api = "#{@baseClient.appHost}/oauth/token"
  end
  tokenSet = @naiveHttpClient.request({
    method: 'POST',
    url: api,
    data: qstr,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
  return tokenSet
end

#_getNewAccessTokenByRefreshTokenWithClientSecretPost(refreshToken) ⇒ Object



459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 459

def _getNewAccessTokenByRefreshTokenWithClientSecretPost(refreshToken)
    qstr = _generateTokenRequest({
      client_id: @appId,
      client_secret: @secret,
      grant_type: 'refresh_token',
      refresh_token: refreshToken
    });

    api = ''
    if @protocol == 'oidc'
      api = "#{@baseClient.appHost}/oidc/token"
    elsif @protocol == 'oauth'
      api = "#{@baseClient.appHost}/oauth/token"
    end

    tokenSet = @naiveHttpClient.request({
      method: 'POST',
      url: api,
      data: qstr,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    return tokenSet;
end

#_introspectTokenWithClientSecretPost(token) ⇒ Object



513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 513

def _introspectTokenWithClientSecretPost(token)
  qstr = _generateTokenRequest({
    client_id: @appId,
    client_secret: @secret,
    token: token,
  })
  api = ''
  if @protocol == 'oidc'
    api = "#{@baseClient.appHost}/oidc/token/introspection"
  elsif @protocol == 'oauth'
    api = "#{@baseClient.appHost}/oauth/token/introspection"
  end
  tokenSet = @naiveHttpClient.request({
    method: 'POST',
    url: api,
    data: qstr,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  });
  return tokenSet;
end

#_revokeTokenWithClientSecretPost(token) ⇒ Object



752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 752

def _revokeTokenWithClientSecretPost(token)
  qstr = _generateTokenRequest({
    client_id: @appId,
    client_secret: @secret,
    token: token,
  });
  api = '';
  if @protocol === 'oidc'
    api = "#{@baseClient.appHost}/oidc/token/revocation";
  elsif @protocol === 'oauth'
    api = "#{@baseClient.appHost}/oauth/token/revocation";
  end
  tokenSet = @naiveHttpClient.request({
    method: 'POST',
    url: api,
    data: qstr,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  });
  return tokenSet;
end

#bindPhone(phone, phoneCode) ⇒ Object

绑定手机号用户初次绑定手机号,如果需要修改手机号请使用 updatePhone 方法。如果该手机号已被绑定,将会绑定失败。发送验证码请使用 sendSmsCode 方法。



690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 690

def bindPhone(phone, phoneCode)
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  variables = {
    "phone": phone,
    "phoneCode": phoneCode,
  }
  res = graphqlAPI.bindPhone(@graphqlClient, @tokenProvider, variables)
  json = JSON.parse(res)
  user = json.dig("data", "bindPhone")
  if user
    setCurrentUser(user);
    return user;
  else
    return json
  end
end

#buildAuthorizeUrl(options = {}) ⇒ Object



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 347

def buildAuthorizeUrl(options = {})
  unless @appHost
    raise '请在初始化 AuthenticationClient 时传入应用域名 appHost 参数,形如:https://app1.authing.cn'
  end
  protocol = @options.fetch(:protocol, nil)
  if protocol == 'oidc'
    return _buildOidcAuthorizeUrl(options);
  end
  if protocol == 'oauth'
    throw "oauth 协议暂未实现"
  end
  if protocol == 'saml'
    throw "saml 协议暂未实现"
  end
  if protocol == 'cas'
    throw "cas 协议暂未实现"
  end
  raise '不支持的协议类型,请在初始化 AuthenticationClient 时传入 protocol 参数,可选值为 oidc、oauth、saml、cas'
end

#checkLoggedInObject

checkLoggedIn 解释: 如果登录了,会返回唯一 id (userId) 如果没登录,会抛出错误



624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 624

def checkLoggedIn()
  # 有 user 就直接返回 id
  user = @tokenProvider.getUser()
  if user
    return user.fetch("id", nil) # 608966b08b4af522620d2e59
  end
  
  # 尝试获取 token
  token = @tokenProvider.getToken()
  if !token
    raise '请先登录!' # 例子: 如果 logout 了再次调用 checkLoggedIn 会报错,就是这里报错
  end

  # 解码 token
  decoded_token_array = JWT.decode token, nil, false
  payload = decoded_token_array[0]

  # 从 token 中获取 user_id 并返回
  userId = nil
  authing_sub = payload.fetch("sub", nil)
  id = payload.dig("data", "id")

  if authing_sub
    userId = authing_sub
  else
    userId = id
  end

  return userId
end

#checkLoginStatus(token) ⇒ Object

检测 Token 登录状态



665
666
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 665

def checkLoginStatus
end

#checkPasswordStrength(password) ⇒ Object

检查密码强度



656
657
658
659
660
661
662
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 656

def checkPasswordStrength(password)
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  variables = { "password": password }
  res = graphqlAPI.checkPasswordStrength(@graphqlClient, @tokenProvider, variables)
  json = JSON.parse(res)
  return json.dig("data", "checkPasswordStrength")
end

#generateCodeChallengeObject



725
726
727
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 725

def generateCodeChallenge()
  return AuthingRuby::Utils.generateRandomString(43);
end

#getAccessTokenByCode(code, options = {}) ⇒ Object

Code 换 Token 使用授权码 Code 获取用户的 Token 信息。res = a.getAccessTokenByCode(‘授权码 code’); 参照: github.com/Authing/authing.js/blob/cf4757d09de3b44c3c3f4509ae8c8715c9f302a2/src/lib/authentication/AuthenticationClient.ts#L1977



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 412

def getAccessTokenByCode(code, options = {})
  # 检查参数合法性
  if ['oauth', 'oidc'].include?(@protocol) == false
    raise '初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc,请检查参数'
  end
  if !@secret && @tokenEndPointAuthMethod != nil
    raise '请在初始化 AuthenticationClient 时传入 appId 和 secret 参数'
  end

  if @tokenEndPointAuthMethod == 'client_secret_post'
    return _getAccessTokenByCodeWithClientSecretPost(code, options)
  end

  if @tokenEndPointAuthMethod == 'client_secret_basic'
    # TODO
    raise "client_secret_basic 还未实现"
    # return _getAccessTokenByCodeWithClientSecretBasic(code, options.fetch(:codeVerifier, nil))
  end

  if @tokenEndPointAuthMethod == nil
    # TODO
    raise "还未实现"
    # return _getAccessTokenByCodeWithNone(code, options.fetch(:codeVerifier, nil))
  end
end

#getCodeChallengeDigest(options = {}) ⇒ Object

照搬 JS SDK 的逻辑



730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 730

def getCodeChallengeDigest(options = {})
  if options.empty?
    raise '请提供 options 参数,options.codeChallenge 为一个长度大于等于 43 的字符串,options.method 可选值为 S256、plain'
  end
  codeChallenge = options.fetch(:codeChallenge, nil)
  method = options.fetch(:method, 'S256')

  if codeChallenge == nil
    raise '请提供 options.codeChallenge,值为一个长度大于等于 43 的字符串'
  end

  if method == 'S256'
    base64 = Digest::SHA256.base64digest codeChallenge
    result = base64.gsub(/\+/, '-').gsub(/\//, '-').gsub(/=/, '')
    return result
  end
  if method == 'plain'
    return options.codeChallenge;
  end
  raise '不支持的 options.method,可选值为 S256、plain'
end

#getCurrentUserObject

获取当前登录的用户信息返回:用户信息



273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 273

def getCurrentUser()
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  res = graphqlAPI.getCurrentUser(@graphqlClient, @tokenProvider, variables)
  json = JSON.parse(res)
  user = json.dig("data", "user")
  if user
    setCurrentUser(user)
    return user
  else
    return json
  end
end

#getNewAccessTokenByRefreshToken(refreshToken) ⇒ Object

TODO 刷新 Access Token 使用 Refresh token 获取新的 Access token。代码参考: github.com/Authing/authing.js/blob/cf4757d09de3b44c3c3f4509ae8c8715c9f302a2/src/lib/authentication/AuthenticationClient.ts#L2296



489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 489

def getNewAccessTokenByRefreshToken(refreshToken)
  # 检查参数合法性
  if ['oauth', 'oidc'].include?(@protocol) == false
    raise '初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc,请检查参数'
  end
  if !@secret && @tokenEndPointAuthMethod != nil
    raise '请在初始化 AuthenticationClient 时传入 appId 和 secret 参数'
  end

  if @tokenEndPointAuthMethod == 'client_secret_post'
    return _getNewAccessTokenByRefreshTokenWithClientSecretPost(
      refreshToken
    );
  end
  if @tokenEndPointAuthMethod == 'client_secret_basic'
    # return await this._getNewAccessTokenByRefreshTokenWithClientSecretBasic(
    #   refreshToken
    # );
  end
  if @tokenEndPointAuthMethod == 'none'
    # return await this._getNewAccessTokenByRefreshTokenWithNone(refreshToken);
  end
end

#getUserInfoByAccessToken(access_token) ⇒ Object



441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 441

def getUserInfoByAccessToken(access_token)
  api = nil;
  if @protocol == 'oidc'
    api = "#{@appHost}/oidc/me";
  elsif @protocol == 'oauth'
    api = "#{@appHost}/oauth/me";
  end

  userInfo = @naiveHttpClient.request({
    method: 'POST',
    url: api,
    headers: {
      Authorization: 'Bearer ' + access_token
    }
  });
  return userInfo
end

#introspectToken(token) ⇒ Object



540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 540

def introspectToken(token)
  # 检查参数合法性
  if ['oauth', 'oidc'].include?(@protocol) == false
    raise '初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc,请检查参数'
  end
  if !@secret && @tokenEndPointAuthMethod != nil
    raise '请在初始化 AuthenticationClient 时传入 appId 和 secret 参数'
  end

  if @introspectionEndPointAuthMethod == 'client_secret_post'
    return _introspectTokenWithClientSecretPost(token)
  end
  if @introspectionEndPointAuthMethod == 'client_secret_basic'
    # return await this._introspectTokenWithClientSecretBasic(token);
  end
  if @introspectionEndPointAuthMethod == 'none'
    # return await this._introspectTokenWithNone(token);
  end
  raise '初始化 AuthenticationClient 时传入的 introspectionEndPointAuthMethod 参数可选值为 client_secret_base、client_secret_post、none,请检查参数'
end

#loginByEmail(email, password, options = {}) ⇒ Object

使用邮箱登录a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”, userPoolId: “60800b8ee5b66b23128b4980”) a.loginByEmail(‘[email protected]’, “123456789”)



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 146

def loginByEmail(email, password, options = {})
  # 第一步:构建 variables
  publicKey = @publicKeyManager.getPublicKey()
  encryptedPassword = AuthingRuby::Utils.encrypt(password, publicKey)
  variables = {
    "input": {
      "email": email,
      "password": encryptedPassword,

      "autoRegister": options.fetch(:autoRegister, nil),
      "captchaCode": options.fetch(:captchaCode, nil),
      "clientIp": options.fetch(:clientIp, nil),
    }
  }
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  res = graphqlAPI.loginByEmail(@graphqlClient, variables)
  json = JSON.parse(res)
  user = json.dig('data', 'loginByEmail')
  if user
    setCurrentUser(user);
    return user 
  end
  return json
end

#loginByPhoneCode(phone, code, options = {}) ⇒ Object

使用手机号验证码登录a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.sendSmsCode(“13556136684”) a.loginByPhoneCode(“13556136684”, “1347”)



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 203

def loginByPhoneCode(phone, code, options = {})
  # 第一步:构建 variables
  variables = {
    "input": {
      "phone": phone,
      "code": code,
      "clientIp": options.fetch(:clientIp, nil),
    }
  }
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  res = graphqlAPI.loginByPhoneCode(@graphqlClient, variables)
  json = JSON.parse(res)
  user = json.dig('data', 'loginByPhoneCode')
  if user
    setCurrentUser(user);
    return user 
  end
  return json
end

#loginByPhonePassword(phone, password, options = {}) ⇒ Object

使用手机号密码登录a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.loginByPhonePassword(“13556136684”, “123456”)



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 226

def loginByPhonePassword(phone, password, options = {})
  # 第一步:构建 variables
  publicKey = @publicKeyManager.getPublicKey()
  encryptedPassword = AuthingRuby::Utils.encrypt(password, publicKey)
  variables = {
    "input": {
      "phone": phone,
      "password": encryptedPassword,

      "captchaCode": options.fetch(:captchaCode, nil),
      "clientIp": options.fetch(:clientIp, nil),
    }
  }
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  res = graphqlAPI.loginByPhonePassword(@graphqlClient, variables)
  json = JSON.parse(res)
  user = json.dig('data', 'loginByPhonePassword')
  if user
    setCurrentUser(user);
    return user 
  end
  return json
end

#loginByUsername(username, password, options = {}) ⇒ Object

使用用户名登录a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.loginByUsername(‘agoodob’, “123456789”)



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 174

def loginByUsername(username, password, options = {})
  # 第一步:构建 variables
  publicKey = @publicKeyManager.getPublicKey()
  encryptedPassword = AuthingRuby::Utils.encrypt(password, publicKey)
  variables = {
    "input": {
      "username": username,
      "password": encryptedPassword,

      "autoRegister": options.fetch(:autoRegister, nil),
      "captchaCode": options.fetch(:captchaCode, nil),
      "clientIp": options.fetch(:clientIp, nil),
    }
  }
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  res = graphqlAPI.loginByUsername(@graphqlClient, variables)
  json = JSON.parse(res)
  user = json.dig('data', 'loginByUsername')
  if user
    setCurrentUser(user);
    return user 
  end
  return json
end

#logoutObject

退出登录



295
296
297
298
299
300
301
302
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 295

def logout()
  url = "#{@appHost}/api/v2/logout?app_id=#{@appId}"
  @httpClient.request({
    method: 'GET',
    url: url,
  });
  @tokenProvider.clearUser();
end

#registerByEmail(email, password, profile = {}, options = {}) ⇒ Object

使用邮箱+密码注册 (完成, 测试通过) 参照: docs.authing.cn/v2/reference/sdk-for-node/authentication/AuthenticationClient.html 测试代码: a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.registerByEmail(‘[email protected]’, “123456789”)



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 49

def registerByEmail(email, password, profile = {}, options = {})
  # 第一步:构建 variables
  publicKey = @publicKeyManager.getPublicKey()
  encryptedPassword = AuthingRuby::Utils.encrypt(password, publicKey)
  variables = {
    "input": {
      "email": email,
      "password": encryptedPassword,

      "profile": profile,
      "forceLogin": options.fetch(:forceLogin, false),
      "clientIp": options.fetch(:clientIp, nil),
      "context": options.fetch(:context, nil),
      "generateToken": options.fetch(:generateToken, nil),
    }
  }
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  res = graphqlAPI.registerByEmail(@graphqlClient, variables)
  json = JSON.parse(res)
  user = json.dig('data', 'registerByEmail')
  return user if user
  return json
end

#registerByPhoneCode(phone, code, password, profile = {}, options = {}) ⇒ Object

使用手机号注册a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”, userPoolId: “60800b8ee5b66b23128b4980”) a.registerByPhoneCode(“13556136684”, “6330”, “123456”)



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 118

def registerByPhoneCode(phone, code, password, profile = {}, options = {})
  # 第一步:构建 variables
  publicKey = @publicKeyManager.getPublicKey()
  encryptedPassword = AuthingRuby::Utils.encrypt(password, publicKey)
  variables = {
    "input": {
      "phone": phone,
      "code": code,
      "password": encryptedPassword,

      "profile": profile,
      "forceLogin": options.fetch(:forceLogin, false),
      "clientIp": options.fetch(:clientIp, nil),
      "context": options.fetch(:context, nil),
      "generateToken": options.fetch(:generateToken, nil),
    }
  }
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  res = graphqlAPI.registerByPhoneCode(@graphqlClient, variables)
  json = JSON.parse(res)
  user = json.dig('data', 'registerByPhoneCode')
  return user if user
  return json
end

#registerByUsername(username, password, profile = {}, options = {}) ⇒ Object

使用用户名注册docs.authing.cn/v2/reference/sdk-for-node/authentication/AuthenticationClient.html#%E4%BD%BF%E7%94%A8%E7%94%A8%E6%88%B7%E5%90%8D%E6%B3%A8%E5%86%8C a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.registerByUsername(‘agoodob’, “123456789”)



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 77

def registerByUsername(username, password, profile = {}, options = {})
  # 第一步:构建 variables
  publicKey = @publicKeyManager.getPublicKey()
  encryptedPassword = AuthingRuby::Utils.encrypt(password, publicKey)
  variables = {
    "input": {
      "username": username,
      "password": encryptedPassword,

      "profile": profile,
      "forceLogin": options.fetch(:forceLogin, false),
      "clientIp": options.fetch(:clientIp, nil),
      "context": options.fetch(:context, nil),
      "generateToken": options.fetch(:generateToken, nil),
    }
  }
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  res = graphqlAPI.registerByUsername(@graphqlClient, variables)
  json = JSON.parse(res)
  user = json.dig('data', 'registerByUsername')
  return user if user
  return json
end

#resetPasswordByPhoneCode(phone, code, newPassword) ⇒ Object

通过短信验证码重置密码



708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 708

def resetPasswordByPhoneCode(phone, code, newPassword)
  publicKey = @publicKeyManager.getPublicKey()
  newPasswordEncrypted = AuthingRuby::Utils.encrypt(newPassword, publicKey)

  variables = {
    "phone": phone,
    "code": code,
    "newPassword": newPasswordEncrypted,
  }
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  resp = graphqlAPI.resetPassword(@graphqlClient, @tokenProvider, variables)
  json = JSON.parse(resp)
  result = json.dig("data", "resetPassword") # {"message":"重置密码成功!","code":200}
  return result if result
  return json
end

#revokeToken(token) ⇒ Object

撤回 Access Token 或 Refresh token



776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 776

def revokeToken(token)
  # 检查参数合法性
  if ['oauth', 'oidc'].include?(@protocol) == false
    raise '初始化 AuthenticationClient 时传入的 protocol 参数必须为 oauth 或 oidc,请检查参数'
  end
  if !@secret && @tokenEndPointAuthMethod != nil
    raise '请在初始化 AuthenticationClient 时传入 appId 和 secret 参数'
  end

  if @revocationEndPointAuthMethod == 'client_secret_post'
    _revokeTokenWithClientSecretPost(token) # 实测这个请求啥也不返回, 空的, 所以把这个直接 return 返回没啥用
    return true;
  end
  if @revocationEndPointAuthMethod == 'client_secret_basic'
    # await this._revokeTokenWithClientSecretBasic(token);
    # return true;
  end
  if @revocationEndPointAuthMethod == 'none'
    # await this._revokeTokenWithNone(token);
    # return true;
  end
  raise '初始化 AuthenticationClient 时传入的 revocationEndPointAuthMethod 参数可选值为 client_secret_base、client_secret_post、none,请检查参数'
end

#sendEmail(email, scene) ⇒ Object

发送邮件a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”) a.sendEmail(‘[email protected]’, “VERIFY_EMAIL”)

  • @param EmailScene scene 发送场景,可选值为 RESET_PASSWORD(发送重置密码邮件,邮件中包含验证码)、VerifyEmail(发送验证邮箱的邮件)、ChangeEmail(发送修改邮箱邮件,邮件中包含验证码)



257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 257

def sendEmail(email, scene)
  variables = {
    "email": email,
    "scene": scene,
  }
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  res = graphqlAPI.sendEmail(@graphqlClient, variables)
  json = JSON.parse(res)
  data = json.dig('data')
  return data if data
  return json
  # {"sendEmail":{"message":"","code":200}}
end

#sendSmsCode(phone) ⇒ Object

发送短信验证码a = AuthingRuby::AuthenticationClient.new(“rails-demo.authing.cn”, appId: “60800b9151d040af9016d60b”, userPoolId: “60800b8ee5b66b23128b4980”) a.sendSmsCode(“13556136684”)



104
105
106
107
108
109
110
111
112
113
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 104

def sendSmsCode(phone)
  url = "#{@appHost}/api/v2/sms/send"
  graphqlClient = AuthingRuby::Common::GraphqlClient.new(url, @options)
  json = {
    "phone": phone
  }
  response = graphqlClient.request({json: json})
  # {"code":200,"message":"发送成功"}
  return response
end

#setCurrentUser(user) ⇒ Object



286
287
288
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 286

def setCurrentUser(user)
  @tokenProvider.setUser(user);
end

#setToken(token) ⇒ Object



290
291
292
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 290

def setToken(token)
  @tokenProvider.setToken(token);
end

#updatePassword(newPassword, oldPassword) ⇒ Object

更新用户密码



674
675
676
677
678
679
680
681
682
683
684
685
686
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 674

def updatePassword(newPassword, oldPassword)
  publicKey = @publicKeyManager.getPublicKey()
  newPasswordEncrypted = AuthingRuby::Utils.encrypt(newPassword, publicKey)
  oldPasswordEncrypted = AuthingRuby::Utils.encrypt(oldPassword, publicKey)
  variables = { 
    "newPassword": newPasswordEncrypted,
    "oldPassword": oldPasswordEncrypted,
  }
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  res = graphqlAPI.updatePassword(@graphqlClient, @tokenProvider, variables)
  json = JSON.parse(res)
  return json.dig("data", "updatePassword")
end

#updateProfile(updates = {}) ⇒ Object

修改用户资料



600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 600

def updateProfile(updates = {})
  userId = checkLoggedIn()
  graphqlAPI = AuthingRuby::GraphQLAPI.new
  variables = {
    "id": userId,
    "input": updates
  }
  res = graphqlAPI.updateUser(@graphqlClient, @tokenProvider, variables)
  json = JSON.parse(res)
  updated_user = json.dig('data', 'updateUser')
  if updated_user
    # 如果更新成功,返回更新后的用户
    setCurrentUser(updated_user)
    return updated_user
  else
    # 如果更新失败,返回原结果
    # {"errors"=>[{"message"=>{"code"=>2020, "message"=>"尚未登录,无访问权限"}, "locations"=>[{"line"=>2, "column"=>3}], "path"=>["updateUser"], "extensions"=>{"code"=>"INTERNAL_SERVER_ERROR"}}], "data"=>nil}
    return json
  end
end

#validateToken(options = {}) ⇒ Object



566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# File 'lib/authing_ruby/authentication/AuthenticationClient.rb', line 566

def validateToken(options = {})
  if options.empty?
    raise '请在传入的参数对象中包含 accessToken 或 idToken 字段'
  end

  accessToken = options.fetch(:accessToken, nil)
  idToken = options.fetch(:idToken, nil)

  if accessToken != nil && idToken != nil
    raise "accessToken 和 idToken 只能传入一个,不能同时传入"
  end

  if idToken
    data = @naiveHttpClient.request({
      url: "#{@baseClient.appHost}/api/v2/oidc/validate_token",
      method: 'GET',
      params: {
        id_token: idToken
      }
    })
    return data
  elsif accessToken
    data = @naiveHttpClient.request({
      url: "#{@baseClient.appHost}/api/v2/oidc/validate_token",
      method: 'GET',
      params: {
        access_token: accessToken
      }
    });
    return data
  end
end