示例#1
0
        public async Task <IActionResult> GoogleLogin([FromBody] GoogleLoginViewModel info)
        {
            #region Request params validation

            if (info == null)
            {
                info = new GoogleLoginViewModel();
                TryValidateModel(info);
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            #endregion

            #region Google login

            var user = await _userDomain.GoogleLoginAsync(info);

            var jsonWebToken = _userDomain.GenerateJwt(user);

            #endregion

            return(Ok(jsonWebToken));
        }
示例#2
0
        /// <summary>
        ///     <inheritdoc />
        /// </summary>
        /// <param name="model"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public virtual async Task <User> GoogleLoginAsync(GoogleLoginViewModel model,
                                                          CancellationToken cancellationToken = default(CancellationToken))
        {
            // Get the profile information.
            var profile = await _externalAuthenticationService.GetGoogleBasicProfileAsync(model.IdToken);

            if (profile == null)
            {
                throw new ApiException(HttpMessages.GoogleCodeIsInvalid, HttpStatusCode.Forbidden);
            }

            // Find accounts by searching for email address.
            var users = _unitOfWork.Accounts.Search();

            users = users.Where(x => x.Email.Equals(profile.Email));

            // Get the first matched account.
            var user = await users.FirstOrDefaultAsync(cancellationToken);

            // Account is available in the system. Check its status.
            if (user != null)
            {
                // Prevent account from logging into system because it is pending.
                if (user.Status == UserStatus.Pending)
                {
                    throw new ApiException(HttpMessages.AccountIsPending, HttpStatusCode.Forbidden);
                }

                // Prevent account from logging into system because it is deleted.
                if (user.Status == UserStatus.Disabled)
                {
                    throw new ApiException(HttpMessages.AccountIsDisabled, HttpStatusCode.Forbidden);
                }
            }
            else
            {
                // Initialize account instance.
                user = new User();

#if USE_IN_MEMORY
                user.Id = _unitOfWork.Accounts.Search().OrderByDescending(x => x.Id).Select(x => x.Id)
                          .FirstOrDefault() + 1;
#endif
                user.Email      = profile.Email;
                user.Nickname   = profile.Name;
                user.Role       = UserRole.User;
                user.Photo      = profile.Picture;
                user.JoinedTime = _baseTimeService.DateTimeUtcToUnix(DateTime.UtcNow);
                user.Type       = UserKind.Google;
                user.Status     = UserStatus.Available;

                // Add account to database.
                _unitOfWork.Accounts.Insert(user);
                await _unitOfWork.CommitAsync(cancellationToken);
            }
            return(user);
        }
示例#3
0
        public ActionResult GoogleLoginCallback()
        {
            var claimsPrincipal = HttpContext.User.Identity as ClaimsIdentity;

            var loginInfo = GoogleLoginViewModel.GetLoginInfo(claimsPrincipal);

            if (loginInfo == null)
            {
                return(RedirectToAction("Index"));
            }

            var user = db.Members.FirstOrDefault(x => x.MemberAccount == loginInfo.nameidentifier);

            if (user == null)
            {
                user = new Member
                {
                    Email         = loginInfo.emailaddress,
                    Name          = loginInfo.givenname + loginInfo.surname,
                    MemberAccount = loginInfo.nameidentifier,
                    EmailVerified = true,
                    Password      = "******",
                    HashCode      = loginInfo.nameidentifier,
                    Address       = "Google",
                    Phone         = "Google"
                };
                db.Members.Add(user);
                db.SaveChanges();
            }

            var ident = new ClaimsIdentity(
                new[] {
                // adding following 2 claim just for supporting default antiforgery provider
                new Claim(ClaimTypes.NameIdentifier, user.Email),
                new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

                new Claim(ClaimTypes.Name, user.Name),
                new Claim(ClaimTypes.Email, user.Email),
                // optionally you could add roles if any
                new Claim(ClaimTypes.Role, "User")
            },
                CookieAuthenticationDefaults.AuthenticationType, "Google", user.MemberID.ToString());


            HttpContext.GetOwinContext().Authentication.SignIn(
                new AuthenticationProperties {
                IsPersistent = false
            }, ident);
            return(Redirect("~/"));
        }
