Identifier missing on GameCenter Firebase Auth - c#

I have implemented auth in PlayGames for Android. When users sign in, their usernames show up under "Identifier" in the fireBase console.
In GameCenter, it does not:
public void AuthenticateToGameCenter(Action onAuthenticationComplete = null)
{
Social.localUser.Authenticate(success =>
{
Debug.Log("Game Center Initialization Complete - Result: " + success);
if (onAuthenticationComplete != null)
onAuthenticationComplete();
});
}
public Task SignInWithGameCenterAsync()
{
var credentialTask = Firebase.Auth.GameCenterAuthProvider.GetCredentialAsync();
var continueTask = credentialTask.ContinueWithOnMainThread((Task<Credential> task) =>
{
if (!task.IsCompleted)
return null;
if (task.Exception != null)
Debug.Log("GC Credential Task - Exception: " + task.Exception.Message);
var credential = task.Result;
Debug.Log($"credential { task.Result}");
var loginTask = auth.SignInWithCredentialAsync(credential);
return loginTask.ContinueWithOnMainThread(handleLoginResult);
});
return continueTask;
}
private void GameCenterLogin()
{
// first initialize, then sign in
var signinAsync = new Action(() => SignInWithGameCenterAsync());
AuthenticateToGameCenter(signinAsync);
}
Am I authing wrong?

Related

Discord.net issues creating, adding and removing roles

so I'm working on a mute and unmute command and what I want it to do is find if there is a role called "Muted" in the server if there is then give the user that role if there isn't then create the role with the necessary permissions. I've tried messing with bot permissions, role permissions, and hierarchy and it just doesn't do anything. There is no error given to me via Console nor is there an error generated in the text, it just simply seems to do nothing no matter what I try, can anyone see what I'm doing wrong? I created a pre-existing role called "Muted" and even with the role pre-applied it didn't add it. It also doesn't work while trying to remove the role if I manually added it to the user. This is what I've got:
[Command("mute")]
[Remarks("Mutes A User")]
[RequireUserPermission(GuildPermission.MuteMembers)]
public async Task Mute(SocketGuildUser user)
{
var UserCheck = Context.Guild.GetUser(Context.User.Id);
if (!UserCheck.GuildPermissions.MuteMembers)
{
await Context.Message.Channel.SendMessageAsync("", false, new EmbedBuilder()
{
Color = Color.LightOrange,
Title = "You dont have Permission!",
Description = $"Sorry, {Context.Message.Author.Mention} but you do not have permission to use this command",
Author = new EmbedAuthorBuilder()
{
Name = Context.Message.Author.ToString(),
IconUrl = Context.Message.Author.GetAvatarUrl(),
Url = Context.Message.GetJumpUrl()
}
}.Build());
}
else
{
await Context.Guild.GetUser(user.Id).ModifyAsync(x => x.Mute = true);
var muteRole = await GetMuteRole(user.Guild);
if (!user.Roles.Any(r => r.Id == muteRole.Id))
await user.AddRoleAsync(muteRole);//.ConfigureAwait(false);
}
}
[Command("unmute")]
[Remarks("Unmutes A User")]
[RequireUserPermission(GuildPermission.MuteMembers)]
public async Task Unmute(SocketGuildUser user)
{
var UserCheck = Context.Guild.GetUser(Context.User.Id);
if (!UserCheck.GuildPermissions.MuteMembers)
{
await Context.Message.Channel.SendMessageAsync("", false, new EmbedBuilder()
{
Color = Color.LightOrange,
Title = "You dont have Permission!",
Description = $"Sorry, {Context.Message.Author.Mention} but you do not have permission to use this command",
Author = new EmbedAuthorBuilder()
{
Name = Context.Message.Author.ToString(),
IconUrl = Context.Message.Author.GetAvatarUrl(),
Url = Context.Message.GetJumpUrl()
}
}.Build());
}
else
{
await Context.Guild.GetUser(user.Id).ModifyAsync(x => x.Mute = false).ConfigureAwait(false);
try { await user.ModifyAsync(x => x.Mute = false);/*.ConfigureAwait(false); */} catch { ReplyAsync("no"); }
try { await user.RemoveRoleAsync(await GetMuteRole(user.Guild));/*.ConfigureAwait(false); */} catch { ReplyAsync("No lmao"); }
}
}
public async Task<IRole> GetMuteRole(IGuild guild)
{
const string defaultMuteRoleName = "Muted";
var muteRoleName = "Muted";
var muteRole = guild.Roles.FirstOrDefault(r => r.Name == muteRoleName);
if (muteRole == null)
{
try
{
muteRole = await guild.CreateRoleAsync(muteRoleName, GuildPermissions.None, Color.Default, false, false);//.ConfigureAwait(false);
}
catch
{
muteRole = guild.Roles.FirstOrDefault(r => r.Name == muteRoleName) ?? await guild.CreateRoleAsync(defaultMuteRoleName, GuildPermissions.None, Color.Default, false, false);//.ConfigureAwait(false);
}
}
foreach (var toOverwrite in (await guild.GetTextChannelsAsync()))
{
try
{
if (!toOverwrite.PermissionOverwrites.Any(x => x.TargetId == muteRole.Id && x.TargetType == PermissionTarget.Role))
{
await toOverwrite.AddPermissionOverwriteAsync(muteRole, denyOverwrite);//.ConfigureAwait(false);
await Task.Delay(200);//.ConfigureAwait(false);
}
}
catch
{
}
}
return muteRole;
}
If anyone can help me that would be great, cheers!

