tapsdk_pc/user.rs
1//! User authentication functionality
2
3use std::ffi::{CStr, CString};
4
5use crate::error::{AuthorizeResult, Result, TapSdkError};
6use crate::sdk::is_initialized;
7
8/// Request user authorization
9///
10/// This initiates the authorization flow. The result will be delivered via
11/// the `AuthorizeFinished` event when calling `TapSdk::run_callbacks()`.
12///
13/// # Arguments
14/// * `scopes` - Permission scopes to request, comma-separated (e.g., "public_profile,user_friends")
15///
16/// # Returns
17/// * `Ok(())` - Authorization flow started successfully
18/// * `Err` - Failed to start authorization (check the error for details)
19///
20/// # Example
21/// ```no_run
22/// use tapsdk_pc::{user, TapSdk};
23///
24/// let sdk = TapSdk::init("your_public_key").expect("Failed to init");
25/// user::authorize("public_profile").expect("Failed to authorize");
26///
27/// // Poll for events in your game loop
28/// for event in sdk.run_callbacks() {
29/// // Handle AuthorizeFinished event
30/// }
31/// ```
32pub fn authorize(scopes: &str) -> Result<()> {
33 if !is_initialized() {
34 return Err(TapSdkError::NotInitialized);
35 }
36
37 let scopes_c = CString::new(scopes)?;
38
39 let result = unsafe { tapsdk_pc_sys::TapUser_AsyncAuthorize(scopes_c.as_ptr()) };
40
41 let auth_result = AuthorizeResult::from(result);
42
43 match auth_result {
44 AuthorizeResult::Ok => Ok(()),
45 _ => Err(TapSdkError::AuthorizeFailed(auth_result)),
46 }
47}
48
49/// Get the current user's OpenID
50///
51/// The OpenID is a unique identifier for the user within your game.
52///
53/// # Returns
54/// The user's OpenID, or `None` if not authorized or not available
55pub fn get_open_id() -> Option<String> {
56 if !is_initialized() {
57 return None;
58 }
59
60 let mut buffer: [std::os::raw::c_char; 256] = [0; 256];
61
62 let success = unsafe { tapsdk_pc_sys::TapUser_GetOpenID(buffer.as_mut_ptr()) };
63
64 if success {
65 let open_id = unsafe {
66 CStr::from_ptr(buffer.as_ptr())
67 .to_string_lossy()
68 .into_owned()
69 };
70 if open_id.is_empty() {
71 None
72 } else {
73 Some(open_id)
74 }
75 } else {
76 None
77 }
78}