public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginViewModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    throw new ApplicationException("Error loading external login information during confirmation.");
                }
                var user = new MyIdentityUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user);

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

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(nameof(ExternalLogin), model));
        }
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new MyIdentityUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

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

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                    await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

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

                    _logger.LogInformation("User created a new account with password.");
                    return(RedirectToLocal(returnUrl));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #3
0
        public ActionResult Register(Register model)
        {
            if (ModelState.IsValid)
            {
                MyIdentityUser user = new MyIdentityUser();
                user.UserName     = model.Email;
                user.Email        = model.Email;
                user.FirstName    = model.FirstName;
                user.LastName     = model.LastName;
                user.MobileNumber = model.MobileNumber;
                user.CreatedBy    = User.Identity.GetUserId();
                IdentityResult result = userManager.Create(user, model.Password);
                if (result.Succeeded)
                {
                    userManager.AddToRole(user.Id, "Administrator");

                    return(RedirectToAction("Login", "Account"));
                }
                else
                {
                    ModelState.AddModelError("UserName", "Error while creating the user!");
                }
            }
            return(View(model));
        }
コード例 #4
0
        public IActionResult Register([FromBody] RegisterViewModel registerObj)
        {
            if (ModelState.IsValid)
            {
                MyIdentityUser user = new MyIdentityUser();
                user.UserName  = registerObj.UserName;
                user.Email     = registerObj.Email;
                user.FullName  = registerObj.FullName;
                user.BirthDate = registerObj.BirthDate;

                IdentityResult result = _userManager.CreateAsync(user, registerObj.Password).Result;
                _logger.LogError(result.ToString());
            }
            else
            {
                foreach (var modelStateValue in ModelState.Values)
                {
                    foreach (var modelError in modelStateValue.Errors)
                    {
                        _logger.LogError(modelError.Exception, modelError.ErrorMessage);
                    }
                }
            }

            return(Json(true));
        }
コード例 #5
0
 public AuthenticateResponse(MyIdentityUser user, string token)
 {
     Id       = user.Id;
     FullName = user.FullName;
     Phone    = user.PhoneNumber;
     Token    = token;
 }
コード例 #6
0
        public async Task <ActionResult> Register(RegisterUser registerUser)
        {
            if (!ModelState.IsValid)
            {
                return(CustomResponse(ModelState));
            }

            var user = new MyIdentityUser
            {
                UserName       = registerUser.Email,
                Email          = registerUser.Email,
                EmailConfirmed = true
            };

            var result = await _userManager.CreateAsync(user, registerUser.Password);

            if (result.Succeeded)
            {
                return(CustomResponse(GetUserResponse(user.Email)));
            }

            foreach (var error in result.Errors)
            {
                AddError(error.Description);
            }

            return(CustomResponse());
        }
