public async Task <IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var info = await Authentication.GetExternalLoginInfoAsync();

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

            var user = new FSMIdentityUser()
            {
                UserName = model.Email, Email = model.Email
            };

            IdentityResult result = await UserManager.CreateAsync(user);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }

            result = await UserManager.AddLoginAsync(user.Id, info.Login);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }
            return(Ok());
        }
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

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

            ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);

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

            if (externalLogin.LoginProvider != provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                return(new ChallengeResult(provider, this));
            }

            FSMIdentityUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
                                                                                 externalLogin.ProviderKey));

            bool hasRegistered = user != null;

            if (hasRegistered)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
            }
            else
            {
                IEnumerable <Claim> claims   = externalLogin.GetClaims();
                ClaimsIdentity      identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
                Authentication.SignIn(identity);
            }

            return(Ok());
        }
Exemplo n.º 3
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager <FSMUserManager>();

            FSMIdentityUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
            //dbFSMEntities db = new dbFSMEntities();
            //var us = (from i in db.tbNhanviens where i.USERNAME.Equals(context.UserName) && i.KHOA == 0 select i).FirstOrDefault();
            //if (us == null)
            //{
            //    context.SetError("invalid_grant", "The user name was locked.");
            //    return;
            //}
            OAMS.MyHub.ChatHub.checkLogin(context.UserName);
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                                                                                  CookieAuthenticationDefaults.AuthenticationType);

            var    roles    = userManager.GetRoles(user.Id);
            string rulename = "";

            if (roles.Count > 0)
            {
                rulename = roles[0];
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, rulename));
                cookiesIdentity.AddClaim(new Claim(ClaimTypes.Role, rulename));
            }
            AuthenticationProperties properties = CreateProperties(user.UserName, rulename);

            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
            Nhatkyhethong.insertLog(user.UserName, "Đăng nhập hệ thống", 1);
        }
        public async Task <ManageInfoViewModel> GetManageInfo(string returnUrl, bool generateState = false)
        {
            FSMIdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            if (user == null)
            {
                return(null);
            }

            List <UserLoginInfoViewModel> logins = new List <UserLoginInfoViewModel>();

            foreach (IdentityUserLogin linkedAccount in user.Logins)
            {
                logins.Add(new UserLoginInfoViewModel
                {
                    LoginProvider = linkedAccount.LoginProvider,
                    ProviderKey   = linkedAccount.ProviderKey
                });
            }

            if (user.PasswordHash != null)
            {
                logins.Add(new UserLoginInfoViewModel
                {
                    LoginProvider = LocalLoginProvider,
                    ProviderKey   = user.UserName,
                });
            }

            return(new ManageInfoViewModel
            {
                LocalLoginProvider = LocalLoginProvider,
                Email = user.UserName,
                Logins = logins,
                ExternalLoginProviders = GetExternalLogins(returnUrl, generateState)
            });
        }
        public async Task <IHttpActionResult> Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new FSMIdentityUser()
            {
                UserName = model.Username, Email = model.Email
            };

            IdentityResult result = await UserManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(GetErrorResult(result));
            }
            try
            {
                dbOAMSEntities db = new dbOAMSEntities();
                if (model.CHUCVU.checkIsNull() == "")
                {
                    db.Database.ExecuteSqlCommand("insert into [users].[tbNguoidung](ID,USERNAME,HOLOT,TEN,BOPHAN,NGAYTAO,Email,HANCHE,KHOA) values(" +
                                                  " @ID, @USERNAME, @HOLOT, @TEN, @BOPHAN, @NGAYTAO, @Email, @HANCHE, @KHOA)",
                                                  new System.Data.SqlClient.SqlParameter("@ID", user.Id),
                                                  new System.Data.SqlClient.SqlParameter("@USERNAME", model.Username),
                                                  new System.Data.SqlClient.SqlParameter("@HOLOT", model.HOLOT),
                                                  new System.Data.SqlClient.SqlParameter("@TEN", model.TEN),
                                                  new System.Data.SqlClient.SqlParameter("@BOPHAN", model.BOPHAN.checkIsNull()),
                                                  new System.Data.SqlClient.SqlParameter("@NGAYTAO", DateTime.Now),
                                                  new System.Data.SqlClient.SqlParameter("@Email", model.Email),
                                                  new System.Data.SqlClient.SqlParameter("@HANCHE", false),
                                                  new System.Data.SqlClient.SqlParameter("@KHOA", model.KHOA.checkBoolIsNull())
                                                  );
                }
                else
                {
                    db.Database.ExecuteSqlCommand("insert into [users].[tbNguoidung](ID,USERNAME,HOLOT,TEN,BOPHAN,CHUCVU,NGAYTAO,Email,HANCHE,KHOA) values(" +
                                                  " @ID, @USERNAME, @HOLOT, @TEN, @BOPHAN, @CHUCVU, @NGAYTAO, @Email, @HANCHE, @KHOA)",
                                                  new System.Data.SqlClient.SqlParameter("@ID", user.Id),
                                                  new System.Data.SqlClient.SqlParameter("@USERNAME", model.Username),
                                                  new System.Data.SqlClient.SqlParameter("@HOLOT", model.HOLOT),
                                                  new System.Data.SqlClient.SqlParameter("@TEN", model.TEN),
                                                  new System.Data.SqlClient.SqlParameter("@BOPHAN", model.BOPHAN.checkIsNull()),
                                                  new System.Data.SqlClient.SqlParameter("@CHUCVU", model.CHUCVU.checkIsNull()),
                                                  new System.Data.SqlClient.SqlParameter("@NGAYTAO", DateTime.Now),
                                                  new System.Data.SqlClient.SqlParameter("@Email", model.Email),
                                                  new System.Data.SqlClient.SqlParameter("@HANCHE", false),
                                                  new System.Data.SqlClient.SqlParameter("@KHOA", model.KHOA.checkBoolIsNull())
                                                  );
                }

                return(Ok(1));
            }
            catch (Exception e)
            {
                dbOAMSEntities db = new dbOAMSEntities();
                db.Database.ExecuteSqlCommand("delete [dbo].[AspNetUsers] where Id = @id",
                                              new System.Data.SqlClient.SqlParameter("@id", user.Id));
                return(BadRequest());
            }
            return(Ok(1));
        }