public async Task <IActionResult> ForgotPassword(string Email)
        {
            var account = await _userManager.FindByEmailAsync(Email);

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

            var Token = await _userManager.GeneratePasswordResetTokenAsync(account);

            Guid   tokenId       = Guid.NewGuid();
            string tokenUid      = tokenId.ToString();
            var    slidingOption = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMilliseconds(5));
            await distributedCache.SetStringAsync(tokenUid, Token, slidingOption);

            string email_contents = htmlGenerator.GenerateHtml("ResetPassword.html",
                                                               new
            {
                email = Email,
                token = tokenUid,
                url   = WebServerUrl
            });

            string sender = "PEIU 운영팀";
            string target = "중개거래사업자";

            //var aggregator_account_users = await _userManager.GetUsersInRoleAsync(UserRoleTypes.Supervisor);
            await _emailSender.SendEmailAsync(sender, $"비밀번호 초기화가 요청되었습니다", email_contents, Email);

            logger.LogInformation($"비밀번호 초기화 메일 전송: {Email}\n{Token}");
            return(Ok(new { Result = IdentityResult.Success, Token = Token }));
        }
Esempio n. 2
0
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> SignonAggregator([FromBody] AggregatorRegistModel model)
        {
            if (ModelState.IsValid)
            {
                AggregatorGroup aggregatorGroup = _accountContext.AggregatorGroups.FirstOrDefault(x => x.AggName == model.Company);
                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 _accountContext.AddAsync(aggregatorGroup);
                }

                var user   = CreateUserAccount(model, RegisterType.Aggregator);
                var result = await _userManager.CreateAsync(user, model.Password);

                //result.Errors
                if (result.Succeeded)
                {
                    var role_add_result = await _userManager.AddToRoleAsync(user, UserRoleTypes.Aggregator);

                    //_userManager.AddClaimAsync(user, new Claim())
                    AggregatorUser aggregatorUser = new AggregatorUser();
                    aggregatorUser.AggregatorGroup = aggregatorGroup;
                    aggregatorUser.UserId          = user.Id;
                    await _accountContext.AggregatorUsers.AddAsync(aggregatorUser);

                    await _accountContext.SaveChangesAsync();

                    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 운영팀";
                    var    aggregator_account_users = await _userManager.GetUsersInRoleAsync(UserRoleTypes.Supervisor);

                    await _emailSender.SendEmailAsync(sender, "새로운 중계거래자 가입이 요청되었습니다", email_contents, aggregator_account_users.Select(x => x.Email).ToArray());

                    return(Ok(new { Result = result }));
                }
                else
                {
                    return(BadRequest(new { Result = result }));
                }
            }
            return(BadRequest());
        }
        //[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());
            }
        }