Allow an account access to only one mobile app and browser on website

I'm doing a task that allow an account access to only one mobile app and browser on website(When login on other mobile app or browser on website, this current mobile app or browser website will return to login page when call APi). My idea is creating Dictionary> on AddSingleton Class to save userName and Token.
The request call to API will check whether this account and token are existed on Dictionary> or not. Everything work on local (dev) but when i deploy on server,
Dictionary> clear (dispose) all value saved before automatically .
Anybody know why or have any idea for this issue. Thanks all.
Declare On Startup:
services.AddSingleton<DictionaryAccount, DictionaryAccount>();
Event When Call Api On Startup:
OnTokenValidated = AdditionalValidation
Fuction AdditionalValidation on startup:
public Task AdditionalValidation(TokenValidatedContext context)
{
bool check = true;
var securityToken = context.SecurityToken as JwtSecurityToken;
var claim = securityToken.Claims.SingleOrDefault(t => t.Type == "unique_name");
//1 - web ; 2 - mobile
var platform = securityToken.Claims.SingleOrDefault(t => t.Type == "platform");
try
{
if (TurnOff != 1)
{
if (platform.Value != null)
{
try
{
int type = int.Parse(platform.Value);
string email = securityToken.Claims.SingleOrDefault(t => t.Type == "Email").Value;
if(!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(securityToken.RawData))
{
using (var serviceScope = _app.ApplicationServices.CreateScope())
{
var _context = serviceScope.ServiceProvider.GetRequiredService<DictionaryAccount>();
check = _context.CheckValidSession(type, email, securityToken.RawData, _logger);
}
}
}
catch (Exception e)
{
_logger.LogError("Fail login startUp " + e.ToString());
context.Response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable;
context.Fail("Failed additional validation");
}
}
if (!check)
{
context.Response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable;
context.Fail("Failed additional validation");
}
}
}
catch(Exception e)
{
_logger.LogError("Fail login startUp " + e.ToString());
context.Response.StatusCode = (int)HttpStatusCode.RequestedRangeNotSatisfiable;
context.Fail("Failed additional validation");
}
return Task.CompletedTask;
}
Function CheckValidSession:
public bool CheckValidSession(int type, string email, string token, ILogger<AuthController> _logger)
{
string outConnection;
try
{
//1 - web ; 2 - mobile
_logger.LogWarning("login write log email: " +email);
_logger.LogWarning("login write log type: " +type);
_logger.LogWarning("login write log token: " + token);
_logger.LogWarning("login write log list" + string.Join(",", accountListWebsite.Select(x => x.Key).ToArray()));
var item = accountListWebsite.Select(x => x.Value).ToList();
for (int i = 0; i < item.Count; i++)
{
_logger.LogWarning("Token In list: " + string.Join(",", accountListWebsite.Select(x => x.Value).ToList()[0].ToArray()));
}
if (type == 1)
{
if (accountListWebsite[email].TryGetValue(token, out outConnection))
{
_logger.LogWarning("return true");
return true;
}
}
else if(type == 2)
{
if (accountListMobile[email].TryGetValue(token, out outConnection))
{
return true;
}
}
return false;
}
catch(Exception e)
{
_logger.LogWarning("Exception return false " + e.ToString(), e.Message);
bool check = false;
return check;
}
}
Function CreateDictionaryAccountWeb: -> called this function when login success
public bool CreateDictionaryAccountWeb(string email, string token, int count, ILogger<AuthController> logger)
{
_logger = logger;
Count = count;
bool result = true;
try
{
lock (accountListWebsite)
{
HashSet<string> emails;
if (!accountListWebsite.TryGetValue(email, out emails))
{
emails = new HashSet<string>();
accountListWebsite.Add(email, emails);
}
_logger.LogWarning("login write log " + string.Join(",", accountListWebsite.Select(x => x.Key).ToArray()));
lock (accountListWebsite)
{
if (emails != null && emails.Count >= 0) {
if (!emails.Any(x => x.Contains(token))) {
if (emails.Count >= count)
{
var temp = emails.First();
if (temp != token)
emails.Remove(temp);
}
_logger.LogWarning("login token " + token);
emails.Add(token);
}
}
else
{
emails.Add(token);
}
}
}
}
catch (Exception e)
{
_logger.LogError("Fail login" + e.ToString());
result = false;
}
return result;
}
My Log:

PHAssetChangeRequest Cocoa error -1

I need to save downloaded video to gallery on iPhone, but getting error:
The operation couldnt be completed. (Cocoa error -1/)
Tried also to do this through webClient.DownloadDataAsync(), getting same error. Here is my listing:
public async Task<string> DownloadFile(string fileUri)
{
var tcs = new TaskCompletionSource<string>();
string fileName = fileUri.Split('/').Last();
var documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string videoFileName = System.IO.Path.Combine(documentsDirectory, fileName);
var webClient = new WebClient();
webClient.DownloadFileCompleted += (s, e) =>
{
var authStatus = await PHPhotoLibrary.RequestAuthorizationAsync();
if(authStatus == PHAuthorizationStatus.Authorized){
var fetchOptions = new PHFetchOptions();
var collections = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, fetchOptions);
collection = collections.firstObject as PHAssetCollection;
PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => {
var assetCreationRequest = PHAssetChangeRequest.FromVideo(NSUrl.FromFileName(videoFileName));
var assetPlaceholder = assetCreationRequest.PlaceholderForCreatedAsset;
var albumChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(collection);
albumChangeRequest.AddAssets(new PHObject[] { assetPlaceholder });
}, delegate (bool status, NSError error) {
if (status)
{
Console.Write("Video added");
tcs.SetResult("success");
}
});
}
try
{
webClient.DownloadFileAsync(new Uri(fileUri), videoFileName);
}
catch (Exception e)
{
tcs.SetException(e);
}
return await tcs.Task;
}
Any help would be appreciated. Thanks.
(Cocoa error -1/)
Are you sure that you actually have valid data/mp4 from your download?
Are you using SSL (https), otherwise have you applied for an ATS exception in your info.plist?
Check the phone/simulator console output for errors concerning ATS
Note: I typically use NSUrlSession directly to avoid the HttpClient wrapper...
Example using NSUrlSession task:
var videoURL = NSUrl.FromString(urlString);
var videoPath = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User)[0];
NSUrlSession.SharedSession.CreateDownloadTask(videoURL, (location, response, createTaskError) =>
{
if (location != null && createTaskError == null)
{
var destinationURL = videoPath.Append(response?.SuggestedFilename ?? videoURL.LastPathComponent, false);
// If file exists, it is already downloaded, but for debugging, delete it...
if (NSFileManager.DefaultManager.FileExists(destinationURL.Path)) NSFileManager.DefaultManager.Remove(destinationURL, out var deleteError);
NSFileManager.DefaultManager.Move(location, destinationURL, out var moveError);
if (moveError == null)
{
PHPhotoLibrary.RequestAuthorization((status) =>
{
if (status.HasFlag(PHAuthorizationStatus.Authorized))
{
PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
{
PHAssetChangeRequest.FromVideo(destinationURL);
}, (complete, requestError) =>
{
if (!complete && requestError != null)
Console.WriteLine(requestError);
});
}
});
}
else
Console.WriteLine(moveError);
}
else
Console.WriteLine(createTaskError);
}).Resume();
Note: To confirm your code, try using a known valid secure URL source:
https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4 via “Video For Everybody” Test Page

