-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTokenGenerator.swift
More file actions
112 lines (97 loc) · 3.56 KB
/
TokenGenerator.swift
File metadata and controls
112 lines (97 loc) · 3.56 KB
1
2
3
4
5
6
7
8
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
* FCS API - Token Generator (Swift)
*
* Generate secure tokens for frontend JavaScript authentication
*
* Usage:
* 1. Set your accessKey and publicKey
* 2. Call generateToken()
* 3. Pass the token data to your frontend JavaScript
*
* @package FcsApi
* @author FCS API <support@fcsapi.com>
* @link https://fcsapi.com
*/
import Foundation
import CryptoKit
/// Token data structure
struct TokenData: Codable {
let token: String
let expiry: Int64
let publicKey: String
enum CodingKeys: String, CodingKey {
case token = "_token"
case expiry = "_expiry"
case publicKey = "_public_key"
}
}
/// Token generator for FCS API
/// Token expiry options (in seconds): 300 (5min), 900 (15min), 1800 (30min), 3600 (1hr), 86400 (24hr)
class FcsTokenGenerator {
private let accessKey: String
private let publicKey: String
private let tokenExpiry: Int64
/// Initialize token generator
/// - Parameters:
/// - accessKey: Your API access key (get from https://fcsapi.com/dashboard)
/// - publicKey: Your public key (get from https://fcsapi.com/dashboard)
/// - tokenExpiry: Token expiry in seconds (default: 3600 = 1 hour)
init(accessKey: String = "YOUR_ACCESS_KEY_HERE", publicKey: String = "YOUR_PUBLIC_KEY_HERE", tokenExpiry: Int64 = 3600) {
self.accessKey = accessKey
self.publicKey = publicKey
self.tokenExpiry = tokenExpiry
}
/// Generate token for frontend authentication
/// - Returns: TokenData with token, expiry, and public_key
func generateToken() -> TokenData {
let expiry = Int64(Date().timeIntervalSince1970) + tokenExpiry
let message = "\(publicKey)\(expiry)"
let key = SymmetricKey(data: Data(accessKey.utf8))
let signature = HMAC<SHA256>.authenticationCode(for: Data(message.utf8), using: key)
let token = signature.map { String(format: "%02x", $0) }.joined()
return TokenData(token: token, expiry: expiry, publicKey: publicKey)
}
/// Generate token and return as JSON string
/// - Returns: JSON string of token data
func toJson() -> String? {
let tokenData = generateToken()
let encoder = JSONEncoder()
guard let jsonData = try? encoder.encode(tokenData) else { return nil }
return String(data: jsonData, encoding: .utf8)
}
/// Generate HTML meta tags for token
/// - Returns: HTML meta tags string
func getMetaTags() -> String {
let tokenData = generateToken()
return """
<meta name="fcs-public-key" content="\(tokenData.publicKey)">
<meta name="fcs-token" content="\(tokenData.token)">
<meta name="fcs-token-expiry" content="\(tokenData.expiry)">
"""
}
}
// ============================================
// USAGE EXAMPLES
// ============================================
// Example 1: Generate token
let generator = FcsTokenGenerator(accessKey: "your_access_key", publicKey: "your_public_key")
let tokenData = generator.generateToken()
print("Token Data: \(tokenData)")
// Example 2: Get as JSON
if let json = generator.toJson() {
print("\nJSON: \(json)")
}
// Example 3: Get meta tags
print("\nMeta Tags:\n\(generator.getMetaTags())")
// Vapor example:
// import Vapor
//
// func routes(_ app: Application) throws {
// app.get("fcs-token") { req -> TokenData in
// let generator = FcsTokenGenerator(
// accessKey: Environment.get("FCS_ACCESS_KEY") ?? "",
// publicKey: Environment.get("FCS_PUBLIC_KEY") ?? ""
// )
// return generator.generateToken()
// }
// }