Example #1
0
        // GET: LoginPage/LoginPages
        public ActionResult Page()
        {
            UserFacebook user = (UserFacebook)Session["infoUser"];
            var          fb   = new Facebook.FacebookClient();

            fb.AccessToken = user.access_token;
            dynamic avatar = fb.Get("me/accounts?type=page");

            dynamic data = avatar.data;

            lstPage = new List <Models.Pagefb>();

            foreach (dynamic info in data)
            {
                Pagefb page = new Pagefb();
                page.pageId      = info.id;
                page.accessToken = info.access_token;
                page.category    = info.category;
                page.pageName    = info.name;
                page.perms       = info.perms;
                lstPage.Add(page);
            }
            ViewData.Add("pages", lstPage);
            return(View());
        }
Example #2
0
        public ActionResult FacebookCallBack(string code)
        {
            var     fb     = new Facebook.FacebookClient();
            dynamic result = fb.Post("oauth/access_token", new {
                client_id     = ConfigurationManager.AppSettings["FBAppId"],
                client_secret = ConfigurationManager.AppSettings["FBSecret"],
                redirect_uri  = RedirectUri.AbsoluteUri,
                code          = code,
            });

            var accessToken = result.access_token;

            if (!string.IsNullOrEmpty(accessToken))
            {
                fb.AccessToken = accessToken;
                dynamic      me    = fb.Get("me?fields=id,first_name,last_name,email");
                UserFacebook users = new UserFacebook();
                users.user_id      = me.id;
                users.access_token = accessToken;
                users.email        = me.email;
                users.first_name   = me.first_name;
                users.last_name    = me.last_name;

                Session.Add("infoUser", users);
            }
            else
            {
            }

            return(Redirect("/Login/Page"));
        }
        public async Task <bool> LoginAsync()
        {
            bool r = false;

            r = Settings.IsLoggedIn;

            if (!Settings.IsLoggedIn)
            {
                r = await _azureService.LoginAsync();
            }

            if (!r)
            {
                return(false);
            }

            Newtonsoft.Json.Linq.JToken j = await _azureService.GetInfoProvider("/.auth/me");

            Settings.TokenAuthFacebook = j[0].Value <string>("access_token");

            UserFacebook us = await _iFacebookService.GetPublicPerfil(Settings.TokenAuthFacebook);

            User.Email      = us.Email;
            User.UrlPicture = us.UrlPicture;
            User.UID        = us.UID;
            User.FirstName  = us.FirstName;
            User.LastName   = us.LastName;

            return(true);
        }
 private string GenerateErrorRedirect(UserFacebook externalLogin, string message, string redirectUri)
 {
     return(string.Format("{0}?email={1}&provider={2}&err={3}",
                          redirectUri,
                          externalLogin.Email,
                          externalLogin.LoginProvider,
                          message
                          ));
 }
Example #5
0
        private async Task LoadAsync(UserFacebook user)
        {
            var userName = await _userManager.GetUserNameAsync(user);

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;

            Input = new InputModel
            {
                PhoneNumber = phoneNumber
            };
        }