コード例 #7
0
        private async Task <string> GenerateJWT(MyIdentityUser user)
        {
            try
            {
                IList <string> iListRoleUser = await this._UserManager.GetRolesAsync(user);

                List <Claim> listClaimUser = new List <Claim>
                {
                    new Claim("MaNguoiDung", user.Id.ToString()),
                    new Claim("TenDangNhap", user.UserName),
                    new Claim("HoTen", user.FullName),
                    new Claim("SoDienThoai", user.PhoneNumber),
                    new Claim("NgaySinh", user.DateOfBirth?.ToString() ?? "Trống"),
                    new Claim("Email", user.Email),
                    new Claim("DiaChi", user.Address ?? "Trống"),
                };

                string roleUser = iListRoleUser.First();
                listClaimUser.Add(new Claim(ClaimTypes.Role, roleUser));
                listClaimUser.Add(new Claim("ChucVu", roleUser));
                string key    = _IConfiguration["JWT:Key"];
                string issuer = _IConfiguration["JWT:Issuer"];
                SymmetricSecurityKey symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
                SigningCredentials   signingCredentials   = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
                JwtSecurityToken     jwtSecurityToken     = new JwtSecurityToken(issuer, issuer, listClaimUser, expires: DateTime.Now.AddHours(1), signingCredentials: signingCredentials);
                string jwt = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
                return(await Task.FromResult <string>(jwt));
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #8
0
        public ActionResult Register(Register model)
        {
            if (ModelState.IsValid)
            {
                var user = new MyIdentityUser();

                user.UserName  = model.UserName;
                user.Email     = model.Email;
                user.FullName  = model.FullName;
                user.BirthDate = model.BirthDate;
                user.Bio       = model.Bio;

                IdentityResult result = userManager.Create(user, model.Password);

                //redirection to login page
                if (result.Succeeded)
                {
                    //Pour l'exemple on donne les droits admin au nouvel utilisateur
                    userManager.AddToRole(user.Id, "Administrator");
                    return(RedirectToAction("Login", "Account"));
                }
                else
                {
                    ModelState.AddModelError("UserName", "Error while creating the user!");
                }
            }
            return(View(model));
        }
コード例 #9
0
        public async Task <MyServiceResult> ResetPassword(string userId, string newPassword)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userId))
                {
                    return(new MyServiceResult
                    {
                        Successed = false,
                        Content = "Người dùng không tồn tại"
                    });
                }
                MyIdentityUser objMyIdentityUser = await this._UserManager.FindByIdAsync(userId);

                if (objMyIdentityUser is null)
                {
                    return(new MyServiceResult
                    {
                        Successed = false,
                        Content = "Người dùng không tồn tại"
                    });
                }

                IdentityResult objIdentityResultRemove = await this._UserManager.RemovePasswordAsync(objMyIdentityUser);

                if (objIdentityResultRemove.Succeeded)
                {
                    IdentityResult objIdentityResultAdd = await this._UserManager.AddPasswordAsync(objMyIdentityUser, newPassword);

                    if (objIdentityResultAdd.Succeeded)
                    {
                        return(new MyServiceResult
                        {
                            Successed = true,
                            Content = "Đặt lại mật khẩu thành công"
                        });
                    }
                    else
                    {
                        return(new MyServiceResult
                        {
                            Successed = false,
                            Content = "Đặt lại mật khẩu thất bại"
                        });
                    }
                }
                else
                {
                    return(new MyServiceResult
                    {
                        Successed = false,
                        Content = "Đặt lại mật khẩu thất bại"
                    });
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #10
0
        public async Task <MyServiceObjectResult <MyUserInfoModel> > GetInformation(string userId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(userId))
                {
                    return(new MyServiceObjectResult <MyUserInfoModel>
                    {
                        Successed = false,
                        Content = "Người dùng không tồn tại"
                    });
                }
                MyIdentityUser objMyIdentityUser = await this._UserManager.FindByIdAsync(userId);

                if (objMyIdentityUser is null)
                {
                    return(new MyServiceObjectResult <MyUserInfoModel>
                    {
                        Successed = false,
                        Content = "Người dùng không tồn tại"
                    });
                }
                MyUserInfoModel CUserModel = this._IMapper.Map <MyUserInfoModel>(objMyIdentityUser);
                return(new MyServiceObjectResult <MyUserInfoModel>
                {
                    Successed = true,
                    Content = "Lấy thông tin thành công",
                    Object = CUserModel
                });
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #11
0
        public async Task <ActionResult> Register(CustomRegisterUser registerUser)
        {
            var user = new MyIdentityUser
            {
                UserName       = registerUser.Name,
                Email          = registerUser.Email,
                EmailConfirmed = true
            };

            var result = await _userManager.CreateAsync(user, registerUser.Password);


            if (result.Succeeded)
            {
                await _userManager.AddToRoleAsync(user, Roles.BASIC);

                await _userManager.AddClaimAsync(user, new Claim(Claims.Sample, ClaimsValues.READ));

                await _userManager.AddClaimAsync(user, new Claim(Claims.Sample, ClaimsValues.WRITE));

                return(Ok(createToken(user.UserName)));
            }
            else
            {
                var error = new BadRequestError();
                foreach (var item in result.Errors)
                {
                    error.AddMessage(item.Description);
                }
                var json = ErrorFormat.SerializeError(ModelState, error);
                return(BadRequest(json));
            }
        }
コード例 #12
0
        public ActionResult Create([Bind(Include = "Id,LastName,FirstName,Phone,Email,SellerAccount,Login,Password")] Seller seller)
        {
            if (ModelState.IsValid)
            {
                // Creation du vendeur dans le SecurityContext du projet ASP.NET
                using (var secudb = new SecurityDbContext())
                {
                    IdentityRole userRole = RoleUtils.CreateOrGetRole("User");
                    UserManager <MyIdentityUser> userManager = new MyIdentityUserManager(new UserStore <MyIdentityUser>(secudb));
                    MyIdentityUser sellerUser = new MyIdentityUser()
                    {
                        UserName = seller.Login, Email = seller.Email, Login = seller.Login
                    };;
                    var result = userManager.Create(sellerUser, seller.Password);
                    if (!result.Succeeded)
                    {
                        throw new System.Exception("database insert fail");
                    }
                    RoleUtils.AssignRoleToUser(userRole, sellerUser);
                }

                // Creation du vendeur dans le ProductContext du projet librairie
                db.Sellers.Add(seller);
                db.SaveChanges();

                return(RedirectToAction("Index"));
            }

            return(View(seller));
        }
コード例 #13
0
        public JsonResult SavePurchase(ProductReceive O)
        {
            bool status = false;

            if (ModelState.IsValid)
            {
                MyIdentityDbContext          db          = new MyIdentityDbContext();
                UserStore <MyIdentityUser>   userStore   = new UserStore <MyIdentityUser>(db);
                UserManager <MyIdentityUser> userManager = new UserManager <MyIdentityUser>(userStore);
                MyIdentityUser user = userManager.FindByName(HttpContext.User.Identity.Name);

                O.DateReceived = DateTime.Now;
                O.UserId       = user.Id;
                _productReceiveService.AddProductReceive(O);
                //Order order = new Order { OrderNo = O.OrderNo, OrderDate = O.OrderDate, Description = O.Description };
                //foreach (var i in O.OrderDetails)
                //{
                //    //
                //    // i.TotalAmount =
                //    order.OrderDetails.Add(i);
                //}
                //dc.Orders.Add(order);
                //dc.SaveChanges();
                status = true;
            }
            else
            {
                status = false;
            }
            return(new JsonResult {
                Data = new { status = status }
            });
        }
コード例 #14
0
        public ActionResult Register(Register model)
        {
            ClientValidationEdit(model);

            if (ModelState.IsValid)
            {
                MyIdentityUser user = new MyIdentityUser();

                user.UserName = model.UserName;
                user.Email    = model.Email;

                IdentityResult result = userManager.Create(user, model.Password);

                if (result.Succeeded)
                {
                    userManager.AddToRole(user.Id, "AdminD");

                    return(RedirectToAction("Create", "Clients", new { model.Email }));
                }
                else
                {
                    ModelState.AddModelError("UserName", "Ошибка при создании пользователя!");
                }
            }
            return(View(model));
        }
コード例 #15
0
 public ActionResult Login(Login model, string returnUrl)
 {
     if (ModelState.IsValid)
     {
         MyIdentityUser user = userManager.Find(model.UserName, model.Password);
         if (user != null)
         {
             IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
             authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
             ClaimsIdentity           identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
             AuthenticationProperties props    = new AuthenticationProperties();
             props.IsPersistent = model.RememberMe;
             authenticationManager.SignIn(props, identity);
             Session["USER_INFO"] = user;
             if (Url.IsLocalUrl(returnUrl))
             {
                 return(Redirect(returnUrl));
             }
             else
             {
                 return(RedirectToAction("Index", "Home"));
             }
         }
         else
         {
             ModelState.AddModelError("", "Invalid username or password.");
         }
     }
     return(View(model));
 }
コード例 #16
0
        public ActionResult Register(Register model, string RoleList, int BranchList)
        {
            ViewBag.RoleList   = new SelectList(roleManager.Roles, "Id", "Name", RoleList);
            ViewBag.BranchList = new SelectList(_branchService.GetAllBranches(), "BranchId", "BranchName", BranchList);
            if (ModelState.IsValid)
            {
                MyIdentityUser user = new MyIdentityUser();

                user.UserName  = model.UserName;
                user.Email     = model.Email;
                user.FullName  = model.FullName;
                user.BirthDate = model.BirthDate;
                user.Bio       = model.Bio;
                user.Role      = roleManager.FindById(RoleList).Name;
                user.BranchId  = BranchList;

                IdentityResult result = userManager.Create(user, model.Password);

                if (result.Succeeded)
                {
                    userManager.AddToRole(user.Id, roleManager.FindById(RoleList).Name);
                    return(RedirectToAction("Users", "Account"));
                }
                else
                {
                    ModelState.AddModelError("UserName", "Error while creating the user!");
                }
            }
            return(View(model));
        }
コード例 #17
0
        public ActionResult Create([Bind(Include = "CustomerId,SalesType,ReferenceNo")] SalesInvoiceViewModel salesInvoiceViewModel, int CustomerList,
                                   int BranchList, int?SalesTypeList)
        {
            if (ModelState.IsValid)
            {
                var exists = _salesInvoiceService.Get(t => t.ReferenceNo == salesInvoiceViewModel.ReferenceNo).FirstOrDefault();
                if (exists != null)
                {
                    return(View(salesInvoiceViewModel));
                }

                MyIdentityDbContext          db          = new MyIdentityDbContext();
                UserStore <MyIdentityUser>   userStore   = new UserStore <MyIdentityUser>(db);
                UserManager <MyIdentityUser> userManager = new UserManager <MyIdentityUser>(userStore);
                MyIdentityUser user = userManager.FindByName(HttpContext.User.Identity.Name);

                var salesInvoice = new SalesInvoice()
                {
                    BranchId    = BranchList,
                    CustomerId  = CustomerList,
                    ReferenceNo = salesInvoiceViewModel.ReferenceNo,
                    SalesType   = SalesTypeList ?? 0,
                    UserId      = user.Id,
                    DateSold    = DateTime.Now,
                    Status      = "Draft"
                };

                _salesInvoiceService.AddSalesInvoice(salesInvoice);

                return(RedirectToAction("Create", "SalesInvoices", new { id = salesInvoice.SalesInvoiceId }));
            }

            return(View(salesInvoiceViewModel));
        }
コード例 #18
0
        public JsonResult SaveTransfer(ProductTransfer O)
        {
            bool status = false;

            if (ModelState.IsValid)
            {
                MyIdentityDbContext          db          = new MyIdentityDbContext();
                UserStore <MyIdentityUser>   userStore   = new UserStore <MyIdentityUser>(db);
                UserManager <MyIdentityUser> userManager = new UserManager <MyIdentityUser>(userStore);
                MyIdentityUser user = userManager.FindByName(HttpContext.User.Identity.Name);

                O.DateTransfered = DateTime.Now;
                O.UserId         = user.Id;

                _productTransferService.AddProductTransfer(O);
                status = true;
            }
            else
            {
                status = false;
            }
            return(new JsonResult {
                Data = new { status = status }
            });
        }
コード例 #19
0
        public IActionResult Register(RegisterViewModel regiModel)
        {
            if (ModelState.IsValid)
            {
                MyIdentityUser user = new MyIdentityUser();
                user.UserName  = regiModel.UserName;
                user.Email     = regiModel.Email;
                user.FullName  = regiModel.FullName;
                user.BirthDate = regiModel.BirthDate;

                IdentityResult result = userManager.CreateAsync(user, regiModel.Password).Result;

                if (result.Succeeded)
                {
                    if (!roleManager.RoleExistsAsync("NormalUser").Result)
                    {
                        MyIdentityRole role = new MyIdentityRole();
                        role.Name        = "NormalUser";
                        role.Description = "Perform normal operations.";
                        IdentityResult roleResult = roleManager.CreateAsync(role).Result;

                        if (!roleResult.Succeeded)
                        {
                            ModelState.AddModelError("", "Error while creating role!");
                            return(View(regiModel));
                        }
                    }
                    userManager.AddToRoleAsync(user, "NormalUser").Wait();

                    return(RedirectToAction("Login", "Account"));
                }
            }
            return(View(regiModel));
        }
コード例 #20
0
        // Print Invoice

        public ActionResult Invoice(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ProductReceive productReceive = _productReceiveService.FindById(id.Value);

            if (productReceive == null)
            {
                return(HttpNotFound());
            }

            var productReceiveLineItemViewModels = new List <ProductReceiveLineItemViewModel>();

            foreach (var productReceiveLineItem in productReceive.ProductReceiveLineItems)
            {
                var productReceiveLineItemviewModel = new ProductReceiveLineItemViewModel()
                {
                    ProductReceiveLineItemId = productReceiveLineItem.ProductReceiveLineItemId,
                    ProductId   = productReceiveLineItem.ProductId,
                    Productname = _productService.FindBy(s => s.ProductcId == productReceiveLineItem.ProductId).First().ProductName,
                    Quantity    = productReceiveLineItem.Quantity,
                    UnitCost    = productReceiveLineItem.UnitCost,
                    UnitPrice   = _productService.FindBy(s => s.ProductcId == productReceiveLineItem.ProductId).First().UnitPrice
                };
                productReceiveLineItemViewModels.Add(productReceiveLineItemviewModel);
            }

            ViewBag.LineItems = productReceiveLineItemViewModels;
            MyIdentityUser user = userManager.FindById(productReceive.UserId);

            ViewBag.UserName = user.FullName;
            return(View(productReceive));
        }
コード例 #21
0
        public ActionResult Create([Bind(Include = "DateTransfered,FromBranchId,ToBranchId,UserId")] ProductTransferViewModel productTransferViewModel)
        {
            if (ModelState.IsValid)
            {
                MyIdentityDbContext          db          = new MyIdentityDbContext();
                UserStore <MyIdentityUser>   userStore   = new UserStore <MyIdentityUser>(db);
                UserManager <MyIdentityUser> userManager = new UserManager <MyIdentityUser>(userStore);
                MyIdentityUser user = userManager.FindByName(HttpContext.User.Identity.Name);

                var productTransfer = new ProductTransfer()
                {
                    //FromBranchId =1, //productTransferViewModel.FromBranchId,
                    //ToBranchId= 2, //productTransferViewModel.ToBranchId,
                    FromBranchId   = productTransferViewModel.FromBranchId,
                    ToBranchId     = productTransferViewModel.ToBranchId,
                    UserId         = user.Id,
                    DateTransfered = DateTime.Now
                };

                _productTransferService.AddProductTransfer(productTransfer);

                return(RedirectToAction("Create", "ProductTransfers", new { id = productTransfer.ProductTransferId }));
            }

            return(View(productTransferViewModel));
        }
コード例 #22
0
        public ActionResult Index()
        {
            MyIdentityDbContext db = new MyIdentityDbContext();

            UserStore <MyIdentityUser>   userStore   = new UserStore <MyIdentityUser>(db);
            UserManager <MyIdentityUser> userManager = new UserManager <MyIdentityUser>(userStore);

            MyIdentityUser user = userManager.FindByName(HttpContext.User.Identity.Name);

            DbDataEntities  dbTest = new DbDataEntities();
            List <Customer> model  = null;

            if (userManager.IsInRole(user.Id, "Administrator"))
            {
                model = dbTest.Customers.ToList();
            }

            if (userManager.IsInRole(user.Id, "Operator"))
            {
                model = dbTest.Customers.Where(c => c.Country == "USA").ToList();
            }

            ViewBag.FullName = user.FullName;

            return(View(model));
        }
コード例 #23
0
        public IActionResult Index()
        {
            MyIdentityUser user = userManager.GetUserAsync
                                      (HttpContext.User).Result;

            return(View());
        }
コード例 #24
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new MyIdentityUser {
                    UserName = model.UserName, Login = model.Login
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    IdentityRole defaultRole = RoleUtils.CreateOrGetRole(model.RoleId);
                    RoleUtils.AssignRoleToUser(defaultRole, user);

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // Pour plus d'informations sur l'activation de la confirmation de compte et de la réinitialisation de mot de passe, visitez https://go.microsoft.com/fwlink/?LinkID=320771
                    // Envoyer un message électronique avec ce lien
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirmez votre compte", "Confirmez votre compte en cliquant <a href=\"" + callbackUrl + "\">ici</a>");

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire
            return(View(model));
        }