StorageProgress Report function is not called by GetFileAsync

I'm trying to download resources file for my game from Firebase Storage, and to show downloading progress. But I came to strange behavior of GetFileAsync function. The Report function of StorageProgress is not called periodically during file downloading how it is described in reference. Report function is called during saving to disk, after the file is placed into memory(downloaded). What I'm doing wrong?
string resourcesURL = "URL_TO_RESOURCE_FILE"; // https://firebasestorage.googleapis.com/......
public void UpdateProgress(float val)
{
labelProgress.text = Mathf.RoundToInt(val * 100f) + "%";
circleProgress.fillAmount = val;
}
void OnDownloadClick()
{
SetDownloadingView();
string saveToPath = GetParentFolder() + "/resources.bin";
StorageReference fileRef = FirebaseBackend.Instance.GetStorage().GetReferenceFromUrl(resourcesURL);
StorageProgress<Firebase.Storage.DownloadState> progressHandler = new StorageProgress<Firebase.Storage.DownloadState>(state =>
{
Debug.Log(String.Format ("Progress: {0} of {1} bytes transferred.", state.BytesTransferred, state.TotalByteCount));
UpdateProgress(state.BytesTransferred / state.TotalByteCount);
});
Task dwnTask = fileRef.GetFileAsync
(
saveToPath,
progressHandler,
CancellationToken.None
);
dwnTask.ContinueWith(resultTask =>
{
if (!resultTask.IsFaulted && !resultTask.IsCanceled)
{
ResetView();
Debug.Log("Download finished!");
}
else
{
ResetView();
Debug.Log("Download fail!");
}
});
}
Unity version is 5.5.0f3
Firebase Unity SDK version is 3.0.1
You may not be doing anything wrong at all.
According to this post, this is a Firebase bug that is to be addressed in the next Firebase update.
Try with an IEnumerator, this is my code with the storage progress working:
protected IEnumerator downloadObject(string target_file, string target_path, int item_index)
{
if (target_file != "")
{
FirebaseStorage storage = FirebaseStorage.DefaultInstance;
string local_url = target_path.Replace("\\", "/").Replace("//", "/");
StorageReference storage_ref =
storage.GetReferenceFromUrl(FB_Conf.gsURL + target_file);
Task task = null;
try
{
task = storage_ref.GetFileAsync(local_url,
new Firebase.Storage.StorageProgress<DownloadState>((DownloadState state) =>
{
// called periodically during the download
long tbyte = state.TotalByteCount;
file_progress = (float)state.BytesTransferred / (float)tbyte;
}), CancellationToken.None);
}
catch (Exception exc)
{
Debug.Log("Get file async error: " + exc.Message);
}
if (task != null)
{
yield return new WaitUntil(() => task.IsCompleted);
task.ContinueWith((resultTask) =>
{
if ((resultTask.IsFaulted) || (resultTask.IsCanceled))
{
error_count++;
string msg = (resultTask.IsCanceled) ? "Download error." : "";
if ((resultTask.Exception != null) &&
(resultTask.Exception.InnerExceptions.Count > 0) &&
(resultTask.Exception.InnerExceptions[0] is Firebase.Storage.StorageException))
msg = ((Firebase.Storage.StorageException)resultTask.Exception.InnerExceptions[0]).HttpResultCode.ToString();
else if (resultTask.Exception != null)
msg = resultTask.Exception.Message;
}
});
}
else
{
error_count++;
}
}
}