Example #6
0
        private async Task LoadAsync(UserFacebook user)
        {
            var email = await _userManager.GetEmailAsync(user);

            Email = email;

            Input = new InputModel
            {
                NewEmail = email,
            };

            IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
        }
        private string GenerateRedirectUrl(AuthenticationProperties prop, UserFacebook externalLogin, bool hasRegistered, string redirectUri)
        {
            dynamic timeoffset = prop.ExpiresUtc - DateTimeOffset.UtcNow;

            return(string.Format("{0}?external_access_token={1}&provider={2}&haslocalaccount={3}&external_user_name={4}&access_token={5}&refresh_token={6}&expires_in={7}&token_type={8}",
                                 redirectUri,
                                 externalLogin.ExternalAccessToken,
                                 externalLogin.LoginProvider,
                                 hasRegistered.ToString(),
                                 externalLogin.UserName,
                                 prop.Dictionary["access_token"],
                                 prop.Dictionary["refresh_token"],
                                 timeoffset.Ticks.ToString().Substring(0, 5),
                                 "bearer"
                                 ));
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new UserFacebook {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Example #9
0
        public async Task <UserFacebook> GetPublicPerfil(string accessToken)
        {
            var response = await HttpClient.GetAsync($"me?access_token={accessToken}");

            if (response.IsSuccessStatusCode)
            {
                using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                {
                    string ss = await new StreamReader(responseStream).ReadToEndAsync().ConfigureAwait(false);

                    UserFacebook u = JsonConvert.DeserializeObject <UserFacebook>(ss);
                    u.UrlPicture = $"https://graph.facebook.com/{u.UID}/picture?type=large";
                    return(u);
                }
            }

            return(null);
        }
        private async Task LoadSharedKeyAndQrCodeUriAsync(UserFacebook user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
        public IHttpActionResult LoginFacebook([FromBody] string facebookToken)
        {
            if (facebookToken == null)
            {
                return(BadRequest("Token is missing"));
            }
            try
            {
                FacebookLoginDTO model = _facebookValidator.ValidateAndGet(facebookToken);
                if (model == null)
                {
                    return(BadRequest("invalid token"));
                }
                UserFacebook facebookUser = _authManager.LoginFacebook(model);

                var token = _token.GenerateKey(facebookUser.UserId, model.Username, facebookUser.IsAdmin, facebookToken);

                if (_authManager.IsNewFacebookUser(model.FacebookId))
                {
                    _authManager.AddUserToIdentity(facebookUser.UserId, model.Username, model.Email, token);
                    _authManager.AddUserToSocial(facebookUser.UserId, model.Username, token);
                }

                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Headers.Add("x-auth-token", token);
                return(ResponseMessage(response));
            }
            catch (UserBlockedException ube)
            {
                return(BadRequest(ube.Message));
            }
            catch (Exception e)
            {
                _log.Error(e);
                return(InternalServerError());
            }
        }
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new UserFacebook {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }));
                        }

                        await _signInManager.SignInAsync(user, isPersistent : false);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
        public async Task <IHttpActionResult> facebookLogin(string provider, string error = null)
        {
            string redirectUri = string.Empty;
            Dictionary <string, string> AccessToken = null;

            // Validate request
            if (error != null)
            {
                return(BadRequest(Uri.EscapeDataString(error)));
            }

            // Exist Identity
            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

            // Validate redirect url
            var redirectUriValidationResult = ValidateClientAndRedirectUri(Request, ref redirectUri);

            if (!string.IsNullOrWhiteSpace(redirectUriValidationResult))
            {
                return(BadRequest(redirectUriValidationResult));
            }

            // User data from Identity
            UserFacebook externalLogin = UserFacebook.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            // Exist user in db
            Users user          = db.users.Where(u => (u.facebook_id == externalLogin.ProviderKey && u.email == externalLogin.Email && u.source == "facebook")).FirstOrDefault();
            bool  hasRegistered = user != null;

            // If not identity register to db add new user
            if (!hasRegistered)
            {
                try
                {
                    // check user e-mail exist validation
                    if (db.users.Any(u => u.email == externalLogin.Email))
                    {
                        return(Redirect(GenerateErrorRedirect(externalLogin, "e-posta zaten kullanilmakta", redirectUri)));
                    }

                    string password = Users.generatePassword(5, 3);

                    //generate activation code
                    Random rnd        = new Random();
                    string gsm_code   = rnd.Next(9999, 999999).ToString();
                    string email_code = rnd.Next(9999, 999999).ToString();

                    // disable db validations
                    db.Configuration.ValidateOnSaveEnabled = false;

                    // create user
                    Users userData = new Users
                    {
                        name                  = externalLogin.FirstName,
                        lastname              = externalLogin.LastName,
                        email                 = externalLogin.Email,
                        facebook_id           = externalLogin.ProviderKey,
                        gender                = externalLogin.Gender == "male" ? "Bay" : "Bayan",
                        gsm                   = string.Empty,
                        password              = Bcrypt.hash(password),
                        source                = "facebook",
                        email_activation_code = email_code,
                        gsm_activation_code   = gsm_code,
                        is_external_confirm   = false,
                    };
                    db.users.Add(userData);

                    // save photos
                    byte[] imageData = null;
                    using (var wc = new System.Net.WebClient())
                        imageData = wc.DownloadData(externalLogin.Photo.Data.Url);
                    MemoryStream photoStreamData = new MemoryStream(imageData);

                    // send cloud
                    var    image       = new WebImage(photoStreamData);
                    var    httpRequest = HttpContext.Current.Request;
                    Images userImage   = Cloudinary.upload(image, "users/" + userData.name.ReduceWhitespace().Replace(" ", "-").ToEng() + "-" + userData.lastname.ReduceWhitespace().Replace(" ", "-").ToEng() + "-" + userData.id);
                    if (userImage != null)
                    {
                        db.images.Add(userImage);
                        db.SaveChanges();
                        userData.image_id = userImage.id;
                    }

                    db.SaveChanges();

                    // enable db validations
                    db.Configuration.ValidateOnSaveEnabled = false;

                    return(Redirect(GenerateRedirectUrl(AuthBackdoor.auth(userData, Request), externalLogin, hasRegistered, redirectUri)));
                }
                catch (Exception ex)
                {
                    return(Redirect(GenerateErrorRedirect(externalLogin, ex.Message.ToString(), redirectUri)));
                }
            }
            return(Redirect(GenerateRedirectUrl(AuthBackdoor.auth(user, Request), externalLogin, hasRegistered, redirectUri)));
        }
Example #14
0
        public void Insert(long? FbUid,int UserKey,string FbLocation,string FbEmail,int? FbFriendsCount,string FbAccessToken,DateTime? DateCreated,DateTime? LastChanged,bool? FbIsmale,string FbFirstName,string FbLastName,bool? FbIsverified)
        {
            UserFacebook item = new UserFacebook();

            item.FbUid = FbUid;

            item.UserKey = UserKey;

            item.FbLocation = FbLocation;

            item.FbEmail = FbEmail;

            item.FbFriendsCount = FbFriendsCount;

            item.FbAccessToken = FbAccessToken;

            item.DateCreated = DateCreated;

            item.LastChanged = LastChanged;

            item.FbIsmale = FbIsmale;

            item.FbFirstName = FbFirstName;

            item.FbLastName = FbLastName;

            item.FbIsverified = FbIsverified;

            item.Save(UserName);
        }