コード例 #25
0
        public async Task Initialize()
        {
            if (_context.Database.EnsureCreated())
            {
                var adminRole = await _roleManager.CreateAsync(
                    new IdentityRole(Roles.ADMIN));

                await _roleManager.CreateAsync(
                    new IdentityRole(Roles.BASIC));

                var basicRole = await _roleManager.FindByNameAsync(Roles.BASIC);

                await _roleManager.AddClaimAsync(basicRole, new Claim(Claims.Sample, ClaimsValues.READ));

                var user = new MyIdentityUser
                {
                    UserName       = "******",
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                };


                await _userManager.CreateAsync(user, "pedro123PEDRO@");

                await _userManager.AddToRoleAsync(user, Roles.BASIC);

                await _userManager.AddClaimAsync(user, new Claim(Claims.Sample, ClaimsValues.READ));
            }
        }
コード例 #26
0
        public ActionResult Login(Login model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                MyIdentityUser user = new MyIdentityUser();

                try
                {
                    CustomResponse res = APICalls.Get("AuthenticationAPI/Get?username="******"&password="******"&type=1");
                    if (res.Status == CustomResponseStatus.Successful && res.Response != null)
                    {
                        JavaScriptSerializer serializer1 = new JavaScriptSerializer();
                        serializer1.MaxJsonLength = 1000000000;
                        var uinfo = res.Response.ToString();
                        user = serializer1.Deserialize <MyIdentityUser>(uinfo);
                    }
                }
                catch (System.FormatException ex)
                {
                    return(View());
                }
                if (user.Email != null)
                {
                    IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
                    authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                    ClaimsIdentity           identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    AuthenticationProperties props    = new AuthenticationProperties();
                    props.IsPersistent = model.RememberMe;
                    authenticationManager.SignIn(props, identity);
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        List <string> roless = userManager.GetRoles(user.Id).ToList();

                        if (roless[0] == "Administrator")
                        {
                            return(RedirectToRoute("DashboardRoute"));
                        }
                        else if (roless[0] == "Client")
                        {
                            return(RedirectToRoute("ClientDashboardRoute"));
                        }
                        else
                        {
                            return(RedirectToRoute("UserDashboardRoute"));
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                    return(View());
                }
            }
            return(View(model));
        }
