public async void OnLoginButtonClicked(object sender, EventArgs args) { string user = this.EntryUser.Text; string pass = this.EntryPass.Text; try { FirebaseAuthProvider authProvider = new FirebaseAuthProvider(new FirebaseConfig(AppConfig.Instance.GetFirebaseApiKey())); FirebaseAuthLink authLink = await authProvider.SignInWithEmailAndPasswordAsync(user, pass); if (authLink != null && authLink.FirebaseToken != null) { UserSettings.SaveFirebaseAuthToken(authLink.FirebaseToken); App.Current.MainPage = new ExpensesPage(); } else { await DisplayAlert("Error", "Username/password is incorrect.", "OK"); } } catch (Exception e) { await DisplayAlert("Error", "Error : " + e.Message, "OK"); } }
public PUser(IUser iview) { this._iview = iview; fbProvider = new FirebaseAuthProvider(new FirebaseConfig(ConfigData.Get("FirebaseAppKey"))); }
public async Task <string> Post([FromForm] FileUpload objFile) { client = new FireSharp.FirebaseClient(iconfig); // Block 1: Uploading to wwwroot/Upload. try { if (objFile.files.Length > 0) { if (!Directory.Exists(_environment.WebRootPath + "\\Upload\\")) { Directory.CreateDirectory(_environment.WebRootPath + "\\Upload\\"); } using (FileStream fileStream = System.IO.File.Create(_environment.WebRootPath + "\\Upload\\" + objFile.files.FileName)) { objFile.files.CopyTo(fileStream); fileStream.Flush(); //return "\\Upload\\" + objFile.files.FileName; } } else { return("Failed"); } } catch (Exception ex) { //return ex.Message.ToString(); } // Block 2 (OPTIONAL): Some actions with file. // 3 // Block 3: Uploading to Firestorage. //byte[] fileStream1 = System.IO.File.ReadAllBytes(_environment.WebRootPath + "\\Upload\\" + objFile.files.FileName); //string output = Convert.ToBase64String(fileStream1); //var data = new ImageModel //{ // outputImg = output //}; //SetResponse response = await client.SetTaskAsync("Image/",data); //ImageModel result = response.ResultAs<ImageModel>(); //-------------------------------------------------------------- byte[] fileStream1 = System.IO.File.ReadAllBytes(_environment.WebRootPath + "\\Upload\\" + objFile.files.FileName); string output = Convert.ToBase64String(fileStream1); const string ApiKey = "AIzaSyCZk_pPX5pQylzdr1_Ud78zJp8PY9tYFI4"; const string Bucket = "steposbb.appspot.com"; var auth = new FirebaseAuthProvider(new Firebase.Auth.FirebaseConfig(ApiKey)); var ab = await auth.SignInWithEmailAndPasswordAsync("*****@*****.**", "321321"); var cancelation = new CancellationToken(); string FbToken = ab.FirebaseToken; var fs = new FileStream(_environment.WebRootPath + "\\Upload\\" + objFile.files.FileName, FileMode.Open); var storage = new FirebaseStorage( Bucket, new FirebaseStorageOptions { AuthTokenAsyncFactory = () => Task.FromResult(FbToken), ThrowOnCancel = true } ).Child("documents") .Child($"{objFile.files.FileName}.{Path.GetExtension(objFile.files.FileName).Substring(1)}") .PutAsync(fs, cancelation); var apiKey = _configuration["SendGridAPIKey"]; var client2 = new SendGridClient(apiKey); var from = new EmailAddress("*****@*****.**", "Example User"); var subject = "Sending with SendGrid is Fun"; var to = new EmailAddress("*****@*****.**"); var plainTextContent = "and easy to do anywhere, even with C#"; var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>"; var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent); var banner2 = new Attachment() { Content = output, Type = "image/jpeg", Filename = "ForgotPassword.jpg", Disposition = "inline", ContentId = "Banner 2" }; msg.AddAttachment(banner2); var response = await client2.SendEmailAsync(msg); return("Works!"); }
public async Task <IActionResult> Index(string id, int?pageNumber) { // Filters the people the current logged in user likes IQueryable <ApplicationUser> GetLikedUsers(List <string> keywords) { var predicate = PredicateBuilder.New <ApplicationUser>(); foreach (string keyword in keywords) { predicate = predicate.Or(p => p.Id.Contains(keyword)); } return(_db.ApplicationUser.Where(predicate)); } var likedUsers = await _db.Liked .Where(x => x.ApplicationUserID == id) .ToListAsync(); List <string> likedUserList = new List <string>(); foreach (var item in likedUsers) { likedUserList.Add(item.ApplicationUserLikedID.ToString()); } IQueryable <ApplicationUser> applicationUsersIQ; if (likedUserList.Count() > 0) { applicationUsersIQ = GetLikedUsers(likedUserList); } else { applicationUsersIQ = _db.ApplicationUser.Where(x => x.Id == ""); } int pageSize = 3; PaginatedList <ApplicationUser> paginatedListUsers = await PaginatedList <ApplicationUser> .CreateAsync( applicationUsersIQ, pageNumber ?? 1, pageSize); var auth = new FirebaseAuthProvider(new FirebaseConfig(FirebaseKeys.apiKey)); var a = await auth.SignInWithEmailAndPasswordAsync(FirebaseKeys.AuthEmail, FirebaseKeys.AuthPassword); for (int i = 0; i < paginatedListUsers.Count; i++) { if (paginatedListUsers[i].ProfileImage != "/images/avatar/default_avatar.png") { paginatedListUsers[i].FirebaseProfileImageURL = new FirebaseStorage( FirebaseKeys.Bucket, new FirebaseStorageOptions { AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken), ThrowOnCancel = true }) .Child("images") .Child($"{paginatedListUsers[i].ProfileImage}") .GetDownloadUrlAsync().Result; } } LikedViewModel likedViewModel = new LikedViewModel() { PaginatedListUsers = paginatedListUsers }; return(View(likedViewModel)); }
public async Task <IActionResult> Create([Bind("ApplicationUserID,FileUpload")] ImageViewModel imageViewModel) { FileStream fs; var fileUpload = imageViewModel.FileUpload; var userId = imageViewModel.ApplicationUserID; // Extension validation string[] permittedExtensions = { ".jpg", ".png", ".jpeg" }; string ext = Path.GetExtension(fileUpload.FileName).ToLowerInvariant(); if (string.IsNullOrEmpty(ext) || !permittedExtensions.Contains(ext)) { string errorMessage = $"Files {ext}* not allowed. Only"; for (int i = 0; i < permittedExtensions.Length; i++) { if (permittedExtensions.Length == 1) { errorMessage = errorMessage + " " + permittedExtensions[i] + "*"; } if (i == (permittedExtensions.Length - 1)) { errorMessage = errorMessage + ", and " + permittedExtensions[i] + "*"; } else if (i == 0) { errorMessage = errorMessage + " " + permittedExtensions[i] + "*"; } else { errorMessage = errorMessage + ", " + permittedExtensions[i] + "*"; } } errorMessage = errorMessage + " allowed."; return(RedirectToAction("Index", new { id = userId, errorMessage = errorMessage })); } ; string folderName = "firebaseFiles"; string fileName = Guid.NewGuid() + "_" + fileUpload.FileName; string filepath = Path.Combine(_environment.WebRootPath, $"images/{folderName}", fileName); string fileImagePath = Path.Combine(_environment.ContentRootPath, "wwwroot/images/firebaseFiles/", fileName); if (ModelState.IsValid && fileUpload.Length > 1) { // Upload file to static image using (var fileStream = new FileStream(fileImagePath, FileMode.Create)) { await fileUpload.CopyToAsync(fileStream); } // Upload static image to Firebase fs = new FileStream(filepath, FileMode.Open); var auth = new FirebaseAuthProvider(new FirebaseConfig(FirebaseKeys.apiKey)); var a = await auth.SignInWithEmailAndPasswordAsync(FirebaseKeys.AuthEmail, FirebaseKeys.AuthPassword); var cancellation = new CancellationTokenSource(); var upload = new FirebaseStorage( FirebaseKeys.Bucket, new FirebaseStorageOptions { AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken), ThrowOnCancel = true }) .Child("images") .Child($"{fileName}") .PutAsync(fs, cancellation.Token); try { await upload; Image image = new Image() { ApplicationUserID = userId, ImageFirebaseTitle = fileName }; _db.Add(image); await _db.SaveChangesAsync(); fs.Close(); System.IO.File.Delete(filepath); return(RedirectToAction("Index", new { id = userId, message = "File Successfully Uploaded!" })); } catch (Exception ex) { Debug.WriteLine($"{ex}"); throw; } } return(BadRequest()); }
// Start is called before the first frame update void Start() { authProvider = new FirebaseAuthProvider(new FirebaseConfig(apiKey)); }
public DbFirebaseAuth() { client = new FirebaseClient("https://ssaplication.firebaseio.com/"); userAuth = new FirebaseAuth(); firebaseAuthProvider = new FirebaseAuthProvider(new FirebaseConfig(CONFIG_KEY)); }
public FirebaseService(MyContext context, IOptions <AppSettings> settings) { this._context = context; this.apikey = settings.Value.FirebaseApiKey; this.authProvider = new FirebaseAuthProvider(new FirebaseConfig(this.apikey)); }
public PVehicle(IVehicle iview) { _iview = iview; fbProvider = new FirebaseAuthProvider(new FirebaseConfig(ConfigData.Get("FirebaseAppKey"))); }
public async Task AttemptLogin(string username, string password) { UserEntity user = null; AirDataContext DbContext = new AirDataContext(); try { //string email = Framework.FieldValidation.ValidateStringField(this.txtEmail, "Email Address", 200, true).ToLower(); //string password = Framework.FieldValidation.ValidateStringField(this.txtPassword, "Password", int.MaxValue, 6, true); string firebaseApiKey = ConfigurationManager.AppSettings["Firebase.ApiKey"]; FirebaseAuthProvider authProvider = new FirebaseAuthProvider(new FirebaseConfig(firebaseApiKey)); FirebaseAuthLink auth = await authProvider.SignInWithEmailAndPasswordAsync(username, password); user = UserEntity.GetByFirebaseId(DbContext, auth.User.LocalId); if (user == null) // For some reason the fb auth id didn't get set. Try getting user by email { user = UserEntity.Get(DbContext, username); } user.VerifyStatus(); // create the cookie and record the event and other items Security.LoginUser(user, auth, true); Global.TrackEvent("Login_Success", null, user); // redirect the user to the root redirector page this.Response.Redirect("/", false); } catch (FirebaseAuthException ex) { if (ex.Reason == AuthErrorReason.WrongPassword) { //Way to handle wrong passwords like below.... // int retryCount = int.Parse(this.hidPasswordFailCount.Value); // if (retryCount > 1) // { // BootstrapUtils.ShowMessageAndRedirect(this, "Wrong Password", "It appears you have forgotten your password. We will now redirect you to the forgot password page", "forgot-password.aspx"); // return; // } // retryCount += 1; // this.hidPasswordFailCount.Value = retryCount.ToString(); // BootstrapUtils.ShowMessage(this, "Wrong Password", BootstrapNotifyType.danger); // return; } //BootstrapUtils.ShowMessage(this, ex.Message, BootstrapNotifyType.danger); } catch (FieldValidationException ex) { if (user != null) { Dictionary <string, string> info = new Dictionary <string, string>() { { "Error_Message", ex.Message } }; Global.TrackEvent("Login_Failure", info, user); } //BootstrapUtils.ShowMessage(this, ex.Message, BootstrapNotifyType.danger); return; } }
public async Task <UserDto> RegisterAsync(RegisterCommand command) { try { if ((await GetByEmailAsync(command.Email)).Value != null) { throw new DuplicateWaitObjectException($"{nameof(command.Email)} already exists !"); } // Create User var firebaseAuthLink = await FirebaseAuthProvider.CreateUserWithEmailAndPasswordAsync ( command.Email, command.Password, command.Name, command.SendVerificationEmail ); var newPerson = new Person ( firebaseAuthLink.User.LocalId, firebaseAuthLink.User.DisplayName, command.RegistrationNumber, command.PhoneCountryCode, command.PhoneNumber, command.CreatedAt, command.Role, firebaseAuthLink.User.IsEmailVerified, command.Status ); var person = await FirebaseClient .Child(Table) .PostAsync(JsonConvert.SerializeObject(newPerson)); return(GetUserDto ( person.Key, new User ( newPerson.UserId, newPerson.FullName, newPerson.PhoneCountryCode, newPerson.PhoneNumber, newPerson.CreatedAt, newPerson.Role, firebaseAuthLink.User.IsEmailVerified, newPerson.Status, firebaseAuthLink.User.Email, newPerson.RegistrationNumber, null ) )); } catch (Firebase.Auth.FirebaseAuthException ex) { if (ex.InnerException?.InnerException?.GetType() == typeof(SocketException)) { throw new HttpRequestException("Cannot join the server. Please check your internet connexion."); } throw ex; } catch (Firebase.Database.FirebaseException ex) { if (ex.InnerException?.InnerException?.GetType() == typeof(SocketException)) { throw new HttpRequestException("Cannot join the server. Please check your internet connexion."); } throw ex; } catch (DuplicateWaitObjectException ex) { throw ex; } catch (Exception ex) { throw ex; } }
public AuthenProvider() { _provider = new FirebaseAuthProvider(new FirebaseConfig(Constants.FIREBASE_API_KEY)); }
public Firebase() { authProvider = new FirebaseAuthProvider(new FirebaseConfig("[SUBSCRIPTION-KEY]")); fbClient = new FirebaseClient("https://awer-8918c.firebaseio.com/"); }
async void RegistrationButton_Clicked(System.Object sender, System.EventArgs e) { if ( String.IsNullOrEmpty(newuser_username.Text) || String.IsNullOrEmpty(newuser_email.Text) || String.IsNullOrEmpty(newuser_firstname.Text) || String.IsNullOrEmpty(newuser_lastname.Text) || String.IsNullOrEmpty(newuser_password.Text) || String.IsNullOrEmpty(newuser_phonenumber.Text) ) { await App.Current.MainPage.DisplayAlert("Info", "Za registraciju potrebno je ispuniti sva polja", "OK"); } else { try { bool isSuccessful = false; FirebaseUser firebaseUser = new FirebaseUser(); User user = new User(); using (await MaterialDialog.Instance.LoadingDialogAsync(message: "Dohvaćam podatke..")) { var users = await UserDataStore.GetItemsAsync(false); var username_alreadyexists = users.Where(u => u.Username == newuser_username.Text).FirstOrDefault(); var email_alreadyexists = users.Where(u => u.Email == newuser_email.Text).FirstOrDefault(); if (username_alreadyexists != null) { throw new FirebaseAuthException(null, null, null, null, reason: AuthErrorReason.UserNotFound); } if (email_alreadyexists != null) { throw new FirebaseAuthException(null, null, null, null, reason: AuthErrorReason.EmailExists); } var authProvider = new FirebaseAuthProvider(new FirebaseConfig("AIzaSyAg4riVkvSMtWwKZ6_UssK28-2K6xOndrg")); var auth = await authProvider.CreateUserWithEmailAndPasswordAsync(newuser_email.Text, newuser_password.Text, newuser_username.Text, true); user = await authProvider.GetUserAsync(auth.FirebaseToken); } if (!user.IsEmailVerified) { var allFbUsers = await UserDataStore.GetItemsAsync(false); var fbUser = allFbUsers.Where(f => f.Email == user.Email).FirstOrDefault(); firebaseUser = fbUser; if (firebaseUser != null) { isSuccessful = true; } else { firebaseUser = new FirebaseUser { Email = newuser_email.Text, Username = newuser_username.Text, Year = DateTime.Now.Year.ToString(), FirstName = newuser_firstname.Text, LastName = newuser_lastname.Text, PicturePath = "https://png.pngtree.com/png-vector/20190710/ourmid/pngtree-user-vector-avatar-png-image_1541962.jpg", PhoneNumber = newuser_phonenumber.Text }; isSuccessful = await UserDataStore.AddItemAsync(firebaseUser); } if (isSuccessful) { await App.Current.MainPage.DisplayAlert("Uspješna registracija", "Potvrdite mail adresu kako bi nastavili koristiti aplikaciju.", "Ok"); App.Current.MainPage = new NavigationPage(new UserPage()); } else { await App.Current.MainPage.DisplayAlert("Greška", "Pokušajte ponovno ili se obratite korisničkoj podršci", "Ok"); } } } catch (FirebaseAuthException ex) { if (ex.Reason.Equals(Firebase.Auth.AuthErrorReason.EmailExists)) { await App.Current.MainPage.DisplayAlert("Upozorenje", "Račun sa ovom mail adresom već postoji. Pokušajte ponovno ili se prijavite sa google-om.", "OK"); } else if (ex.Reason.Equals(Firebase.Auth.AuthErrorReason.InvalidEmailAddress)) { await App.Current.MainPage.DisplayAlert("Upozorenje", "Email adresa nije valjana. Pokušajte ponovno ili upišite neku drugu email adresu.", "OK"); } else if (ex.Reason.Equals(Firebase.Auth.AuthErrorReason.WeakPassword)) { await App.Current.MainPage.DisplayAlert("Upozorenje", "Lozinka mora biti dugačka barem 7 znakova, mora se sastojati od kojih barem jedan mora biti znak i barem jedan broj.", "OK"); } else if (ex.Reason.Equals(Firebase.Auth.AuthErrorReason.UserNotFound)) { await App.Current.MainPage.DisplayAlert("Upozorenje", "Već postoji osoba s tim korisničkim imenom!", "OK"); } else if (ex.Reason.Equals(Firebase.Auth.AuthErrorReason.InvalidEmailAddress)) { await App.Current.MainPage.DisplayAlert("Upozorenje", "Neispravna mail adresa!", "OK"); } else if (ex.Reason.Equals(Firebase.Auth.AuthErrorReason.WrongPassword)) { await App.Current.MainPage.DisplayAlert("Upozorenje", "Neispravna lozinka!", "OK"); } else { await App.Current.MainPage.DisplayAlert("Alert", ex.Message, "OK"); } } } }
public MainVM() { CreateCommands(); authProvider = PrepareAuthProvider(); }
public async Task <IActionResult> Index(string id) { if (id == null) { return(NotFound()); } var userId = (await _userManager.GetUserAsync(User)).Id; ApplicationUser loggedInUser = await _db.ApplicationUser .Include(x => x.Liked) .FirstOrDefaultAsync(x => x.Id == userId); ApplicationUser applicationUser = await _db.ApplicationUser .Include(x => x.Height) .Include(x => x.About) .Include(x => x.Images) .FirstOrDefaultAsync(x => x.Id == id); if (applicationUser == null || loggedInUser == null) { return(NotFound()); } var loggedInUserAreadyLikes = loggedInUser.Liked.Any(x => x.ApplicationUserLikedID == applicationUser.Id); ViewData["AlreadyLiked"] = "false"; if (loggedInUserAreadyLikes == true) { ViewData["AlreadyLiked"] = "true"; } var auth = new FirebaseAuthProvider(new FirebaseConfig(FirebaseKeys.apiKey)); var a = await auth.SignInWithEmailAndPasswordAsync(FirebaseKeys.AuthEmail, FirebaseKeys.AuthPassword); if (applicationUser.ProfileImage != "/images/avatar/default_avatar.png") { applicationUser.FirebaseProfileImageURL = new FirebaseStorage( FirebaseKeys.Bucket, new FirebaseStorageOptions { AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken), ThrowOnCancel = true }) .Child("images") .Child($"{applicationUser.ProfileImage}") .GetDownloadUrlAsync().Result; } List <string> firebaseImagesURL = new List <string>(); foreach (var item in applicationUser.Images) { var task = new FirebaseStorage( FirebaseKeys.Bucket, new FirebaseStorageOptions { AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken), ThrowOnCancel = true }) .Child("images") .Child($"{item.ImageFirebaseTitle}") .GetDownloadUrlAsync().Result; firebaseImagesURL.Add(task); } ViewData["Liked"] = new Liked(); ProfileViewModel profileViewModel = new ProfileViewModel() { ApplicationUser = applicationUser, Liked = new Liked(), Pass = new Pass(), FirebaseImagesURL = firebaseImagesURL }; return(View(profileViewModel)); }
/// <summary> /// Initializes a new instance of the <see cref="FirebaseAuthService"/> class. /// </summary> /// <param name="apiKey">The API key.</param> /// <param name="localStorageService">The local storage service.</param> public FirebaseAuthService(string apiKey, ILocalStorageService localStorageService) { _authProvider = new FirebaseAuthProvider(new FirebaseConfig(apiKey)); _localStorageService = localStorageService; }
private Firebase() { authProvider = new FirebaseAuthProvider(new FirebaseConfig(firebaseApiKey)); }
private async void SignUp() { //primero se comprueba que no haya ningún espacio en email o contraseña string nombreSinEspacios = Regex.Replace(Nombre, @"\s", ""); string passSinEspacios = Regex.Replace(Password, @"\s", ""); //campo de validacion vacío, comprueba si el email y la contraseña son null o están vacíos if (string.IsNullOrEmpty(nombreSinEspacios) || string.IsNullOrEmpty(passSinEspacios)) { UserDialogs.Instance.Alert("Por favor, introduzca un nombre de usuario y una contraseña.", "Campos vacíos", "OK"); } else if (!string.IsNullOrEmpty(nombreSinEspacios)) { var user = await FirebaseHelper.ObtenerUsuario(nombreSinEspacios); if (user != null) { if (nombreSinEspacios == user.Nombre) { UserDialogs.Instance.Alert("Por favor, introduzca un nombre de usuario distinto.", "Usuario existente", "OK"); } } else if (!string.IsNullOrEmpty(passSinEspacios)) { if ((passSinEspacios.Length < 8 && passSinEspacios.Length > 15) || !passSinEspacios.ToCharArray().Any(char.IsDigit)) { UserDialogs.Instance.Alert("La contraseña debe tener como mínimo 8 caracteres y un máximo de 15," + " incluyendo una letra minúscula, una mayúscula y un número.", "Error", "OK"); } else { try { var authProvider = new FirebaseAuthProvider(new FirebaseConfig(Constantes.WebAPIkey)); var auth = await authProvider.CreateUserWithEmailAndPasswordAsync(nombreSinEspacios, passSinEspacios); string gettoken = auth.FirebaseToken; var usuario = await FirebaseHelper.InsertarUsuario(nombreSinEspacios, gettoken, Constantes.GenerarId()); if (usuario) { Application.Current.MainPage = new AppShell(nombreSinEspacios); } } catch (Exception) { UserDialogs.Instance.Alert("Se ha producido un fallo en el registro." + " Por favor, compruebe su conexión a internet e inténtelo de nuevo.", "Error", "OK"); } } } else { UserDialogs.Instance.Alert("Debe introducir una contraseña.", "Error", "OK"); } } }
/// <summary> /// Inicializar o serviço conexão para Autenticação Firebase /// </summary> public static void InitializeService() { Authentication = new FirebaseAuthProvider(new FirebaseConfig(FIREBASE_API_KEY)); Database = null; Storage = null; }
public AuthService(string firebaseApiKey) { _authProvider = new FirebaseAuthProvider(new FirebaseConfig(firebaseApiKey)); }
public FirebaseAuthService() { _firebaseAuthProvider = new FirebaseAuthProvider(new FirebaseConfig(Environment.GetEnvironmentVariable("ChatServerFirebaseApiKey", EnvironmentVariableTarget.Machine))); }
internal static FirebaseStorageOptions GetStorageAuthOptions(this FirebaseAuthProvider authProvider, FirebaseAuthenticationModel authSettings) { return(new FirebaseStorageOptions { AuthTokenAsyncFactory = async() => await authSettings.GetAuthenticationTokenAsync(authProvider) }); }
private static async void DetectFaceAndRegister(string personGroupId, CreatePersonResult personResult, string cnp) { //throw new NotImplementedException(); //foreach (var image in Directory.GetFiles(imgPath, "*.*")) //{ // using (Stream S = File.OpenRead(image)) // await faceServiceClient.AddPersonFaceAsync(personGroupId, personResult.PersonId, S); //} var auth = new FirebaseAuthProvider(new FirebaseConfig(apiKey)); var login = await auth.SignInWithEmailAndPasswordAsync(AuthEmail, AuthPassword); var cancellation = new CancellationTokenSource(); var downloadUrl1 = await new FirebaseStorage( Bucket, new FirebaseStorageOptions { AuthTokenAsyncFactory = () => Task.FromResult(login.FirebaseToken), ThrowOnCancel = true }) .Child("user") .Child(cnp) .Child("facial1.jpg").GetDownloadUrlAsync(); string url1 = downloadUrl1.ToString(); var downloadUrl2 = await new FirebaseStorage( Bucket, new FirebaseStorageOptions { AuthTokenAsyncFactory = () => Task.FromResult(login.FirebaseToken), ThrowOnCancel = true }) .Child("user") .Child(cnp) .Child("facial2.jpg"). GetDownloadUrlAsync(); string url2 = downloadUrl2.ToString(); //using (WebClient client = new WebClient()) //{ // // OR // client.DownloadFileAsync(new Uri(url1), @"c:\temp\image35.png"); //} var request1 = WebRequest.Create(url1); using (var response = request1.GetResponse()) using (var stream = response.GetResponseStream()) { await faceServiceClient.AddPersonFaceAsync(personGroupId, personResult.PersonId, stream); } var request2 = WebRequest.Create(url2); using (var response = request2.GetResponse()) using (var stream = response.GetResponseStream()) { await faceServiceClient.AddPersonFaceAsync(personGroupId, personResult.PersonId, stream); } }
public AuthorizationApi() { this.authProvider = new FirebaseAuthProvider(new FirebaseConfig(AuthConfig.ApiKey)); }
public async Task <int> Send(string country, string city, string postalCode, string isp, string type, string speed, string pingFile, string speedFile) { documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments).ToString(); try { // Authenticate Anonymously with Firebase var authProvider = new FirebaseAuthProvider(new FirebaseConfig("AIzaSyAjc7Gk9LydAEKG--oCeeuNM0YG4XGihDg")); var auth = await authProvider.SignInAnonymouslyAsync(); var firebase = new FirebaseClient("https://neasure-5ed3e.firebaseio.com/", new FirebaseOptions { AuthTokenAsyncFactory = () => Task.FromResult(auth.FirebaseToken) }); // Upload Ping file to Bucket UploadToBucket(pingFile, "ping_", auth); // Upload Speed file to Bucket UploadToBucket(speedFile, "speed_", auth); // Upload Information to Database var data = new Data { country = country, city = city, postalCode = postalCode, ISP = isp, type = type, speed = speed, #if DEBUG debug = true #else debug = false #endif }; await firebase.Child("data").Child(auth.User.LocalId).PostAsync(data); // Write sent Data into File and upload to Firebase using (var surveyWriter = File.AppendText(documentsFolder + "\\Neasure\\survey_" + auth.User.LocalId + ".txt")) { surveyWriter.WriteLine("Data Sent to Firebase: "); surveyWriter.WriteLine("Country: " + country); surveyWriter.WriteLine("City: " + city); surveyWriter.WriteLine("Postal Code: " + postalCode); surveyWriter.WriteLine("ISP: " + isp); surveyWriter.WriteLine("Internet Type: " + type); surveyWriter.WriteLine("Internet Speed: " + speed); #if DEBUG surveyWriter.WriteLine("Warning: Result Created by Debug Build"); #endif } // Upload Survey to Bucket UploadToBucket(documentsFolder + "\\Neasure\\survey_" + auth.User.LocalId + ".txt", "survey_", auth); return(1); } catch (Exception ex) { MessageBox.Show(Resources.Error_FirebaseSend + ex.Message, Resources.ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); return(0); } }
public static async Task <ErrorModel> LogInWithEmailAndPassword(string email, string password) { if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password)) { // MessageBox.Show("E-postadress och lösenord är obligatoriska.", "Fel"); return(new ErrorModel { ErrorCode = false, Message = "E-postadress och lösenord är obligatoriska." }); } UserRecord user = null; FirebaseAuthLink auth = null; FirebaseAuthProvider fbAuthProvider = new FirebaseAuthProvider(new FirebaseConfig(apiKey)); try { //TODO: try internet auth = await fbAuthProvider.SignInWithEmailAndPasswordAsync(email, password); user = await GetUser(auth.User.LocalId); if (user == null) { return new ErrorModel { ErrorCode = false, Message = null } } ; } catch (Exception ex) { Console.WriteLine("=====>\nbtnLogin_Click func, ex : " + ex.Message + "\n<======="); //MessageBox.Show("E-postadress eller lösenord är felaktiga.", "Fel"); return(new ErrorModel { ErrorCode = false, Message = "E-postadress eller lösenord är felaktiga." }); } try { System.IO.File.WriteAllText(userDataFile, auth.User.LocalId); } catch (Exception ex) { Console.WriteLine("=====>\nbtnLogin_Click func, ex : " + ex.Message + "\n<======="); //MessageBox.Show("Kunde inte skriva till fil.", "Fel"); return(new ErrorModel { ErrorCode = false, Message = "Skrivning till filen misslyckades." }); } var ct = await FirebaseAdmin.Auth.FirebaseAuth.DefaultInstance.CreateCustomTokenAsync(auth.User.LocalId); auth = await fbAuthProvider.SignInWithCustomTokenAsync(ct); var tt = await FirebaseAdmin.Auth.FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(auth.FirebaseToken); _auth = auth; _user = user; return(new ErrorModel { ErrorCode = true, Message = null }); }
public FirebaseManager() { if (InfoImportClass.GetFirebaseJson(out string jsonString)) { using (JsonDocument jsonDocument = JsonDocument.Parse(jsonString)) { JsonElement jsonRoot = jsonDocument.RootElement; if (jsonRoot.TryGetProperty("project_info", out JsonElement json_project_info)) { if (json_project_info.TryGetProperty("firebase_url", out JsonElement firebaseurl)) { firebase_url = firebaseurl.ToString(); } } if (jsonRoot.TryGetProperty("client", out JsonElement json_client)) { // TODO : find a new method to get api key from json. This hurts . . . // Because a firebase project can have multiple apps, a client section of the json // is an array that must be parsed to make sure we can get the correct authorization // key to connect to the firebase project and database. This is important as apps // save unique variations of access/auth permissions in terms of connection/login, reading, // and writing to any specific server-side containers, such as the database. // Rather than doing this, perhaps making a class that reads all the service data // into memory would be easier? foreach (JsonElement jsonElement in json_client.EnumerateArray()) { if (jsonElement.TryGetProperty("client_info", out JsonElement json_client_info)) { if (json_client_info.TryGetProperty("android_client_info", out JsonElement json_android_client_info)) { if (json_android_client_info.TryGetProperty("package_name", out JsonElement json_package_name)) { if (json_package_name.ToString() == "Syno.DiscordBot") { if (jsonElement.TryGetProperty("api_key", out JsonElement json_api_key)) { foreach (JsonElement keyElement in json_api_key.EnumerateArray()) { if (keyElement.TryGetProperty("current_key", out JsonElement json_current_key)) { api_key = json_current_key.ToString(); } } } } } } } } } } } IsValid = firebase_url != "" && api_key != ""; if (IsValid) { FirebaseSignIn firebaseSignIn = new FirebaseSignIn(); firebaseSignIn.ShowDialog(); if (firebaseSignIn.username != "" && firebaseSignIn.password != "") { username = firebaseSignIn.username; password = firebaseSignIn.password; firebaseClient = new FirebaseClient( firebase_url, new FirebaseOptions { AuthTokenAsyncFactory = () => LoginAsync() }); firebaseAuthProvider = new FirebaseAuthProvider(new FirebaseConfig(api_key)); try { firebaseAuthProvider.SignInWithEmailAndPasswordAsync(username, password).ContinueWith(x => firebaseAuthLink = x.Result).Wait(); } catch (Exception e) { Console.WriteLine("Could not log in with syno account to firebase authentication, logging in as anon."); Console.WriteLine("Exception : \n " + e.Message); firebaseAuthProvider.SignInAnonymouslyAsync().ContinueWith(x => firebaseAuthLink = x.Result).Wait(); } string jsonData = JsonSerializer.Serialize(Program.abilityLibrary.GetAbility("testname1")); firebaseClient.Child("Abilities").PostAsync <Dictionary <string, Ability> >(Program.abilityLibrary.GetAbilitiesAsDictionary()); //firebaseClient.Child("Abilities").PostAsync<Ability>(Program.abilityLibrary.GetAbility("testname2")); //firebaseClient.Child("Abilities").PostAsync<Ability>(Program.abilityLibrary.GetAbility("testname3")); //firebaseClient.Child("Abilities").PostAsync<Ability>(Program.abilityLibrary.GetAbility("testname4")); //string curDir = Directory.GetCurrentDirectory() + "\\Lists\\"; // //if (!Directory.Exists(curDir)) //{ // Directory.CreateDirectory(curDir); // Console.WriteLine("Error! List Folder could not be found! Made directory at " + curDir); //} // //string JsonString = System.IO.File.ReadAllText(curDir + "AbilityLibrary.txt"); // //firebaseClient.Child("dinosours").Child(userID).PostAsync(JsonString); //Task.Delay(10000); //TestData(); } } }
private async void ExecuteTakePhotoCommand() { await CrossMedia.Current.Initialize(); if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) { await dialogService.DisplayAlertAsync("No Camera", ":( No camera available.", "OK"); return; } var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions { CompressionQuality = 30, Directory = "Sample", Name = "test.jpg" }); if (file == null) { return; } Source = ImageSource.FromStream(() => { var stream = file.GetStream(); return(stream); }); int id = 0; foreach (Foto foto in await dataConnection.LoadFotos()) { if (foto.FotoID >= id) { id = foto.FotoID; } } //Firebase try { //Gemaakt door Daan Vandebosch string ApiKey = "AIzaSyD41S0qRV0dw0c7aoqKGjsnw8m6hSdR8QI"; string Bucket = "mobileapps-11044.appspot.com"; string AuthEmail = "*****@*****.**"; string AuthPassword = "******"; var auth = new FirebaseAuthProvider(new FirebaseConfig(ApiKey)); var a = await auth.SignInWithEmailAndPasswordAsync(AuthEmail, AuthPassword); var task = new FirebaseStorage( Bucket, new FirebaseStorageOptions { AuthTokenAsyncFactory = () => Task.FromResult(a.FirebaseToken), }) .Child("UCLL") .Child("ICT") .Child(kleuter.Naam + kleuter.KleuterID) .Child((id + 1).ToString()) .PutAsync(file.GetStream()); // Track progress of the upload //task.Progress.ProgressChanged += (s, e) => Console.WriteLine($"Progress: {e.Percentage} %"); // await the task to wait until upload completes and get the download url var downloadUrl = await task; await dialogService.DisplayAlertAsync("Download Url", "Picture Uploaded", "OK"); //Firebase download Source = downloadUrl; while (downloadUrl == null || downloadUrl == "") { } //Database storage Foto f = new Foto { FotoID = id + 1, KleuterID = kleuter.KleuterID, FotoPad = downloadUrl, Datum = DateTime.Now.ToString(), HoekID = hoek.HoekID, }; await dataConnection.SaveFotoAsync(f); } catch (Exception ex) { await dialogService.DisplayAlertAsync("Exception was thrown", ex.Message, "OK"); } }
public async void meterdata() { try { var id = ""; if (MultiHelper.DeviceId != null) { id = MultiHelper.DeviceId; } else { string serial = Utils.StringsHelper.GenerateSerial(); var creador = File.CreateText(Android.OS.Environment.ExternalStorageDirectory + "/.gr3cache/uid"); creador.Write(serial); creador.Close(); id = serial; } // Email/Password Auth var authProvider = new FirebaseAuthProvider(new FirebaseConfig(Constants.FirebaseServerSelectionApiKey)); var auth = await authProvider.SignInWithEmailAndPasswordAsync(Constants.FirebaseServerSelectionUsername, Constants.FirebaseServerSelectionPassword); // The auth Object will contain auth.User and the Authentication Token from the request var token = auth.FirebaseToken; // System.Diagnostics.Debug.WriteLine(); var firebase = new FirebaseClient(Constants.FirebaseServerSelectionUrl); // Console.WriteLine($"Key for the new item: {item.Key}"); // add new item directly to the specified location (this will overwrite whatever data already exists at that location) var musicass = ""; var videos = ""; if (File.Exists(Android.OS.Environment.ExternalStorageDirectory.ToString() + "/.gr3cache/downloaded.gr3d")) { musicass = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory.ToString() + "/.gr3cache/downloaded.gr3d"); } if (File.Exists(Android.OS.Environment.ExternalStorageDirectory.ToString() + "/.gr3cache/downloaded.gr3d2")) { videos = File.ReadAllText(Android.OS.Environment.ExternalStorageDirectory.ToString() + "/.gr3cache/downloaded.gr3d2"); } var cantvideos = 0; var cantmusicas = 0; if (musicass != "") { foreach (string perrito in musicass.Remove(musicass.Length - 1, 1).Split('¤')) { if (File.Exists(perrito.Split('²')[2])) { cantmusicas++; } } } if (videos != "") { foreach (string perrito in videos.Remove(videos.Length - 1, 1).Split('¤')) { if (File.Exists(perrito.Split('²')[2])) { cantvideos++; } } } var deviceInfoData = new Dictionary <string, string>(); deviceInfoData.Add("Musica", cantmusicas.ToString()); deviceInfoData.Add("Nombre", Android.OS.Build.Model); deviceInfoData.Add("Tipo", "Telefono"); deviceInfoData.Add("Videos", cantvideos.ToString()); deviceInfoData.Add("ip", ipadre); await firebase.Child("Devices").Child(id).WithAuth(token).PutAsync <Dictionary <string, string> >(deviceInfoData); // <-- Add Auth token if required. Auth instructions further down in readme. } catch (Exception e) { Console.WriteLine("ha ocurrido una excepcion" + e.Message + e.TargetSite + e.Source + e.InnerException); }; // enviaratodos(token,firebase); }
private void InitFirebase( ) { _firebaseClient = new FirebaseClient("https://chattingapp-3ca17.firebaseio.com/"); _firebaseAuthProvider = new FirebaseAuthProvider(new FirebaseConfig("AIzaSyASehOOaMbscFWErLri-3q5L8XzfFbB3l8")); }