Class: AuthingRuby::Utils

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

Class Method Summary collapse

Class Method Details

.encrypt(plainText, publicKey) ⇒ Object

参照 JS SDK 的 encrypt 函数github.com/Authing/authing.js/blob/cf4757d09de3b44c3c3f4509ae8c8715c9f302a2/src/lib/utils.ts#L12 用途:传入一个明文,传入一个公钥用这个公钥对明文进行 RSA 加密,然后返回 base64 编码后的结果



12
13
14
15
16
# File 'lib/authing_ruby/utils/utils.rb', line 12

def self.encrypt(plainText, publicKey)
  key = OpenSSL::PKey::RSA.new(publicKey)
  result = key.public_encrypt(plainText)
  return Base64.encode64(result)
end

.generateRandomString(length = 30) ⇒ Object

生成随机字符串,参照 JS SDK 里的 src/lib/utils.ts



19
20
21
22
23
24
25
26
27
# File 'lib/authing_ruby/utils/utils.rb', line 19

def self.generateRandomString(length = 30)
  result = ""
  chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  for i in 0..length-1
    random_index = rand(0..chars.length-1)
    result += chars[random_index]
  end
  return result
end

.randomNumberString(length = 8) ⇒ Object

生成一个纯数字的随机字符串



30
31
32
33
34
35
36
37
38
# File 'lib/authing_ruby/utils/utils.rb', line 30

def self.randomNumberString(length = 8)
  result = ""
  chars = '0123456789'
  for i in 0..length-1
    random_index = rand(0..chars.length-1)
    result += chars[random_index]
  end
  return result
end

.verifyIDTokenHS256(id_token, appSecret) ⇒ Object

参数 id_token 就是登录返回的 “token” 参数 appSecret 就是 Authing 里某个应用的 appSecret



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/authing_ruby/utils/utils.rb', line 53

def self.verifyIDTokenHS256(id_token, appSecret)
  # 如果解码出错,直接返回 false
  begin
    hmac_secret = appSecret
    decoded = JWT.decode id_token, hmac_secret, true, { algorithm: 'HS256' }
  rescue => error
    puts error.message
    return false
  end

  payload = decoded[0]
  header = decoded[1]

  # 从 payload 获得过期时间,然后判断是否过期
  exp = payload["exp"] # 过期时间
  current_timestamp = Time.now.to_i
  if current_timestamp < exp
    return true # 没过期
  else
    return false # 过期了
  end
end