Example #1
0
        public async Task <RegisteredUser> GetCurrentRegisteredUserAsync()
        {
            var rawId = _httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

            if (int.TryParse(rawId, out int id))
            {
                return(await _session.GetAsync <RegisteredUser>(id));
            }
            else
            {
                return(null);
            }
        }
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> SignonContractor([FromBody] AggregatorRegistModelBase model)
        {
            //TransactionScope trans_scope = new TransactionScope(System.Transactions.TransactionScopeAsyncFlowOption.Enabled);
            var trans_scope = await accountEF.Database.BeginTransactionAsync();

            try

            {
                if (ModelState.IsValid)
                {
                    using (NHibernate.ISession session = _accountContext.SessionFactory.OpenSession())
                        using (ITransaction trans = session.BeginTransaction(System.Data.IsolationLevel.ReadCommitted))
                        {
                            AggregatorGroup aggregatorGroup = await session.GetAsync <AggregatorGroup>(model.AggregatorGroupId);

                            if (aggregatorGroup == null)
                            {
                                if (model.Type == RegisterType.Contrator)
                                {
                                    IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).AggregatorNotFounded(model.AggregatorGroupId);
                                    IdentityResult _result = IdentityResult.Failed(error);
                                    return(base.BadRequest(new { Result = _result }));
                                }
                                else
                                {
                                    var groups = await session.CreateCriteria <AggregatorGroup>()
                                                 .Add(Restrictions.Eq("AggName", model.Company))
                                                 .ListAsync <AggregatorGroup>();

                                    aggregatorGroup = groups.FirstOrDefault();
                                    if (aggregatorGroup == null)
                                    {
                                        aggregatorGroup                = new AggregatorGroup();
                                        aggregatorGroup.ID             = Guid.NewGuid().ToString();
                                        aggregatorGroup.AggName        = model.Company;
                                        aggregatorGroup.Representation = "";
                                        aggregatorGroup.Address        = model.Address;
                                        aggregatorGroup.CreateDT       = DateTime.Now;
                                        aggregatorGroup.PhoneNumber    = model.PhoneNumber;
                                        await session.SaveAsync(aggregatorGroup);
                                    }
                                }
                            }


                            var user = CreateUserAccount(model);

                            JObject obj    = JObject.FromObject(user);
                            var     result = await _userManager.CreateAsync(user, model.Password);

                            //result.Errors
                            if (result.Succeeded)
                            {
                                RegisterAccount(session, user, model.AggregatorGroupId);
                                RegisterFileRepositary  registerModel           = RegisterFile(session, user.Id, model.RegisterFilename, model.RegisterFilebase64);
                                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                                await Publisher.PublishMessageAsync(obj.ToString(), cancellationTokenSource.Token);

                                logger.LogInformation($"회원 가입 성공: {obj}");
                                if (model.NotifyEmail)
                                {
                                    string email_contents = htmlGenerator.GenerateHtml("NotifyEmail.html",
                                                                                       new
                                    {
                                        Name       = $"{user.FirstName} {user.LastName}",
                                        Company    = model.Company,
                                        Email      = model.Email,
                                        Phone      = model.PhoneNumber,
                                        Address    = model.Address,
                                        Aggregator = aggregatorGroup.AggName
                                    });

                                    string sender = "PEIU 운영팀";
                                    string target = "";

                                    List <string> supervisor_emails = (await _userManager.GetUsersInRoleAsync(UserRoleTypes.Supervisor)).Select(x => x.Email).ToList();
                                    if (model.Type == RegisterType.Aggregator)
                                    {
                                        target = "중개거래사업자";
                                    }
                                    else if (model.Type == RegisterType.Contrator)
                                    {
                                        target = "발전사업자";
                                        var agg_result = await session.CreateCriteria <VwAggregatoruser>()
                                                         .Add(Restrictions.Eq("AggGroupId", model.AggregatorGroupId))
                                                         .ListAsync <VwAggregatoruser>();

                                        supervisor_emails.AddRange(agg_result.Select(x => x.Email));

                                        //targetEmailUsers = await _userManager.GetUsersInRoleAsync(UserRoleTypes.Aggregator);
                                        //targetEmailUsers = targetEmailUsers.Where(x=>x.agg)
                                    }
                                    else if (model.Type == RegisterType.Supervisor)
                                    {
                                        target = "관리자";
                                    }

                                    //var aggregator_account_users = await _userManager.GetUsersInRoleAsync(UserRoleTypes.Supervisor);
                                    await _emailSender.SendEmailAsync(sender, $"새로운 {target} 가입이 요청되었습니다", email_contents, registerModel, supervisor_emails.ToArray());

                                    logger.LogInformation($"가입 알림 메일 전송: {string.Join(", ", supervisor_emails)}");
                                }
                                //throw new Exception();
                                await trans.CommitAsync();

                                //trans.Commit();
                                trans_scope.Commit();
                                return(Ok(new { Result = result }));
                            }
                            else
                            {
                                trans_scope.Dispose();
                                return(BadRequest(new { Result = result }));
                            }
                        }
                }
                else
                {
                    trans_scope.Dispose();
                    return(BadRequest());
                }
            }
            catch (Exception ex)
            {
                trans_scope.Dispose();
                logger.LogError(ex, ex.Message);
                return(BadRequest());
            }
        }
        //[HttpPost, Route("login"), AllowAnonymous]
        ////public async Task<IActionResult> Login([FromBody]JObject jo)
        //public async Task<IActionResult> Login()
        //{
        //    Console.WriteLine("call login~. No Parameter");
        //    //foreach (string key in Response.Headers.Keys)
        //    //{
        //    //    Console.WriteLine($"{key} : {Response.Headers[key]}");
        //    //}
        //    //Response.Cookies.Append("babo", "you~");
        //    //if (jo == null)
        //    //    return NoContent();
        //    //return await ClaimsLogin(jo);
        //    return Ok();
        //}

        //private async Task<IActionResult> ClaimsLogin([FromBody]JObject jo)
        //{
        //    bool isUservalid = false;
        //    LoginViewModel user = JsonConvert.DeserializeObject<LoginViewModel>(jo.ToString());

        //    if (ModelState.IsValid && isUservalid)
        //    {
        //        var claims = new List<Claim>();

        //        claims.Add(new Claim(ClaimTypes.Name, user.Email));


        //        var identity = new ClaimsIdentity(
        //            claims, JwtBearerDefaults.AuthenticationScheme);

        //        var principal = new ClaimsPrincipal(identity);

        //        var props = new AuthenticationProperties();
        //        props.IsPersistent = user.RememberMe;

        //        HttpContext.SignInAsync(
        //            IdentityConstants.ApplicationScheme,
        //            principal, props).Wait();
        //        string token = JasonWebTokenManager.GenerateToken(user.Email);
        //        return Ok(new { Token = token });
        //    }
        //    else
        //    {
        //        return BadRequest();
        //    }
        //}

        private async Task <IActionResult> OldLogin([FromBody] LoginModel jo)
        {
            //[FromBody]
            //JObject jo = null;
            Console.WriteLine($"Try Logging... {jo}");


            //UserAccount user = await _userManager.FindByNameAsync(input_user.Email);

            if (ModelState.IsValid)
            {
                Console.WriteLine($"Model State is Valid");
                Console.WriteLine(jo.ToString());
                UserAccountEF account = await _userManager.FindByEmailAsync(jo.Email);

                if (account == null)
                {
                    IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).UserNotFound();
                    IdentityResult _result = IdentityResult.Failed(error);
                    return(BadRequest(new { Result = _result }));
                }
                else if (account.SignInConfirm == false)
                {
                    IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).SignInNotConfirm(jo.Email);
                    IdentityResult _result = IdentityResult.Failed(error);
                    return(BadRequest(new { Result = _result }));
                }

                Microsoft.AspNetCore.Identity.SignInResult signResult = await _signInManager.PasswordSignInAsync(jo.Email, jo.Password, true, false);

                if (signResult.Succeeded)
                {
                    using (NHibernate.ISession session = _accountContext.SessionFactory.OpenSession())
                    {
                        var accountUser = await _userManager.FindByEmailAsync(jo.Email);

                        IList <Claim> claims = await _userManager.GetClaimsAsync(accountUser);

                        claims.Add(new Claim(ClaimTypes.NameIdentifier, accountUser.Id));
                        claims.Add(new Claim(ClaimTypes.Email, accountUser.Email));
                        claims.Add(new Claim(ClaimTypes.Name, accountUser.FirstName + accountUser.LastName));
                        if (accountUser.UserType == RegisterType.Aggregator)
                        {
                            VwAggregatoruser agg = await session.GetAsync <VwAggregatoruser>(accountUser.Id);

                            claims.Add(new Claim(UserClaimTypes.AggregatorGroupIdentifier, agg.AggGroupId));
                            claims.Add(new Claim(ClaimTypes.Role, UserRoleTypes.Aggregator));
                            if (string.IsNullOrEmpty(agg.AggName) == false)
                            {
                                claims.Add(new Claim(UserClaimTypes.AggregatorGroupName, agg.AggName));
                            }

                            //var agg = _accountContext.VwAggregatorusers.FirstOrDefault(x => x.UserId == accountUser.Id);
                            //claims.Add(new Claim(UserClaimTypes.AggregatorGroupIdentifier, agg.AggGroupId));
                            //claims.Add(new Claim(ClaimTypes.Role, UserRoleTypes.Aggregator));
                            //if (string.IsNullOrEmpty(agg.AggName) == false)
                            //    claims.Add(new Claim(UserClaimTypes.AggregatorGroupName, agg.AggName));
                        }
                        else if (accountUser.UserType == RegisterType.Contrator)
                        {
                            VwContractoruser con = await session.GetAsync <VwContractoruser>(accountUser.Id);

                            claims.Add(new Claim(UserClaimTypes.AggregatorGroupIdentifier, con.AggGroupId));
                            claims.Add(new Claim(ClaimTypes.Role, UserRoleTypes.Contractor));
                            if (string.IsNullOrEmpty(con.AggName) == false)
                            {
                                claims.Add(new Claim(UserClaimTypes.AggregatorGroupName, con.AggName));
                            }

                            //var contractor = _accountContext.VwContractorusers.FirstOrDefault(x => x.UserId == accountUser.Id);
                            //claims.Add(new Claim(UserClaimTypes.AggregatorGroupIdentifier, contractor.AggGroupId));
                            //claims.Add(new Claim(ClaimTypes.Role, UserRoleTypes.Contractor));
                            //if (string.IsNullOrEmpty(contractor.AggName) == false)
                            //    claims.Add(new Claim(UserClaimTypes.AggregatorGroupName, contractor.AggName));
                        }
                        else if (accountUser.UserType == RegisterType.Supervisor)
                        {
                            claims.Add(new Claim(ClaimTypes.Role, UserRoleTypes.Supervisor));
                        }


                        string token = JasonWebTokenManager.GenerateToken(jo.Email, UserClaimTypes.Issuer, claims);

                        //if (string.IsNullOrEmpty(returnUrl) == false)
                        //{
                        //    Console.WriteLine("returnurl:" + returnUrl);
                        //    return Redirect(returnUrl);
                        //}
                        Console.WriteLine("Log-in Success: " + jo.Email);
                        return(Ok(new { Result = signResult, Token = token, User = accountUser }));
                    }
                }
                else
                {
                    Console.WriteLine($"Login Failed");
                    //if (signResult.RequiresTwoFactor)
                    //{
                    //    return RedirectToAction("act", new { ReturnUrl = returnUrl, RememberMe = user.RememberMe });
                    //}
                    if (signResult.IsLockedOut)
                    {
                        IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).UserLockoutEnabled();
                        IdentityResult _result = IdentityResult.Failed(error);
                        return(BadRequest(new { Result = _result }));
                    }
                    else
                    {
                        IdentityError  error   = (_userManager.ErrorDescriber as LocalizedIdentityErrorDescriber).PasswordMismatch();
                        IdentityResult _result = IdentityResult.Failed(error);
                        return(BadRequest(new { Result = _result }));
                    }
                }
            }
            else
            {
                Console.WriteLine("Invalid LoginViewModel");
                return(Ok(StatusCodes.Status406NotAcceptable));
            }
        }