示例#4
0
        public ActionResult GoogleLoginCallback()
        {
            var claimsPrincipal = HttpContext.User.Identity as ClaimsIdentity;

            var loginInfo = GoogleLoginViewModel.GetLoginInfo(claimsPrincipal);

            if (loginInfo == null)
            {
                return(RedirectToAction("Index"));
            }

            AccountRepository acdb = new AccountRepository();
            UserAccount       user = acdb.GetByMail(loginInfo.EmailAddress);

            if (user == null)
            {
                user = new UserAccount
                {
                    Id         = Guid.NewGuid(),
                    Email      = loginInfo.EmailAddress,
                    GivenName  = loginInfo.GivenName,
                    Identifier = loginInfo.NameIdentifier,
                    Name       = loginInfo.Name,
                    SurName    = loginInfo.Surname,
                    IsActive   = true
                };
                acdb.Insert(user);
                acdb.Save();
            }

            var ident = new ClaimsIdentity(
                new[] {
                // adding following 2 claim just for supporting default antiforgery provider
                new Claim(ClaimTypes.NameIdentifier, user.Email),
                new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

                new Claim(ClaimTypes.Name, user.Name),
                new Claim(ClaimTypes.Email, user.Email),
            },
                CookieAuthenticationDefaults.AuthenticationType);

            HttpContext.GetOwinContext().Authentication.SignIn(
                new AuthenticationProperties {
                IsPersistent = false
            }, ident);
            return(Redirect("~/"));
        }
示例#5
0
        public ActionResult GoogleLoginCallback()
        {
            var claimsPrincipal = HttpContext.User.Identity as ClaimsIdentity;

            var loginInfo = GoogleLoginViewModel.GetLoginInfo(claimsPrincipal);

            if (loginInfo == null)
            {
                return(RedirectToAction("Index"));
            }

            List <Login> login       = GetLoginDetail();
            var          loginDetail = login.FirstOrDefault(x => x.UserName == loginInfo.emailaddress);

            if (loginDetail == null)
            {
                loginDetail = new Login
                {
                    UserName = loginInfo.emailaddress,
                };
                login.Add(loginDetail);
                //db.SaveChanges();
            }

            var ident = new ClaimsIdentity(
                new[] {
                // adding following 2 claim just for supporting default antiforgery provider
                new Claim(ClaimTypes.NameIdentifier, loginDetail.UserName),
                new Claim(ClaimTypes.Name, loginDetail.UserName),
                new Claim(ClaimTypes.Email, loginDetail.UserName),
                // optionally you could add roles if any
                new Claim(ClaimTypes.Role, "User")
            },
                CookieAuthenticationDefaults.AuthenticationType);


            HttpContext.GetOwinContext().Authentication.SignIn(
                new AuthenticationProperties {
                IsPersistent = true
            }, ident);
            return(Redirect(Url.Content("~/")));
        }