コード例 #27
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new MyIdentityUser();

                if (_dbContext.Users.Any())
                {
                    user = new MyIdentityUser {
                        UserName = Input.Username, Email = Input.Email, Role = Panda.Models.Enums.Role.User
                    };
                }
                else
                {
                    user = new MyIdentityUser {
                        UserName = Input.Username, Email = Input.Email, Role = Panda.Models.Enums.Role.Admin
                    };
                }

                var isRoleExists = await _roleManager.RoleExistsAsync(user.Role.ToString());

                if (!isRoleExists)
                {
                    await _roleManager.CreateAsync(new IdentityRole(user.Role.ToString()));
                }

                var result = await _userManager.CreateAsync(user, Input.Password);

                await _userManager.AddToRoleAsync(user, user.Role.ToString());

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

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { 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>.");

                    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());
        }
コード例 #28
0
        public async Task <IActionResult> OnPostConfirmationAsync(IFormFile file, 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)
            {
                // 画像登録
                string imageName = "empty.js";
                if (file != null)
                {
                    file.OpenReadStream();
                    imageName = Path.GetFileName(file.FileName);
                    var filePath = Path.Combine(_hostingEnvironment.WebRootPath, "userImages", imageName);
                    // 画像ファイル名が重複していた場合、リネーム
                    if (System.IO.File.Exists(filePath))
                    {
                        // 修正
                        imageName.Insert(0, "_");
                        filePath.Insert(0, "_");
                    }
                    file.CopyTo(new FileStream(filePath, FileMode.Create));
                }

                var user = new MyIdentityUser {
                    UserName = Input.UserName, Email = Input.Email, ProfileImageUrl = "/userImages/" + imageName
                };
                var result = await _userManager.CreateAsync(user);

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

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
コード例 #29
0
        public static void AssignRoleToUser(IdentityRole role, MyIdentityUser user)
        {
            using (var ctx = new SecurityDbContext())
            {
                var userManager = new UserManager <MyIdentityUser>(new UserStore <MyIdentityUser>(ctx));

                userManager.AddToRole(user.Id, role.Name);
            }
        }
コード例 #30
0
        private async Task SignIn(MyIdentityUser myIdentityUser)
        {
            var identity = await userManager.CreateIdentityAsync(myIdentityUser, DefaultAuthenticationTypes.ApplicationCookie);

            var owinContext = Request.GetOwinContext();
            var authManager = owinContext.Authentication;

            authManager.SignIn(identity);
        }