SignalR 2 still see connection live even after internet cut out at client side

I configure the server as following on startup.cs
GlobalHost.HubPipeline.RequireAuthentication();
// Make long polling connections wait a maximum of 110 seconds for a
// response. When that time expires, trigger a timeout command and
// make the client reconnect.
GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(40);
// Wait a maximum of 30 seconds after a transport connection is lost
// before raising the Disconnected event to terminate the SignalR connection.
GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(30);
// For transports other than long polling, send a keepalive packet every
// 10 seconds.
// This value must be no more than 1/3 of the DisconnectTimeout value.
GlobalHost.Configuration.KeepAlive = TimeSpan.FromSeconds(10);
GlobalHost.HubPipeline.AddModule(new SOHubPipelineModule());
var hubConfiguration = new HubConfiguration { EnableDetailedErrors = true };
var heartBeat = GlobalHost.DependencyResolver.Resolve<ITransportHeartbeat>();
var monitor = new PresenceMonitor(heartBeat);
monitor.StartMonitoring();
app.MapSignalR(hubConfiguration);
where PresenceMonitor is the class responsible of check unlive data . as I keep them in database using the following code
public class PresenceMonitor
{
private readonly ITransportHeartbeat _heartbeat;
private Timer _timer;
// How often we plan to check if the connections in our store are valid
private readonly TimeSpan _presenceCheckInterval = TimeSpan.FromSeconds(40);
// How many periods need pass without an update to consider a connection invalid
private const int periodsBeforeConsideringZombie = 1;
// The number of seconds that have to pass to consider a connection invalid.
private readonly int _zombieThreshold;
public PresenceMonitor(ITransportHeartbeat heartbeat)
{
_heartbeat = heartbeat;
_zombieThreshold = (int)_presenceCheckInterval.TotalSeconds * periodsBeforeConsideringZombie;
}
public async void StartMonitoring()
{
if (_timer == null)
{
_timer = new Timer(_ =>
{
try
{
Check();
}
catch (Exception ex)
{
// Don't throw on background threads, it'll kill the entire process
Trace.TraceError(ex.Message);
}
},
null,
TimeSpan.Zero,
_presenceCheckInterval);
}
}
private async void Check()
{
// Get all connections on this node and update the activity
foreach (var trackedConnection in _heartbeat.GetConnections())
{
if (!trackedConnection.IsAlive)
{
await trackedConnection.Disconnect();
continue;
}
var log = AppLogFactory.Create<WebApiApplication>();
log.Info($"{trackedConnection.ConnectionId} still live ");
var connection = await (new Hubsrepository()).FindAsync(c => c.ConnectionId == trackedConnection.ConnectionId);
// Update the client's last activity
if (connection != null)
{
connection.LastActivity = DateTimeOffset.UtcNow;
await (new Hubsrepository()).UpdateAsync(connection, connection.Id).ConfigureAwait(false);
}
}
// Now check all db connections to see if there's any zombies
// Remove all connections that haven't been updated based on our threshold
var hubRepository = new Hubsrepository();
var zombies =await hubRepository.FindAllAsync(c =>
SqlFunctions.DateDiff("ss", c.LastActivity, DateTimeOffset.UtcNow) >= _zombieThreshold);
// We're doing ToList() since there's no MARS support on azure
foreach (var connection in zombies.ToList())
{
await hubRepository.DeleteAsync(connection);
}
}
}
and my hub connect disconnect , reconnect looks like
public override async Task OnConnected()
{
var log = AppLogFactory.Create<WebApiApplication>();
if (Context.QueryString["transport"] == "webSockets")
{
log.Info($"Connection is Socket");
}
if (Context.Headers.Any(kv => kv.Key == "CMSId"))
{
// Check For security
var hederchecker = CryptLib.Decrypt(Context.Headers["CMSId"]);
if (string.IsNullOrEmpty(hederchecker))
{
log.Info($"CMSId cannot be decrypted {Context.Headers["CMSId"]}");
return;
}
log.Info($" {hederchecker} CMSId online at {DateTime.UtcNow} ");
var user = await (new UserRepository()).FindAsync(u => u.CMSUserId == hederchecker);
if (user != null)
await (new Hubsrepository()).AddAsync(new HubConnection()
{
UserId = user.Id,
ConnectionId = Context.ConnectionId,
UserAgent = Context.Request.Headers["User-Agent"],
LastActivity = DateTimeOffset.UtcNow
}).ConfigureAwait(false);
//_connections.Add(hederchecker, Context.ConnectionId);
}
return;
}
public override async Task OnDisconnected(bool stopCalled)
{
try
{
//if (!stopCalled)
{
var hubRepo = (new Hubsrepository());
var connection = await hubRepo.FindAsync(c => c.ConnectionId == Context.ConnectionId);
if (connection != null)
{
var user = await (new UserRepository()).FindAsync(u => u.Id == connection.UserId);
await hubRepo.DeleteAsync(connection);
if (user != null)
{
//var log = AppLogFactory.Create<WebApiApplication>();
//log.Info($"CMSId cannot be decrypted {cmsId}");
using (UserStatusRepository repo = new UserStatusRepository())
{
//TODO :: To be changed immediatley in next release , Date of change 22/02/2017
var result = await (new CallLogRepository()).CallEvent(user.CMSUserId);
if (result.IsSuccess)
{
var log = AppLogFactory.Create<WebApiApplication>();
var isStudent = await repo.CheckIfStudent(user.CMSUserId);
log.Info($" {user.CMSUserId} CMSId Disconnected here Before Set offline at {DateTime.UtcNow} ");
var output = await repo.OfflineUser(user.CMSUserId);
log.Info($" {user.CMSUserId} CMSId Disconnected here after Set offline at {DateTime.UtcNow} ");
if (output)
{
log.Info($" {user.CMSUserId} CMSId Disconnected at {DateTime.UtcNow} ");
Clients.All.UserStatusChanged(user.CMSUserId, false, isStudent);
}
}
}
}
}
}
}
catch (Exception e)
{
var log = AppLogFactory.Create<WebApiApplication>();
log.Error($"CMSId cannot Faild to be offline {Context.ConnectionId} with error {e.Message}{Environment.NewLine}{e.StackTrace}");
}
}
public override async Task OnReconnected()
{
string name = Context.User.Identity.Name;
var log = AppLogFactory.Create<WebApiApplication>();
log.Info($" {name} CMSId Reconnected at {DateTime.UtcNow} ");
var connection = await (new Hubsrepository()).FindAsync(c => c.ConnectionId == Context.ConnectionId);
if (connection == null)
{
var user = await (new UserRepository()).FindAsync(u => u.CMSUserId == name);
if (user != null)
await (new Hubsrepository()).AddAsync(new HubConnection()
{
UserId = user.Id,
ConnectionId = Context.ConnectionId,
UserAgent = Context.Request.Headers["User-Agent"],
LastActivity = DateTimeOffset.UtcNow
}).ConfigureAwait(false);
}
else
{
connection.LastActivity = DateTimeOffset.UtcNow;
await (new Hubsrepository()).UpdateAsync(connection, connection.Id).ConfigureAwait(false);
}
}
all test cases passes well except when internet cut on client side the connection keep live for more than 10 minutes, is this related to authentication , or any configuration wrong at my side any help am really don't know what's wrong . client use websocket transport

Categories