示例#6
0
        public ActionResult GoogleLoginCallback()
        {
            var claimsPrincipal = HttpContext.User.Identity as ClaimsIdentity;
            var loginInfo       = GoogleLoginViewModel.GetLoginInfo(claimsPrincipal);

            if (loginInfo == null)
            {
                return(View("SignIn"));
            }
            SandeepDBEntities db = new SandeepDBEntities();
            var user             = db.UserAccount.FirstOrDefault(x => x.Email == loginInfo.emailaddress);

            if (user == null)
            {
                user = new UserAccount
                {
                    Email      = loginInfo.emailaddress,
                    GivenName  = loginInfo.givenname,
                    Identifier = loginInfo.nameidentifier,
                    Name       = loginInfo.name,
                    SurName    = loginInfo.surname,
                    IsActive   = true
                };
                var roleInsert = new Models.Roles
                {
                    Id       = user.Id,
                    RoleName = "user"
                };
                db.UserAccount.Add(user);
                db.Roles.Add(roleInsert);
                db.SaveChanges();
            }

            Response.Cookies["Cookie"]["RoleName"] = db.Roles.FirstOrDefault(x => x.Id == user.Id).RoleName;
            string str = Response.Cookies["Cookie"]["RoleName"];

            return(Redirect("signin"));
        }
        public ActionResult GoogleLoginCallback()
        {
            var claimsPrincipal = HttpContext.User.Identity as ClaimsIdentity;

            var loginInfo = GoogleLoginViewModel.GetLoginInfo(claimsPrincipal);

            if (loginInfo == null)
            {
                return(RedirectToAction("Index"));
            }



            var user = db.KHACHHANGs.FirstOrDefault(x => x.EMAIL == loginInfo.emailaddress);

            Session["MAKH"]  = user.MAKH.ToString();
            Session["HoTen"] = user.HOTEN.ToString();
            try
            {
                if (user == null)
                {
                    user = new KHACHHANG
                    { //kh.GIOITINH = null;
                      //kh.MATKHAU = null;
                      //kh.NGAYSINH = null;
                      //kh.DIACHI = null;
                      //kh.DIENTHOAI = null;
                      //kh.HOTEN = fullName;
                      //kh.TRANGTHAI = true;
                        GIOITINH  = null,
                        NGAYSINH  = null,
                        TRANGTHAI = true,
                        EMAIL     = loginInfo.emailaddress,
                        HOTEN     = loginInfo.surname + loginInfo.givenname,
                        DIENTHOAI = null,
                        MATKHAU   = null,
                        DIACHI    = null,
                    };
                    db.KHACHHANGs.Add(user);

                    db.SaveChanges();
                }
            }
            catch (DbEntityValidationException e)
            { }


            var ident = new ClaimsIdentity(
                new[] {
                // adding following 2 claim just for supporting default antiforgery provider
                new Claim(ClaimTypes.NameIdentifier, user.EMAIL),
                new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

                new Claim(ClaimTypes.Name, user.HOTEN),
                new Claim(ClaimTypes.Email, user.EMAIL),
                // optionally you could add roles if any
                new Claim(ClaimTypes.Role, "User")
            },
                CookieAuthenticationDefaults.AuthenticationType);


            HttpContext.GetOwinContext().Authentication.SignIn(
                new AuthenticationProperties {
                IsPersistent = false
            }, ident);
            var thongTinKhachHang = db.KHACHHANGs.FirstOrDefault(n => n.EMAIL == user.EMAIL);

            Session["MAKH"]  = thongTinKhachHang.MAKH;
            Session["HoTen"] = thongTinKhachHang.HOTEN; Session["EMAIL"] = thongTinKhachHang.EMAIL;
            return(Redirect("~/"));
        }
        public async Task <IActionResult> GoogleLogin([FromBody] GoogleLoginViewModel vm)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var user = await _userManager.FindByEmailAsync(vm.email);

            string password = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8);

            if (user == null)
            {
                var u = new GXUser()
                {
                    Email      = vm.email,
                    UserName   = vm.email,
                    googleId   = vm.googleId,
                    photoUrl   = vm.photoUrl,
                    firstName  = vm.name,
                    gender     = "",
                    dateJoined = DateTime.Now
                };

                var result = await _userManager.CreateAsync(u, password);

                if (!result.Succeeded)
                {
                    return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState)));
                }

                user = await _userManager.FindByEmailAsync(vm.email);
            }
            else
            {
                user.googleId = vm.googleId;
                user.photoUrl = vm.photoUrl;
                _context.Users.Update(user);
                await _context.SaveChangesAsync();
            }

            var identity = await Task.FromResult(_jwtFactory.GenerateClaimsIdentity(user.UserName, user.Id));

            var jwt = await Tokens.GenerateJwt(identity, _jwtFactory, user.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });


            return(Ok(new
            {
                Id = user.Id,
                userName = user.UserName,
                firstName = user.firstName,
                lastName = user.lastName,
                email = user.Email,
                facebookId = user.facebookId,
                gender = user.gender,
                twitterId = user.twitterId,
                googleId = user.googleId,
                birthDate = user.birthDate,
                photoUrl = !string.IsNullOrEmpty(user.photoUrl) ? user.photoUrl : "/assets/images/profile-pic.png",
                token = jwt
            }));
        }