コード例 #1
0
        public JsonResult GetTender(int tenderId)
        {
            using (var ctx = new CoronaSupportPlatformDbContext())
            {
                // Get the tender
                var tender = ctx.Tenders.Include("Properties").Include("Items").Include("Organization").FirstOrDefault(t => t.TenderId == tenderId);

                // Get the products
                var products = ctx.Products.ToList();

                var model = new TenderViewModel()
                {
                    Products         = products,
                    TenderId         = tender.TenderId,
                    OrganizationId   = tender.OrganizationId,
                    Items            = tender.Items,
                    LongDescription  = tender.LongDescription,
                    ShortDescription = tender.ShortDescription,
                    RefNumber        = tender.RefNumber,
                    UserId           = tender.UserId,
                    Organization     = tender.Organization,
                    State            = tender.State,
                };

                // Create the partial
                var partial = ViewToString("CS", "~/Views/Tenders/Details.cshtml", model);

                return(Json(new CSPartialResponse()
                {
                    ReturnCode = 200,
                    Html = partial
                }, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #2
0
        public JsonResult UpdateTenderState(int tenderId, short state)
        {
            try
            {
                using (var ctx = new CoronaSupportPlatformDbContext())
                {
                    // Get the tender
                    var tender = ctx.Tenders.FirstOrDefault(t => t.TenderId == tenderId);

                    tender.State = (TenderState)state;

                    ctx.Entry(tender).State = System.Data.Entity.EntityState.Modified;
                    ctx.SaveChanges();

                    return(Json(new CSControllerResponse()
                    {
                        ReturnCode = 200
                    }, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                return(Json(new CSControllerResponse()
                {
                    ReturnCode = -300
                }, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #3
0
        public ActionResult Index()
        {
            var model = new UserListViewModel()
            {
                CurrentOrganization = CurrentOrganization,
                CurrentUser         = CurrentUser
            };

            using (var ctx = new CoronaSupportPlatformDbContext())
            {
                // Load the roles
                var roles = ctx.Roles.ToList();

                // Load the users
                var users = ctx.Users.Include("Roles.Organization").ToList();

                // Convert
                model.Users = users.Select(u => new UserViewModel().From(u, roles)).ToList();
            }

            #region [ Breadcrumb ]

            var breadcrumb = new BreadcrumbViewModel();
            breadcrumb.PageName = "Kullanıcı Listesi";
            breadcrumb.Items.Add("Anasayfa", "/");
            breadcrumb.Items.Add("Kullanıcı Listesi", "");
            TempData["Breadcrumb"] = breadcrumb;

            #endregion

            return(View(model));
        }
コード例 #4
0
        public ActionResult Index()
        {
            // Create the model
            var model = new TenderListViewModel();

            using (var ctx = new CoronaSupportPlatformDbContext())
            {
                if (User.IsInRole("Administrator"))
                {
                    // Load all tenders if administrator
                    var tenders = ctx.Tenders.Include("Organization").Include("Items.Product").Include("Properties").Include("Tags").ToList();
                    model.Tenders = tenders.Select(t => new TenderViewModel().From(t)).ToList();
                }
                else
                {
                    // Load only the tenders for the current user
                    var tenders = ctx.Tenders.Include("Organization").Include("Items.Product").Include("Properties").Include("Items").Where(u => u.UserId == CurrentUser.Id).ToList();
                    model.Tenders = tenders.Select(t => new TenderViewModel().From(t)).ToList();
                }
            }

            #region [ Breadcrumb ]

            var breadcrumb = new BreadcrumbViewModel();
            breadcrumb.PageName = "İhtiyaç Listesi";
            breadcrumb.Items.Add("Anasayfa", "/");
            breadcrumb.Items.Add("İhtiyaç Listesi", "");
            TempData["Breadcrumb"] = breadcrumb;

            #endregion

            return(View(model));
        }
コード例 #5
0
        public ActionResult Details(int id)
        {
            var model = new UserViewModel()
            {
                CurrentOrganization = CurrentOrganization,
                CurrentUser         = CurrentUser
            };

            using (var ctx = new CoronaSupportPlatformDbContext())
            {
                // Load the roles
                var roles = ctx.Roles.ToList();

                // Load the user
                var user = ctx.Users.Include("Roles.Organization").FirstOrDefault(u => u.Id == id);

                // Convert
                model = model.From(user, roles);
            }

            #region [ Breadcrumb ]

            var breadcrumb = new BreadcrumbViewModel();
            breadcrumb.PageName = "Kullanıcı Detay";
            breadcrumb.Items.Add("Anasayfa", "/");
            breadcrumb.Items.Add("Kullanıcı Listesi", "/Users");
            breadcrumb.Items.Add(model.Firstname + " " + model.Lastname, "");
            TempData["Breadcrumb"] = breadcrumb;

            #endregion

            return(View(model));
        }
コード例 #6
0
        public ActionResult ResetPassword(string rt, string ss)
        {
            // Add debug log
            LogService.Debug($"Getting the reset password page. SessionId:{SessionId}");

            var model = new ResetPasswordViewModel()
            {
                CurrentCulture = CurrentCulture,
                Token          = rt,
                SecurityStamp  = ss
            };

            if (ss != null)
            {
                // Add debug log
                LogService.Debug($"Getting the user using the security stamp. SessionId:{SessionId}");

                using (var ctx = new CoronaSupportPlatformDbContext())
                {
                    var user = ctx.Users.Where(u => u.SecurityStamp == ss).FirstOrDefault();

                    if (user != null)
                    {
                        // Add debug log
                        LogService.Debug($"User found. Email:{user.Email}; SessionId:{SessionId}");
                        // Set the email
                        model.Email = user.Email;
                    }
                }
            }

            return(View(model));
        }
コード例 #7
0
        public ActionResult Index()
        {
            var model = new HomeViewModel()
            {
                CurrentCulture      = CurrentCulture,
                CurrentUser         = CurrentUser,
                CurrentOrganization = CurrentOrganization
            };

            #region [ Load tenders ]

            using (var ctx = new CoronaSupportPlatformDbContext())
            {
                if (User.IsInRole("Administrator"))
                {
                    // Load all tenders if administrator
                    var tenders = ctx.Tenders.Include("Organization").Include("Items.Product").Include("Properties").Include("Tags").ToList();
                    model.Tenders = tenders.Select(t => new TenderViewModel().From(t)).ToList();
                }
                else
                {
                    // Load only the tenders for the current user
                    var tenders = ctx.Tenders.Include("Organization").Include("Items.Product").Include("Properties").Include("Items").Where(u => u.UserId == CurrentUser.Id).ToList();
                    model.Tenders = tenders.Select(t => new TenderViewModel().From(t)).ToList();
                }
            }

            #endregion

            return(View(model));
        }
コード例 #8
0
        public ActionResult Register()
        {
            if (!User.Identity.IsAuthenticated)
            {
                // Add debug log
                LogService.Debug($"Getting the registration page. SessionId:{SessionId}");

                // Create the model
                var model = new RegisterViewModel()
                {
                    CurrentCulture = CurrentCulture,
                };

                // Load the locations
                using (var ctx = new CoronaSupportPlatformDbContext())
                {
                    model.Organizations = ctx.Organizations.ToList();
                }

                return(View(model));
            }
            else
            {
                return(RedirectToLocal(null));
            }
        }
コード例 #9
0
        public ActionResult ResetPassword(ResetPasswordViewModel model)
        {
            // Add debug log
            LogService.Debug($"Getting the reset password page (HTTP_POST). SessionId:{SessionId}");
            if (ModelState.IsValid)
            {
                if (model.Password != model.ConfirmPassword)
                {
                    model.HasErrors = true;
                    model.Result    = "Şifreler uyuşmuyor!";

                    return(View(model));
                }

                var securityStamp = model.SecurityStamp;

                // Correct the token
                var passwordUpdateToken = model.Token;

                // Add debug log
                LogService.Debug($"Password and security stamps parsed. SessionId:{SessionId}");

                if (securityStamp != null)
                {
                    // Add debug log
                    LogService.Debug($"Getting the user using the security stamp. SessionId:{SessionId}");

                    using (var ctx = new CoronaSupportPlatformDbContext())
                    {
                        var user = ctx.Users.Where(u => u.SecurityStamp == securityStamp).FirstOrDefault();

                        if (user != null)
                        {
                            // Add debug log
                            LogService.Debug($"User found. Email:{user.Email}; SessionId:{SessionId}");

                            // Set the context parameters for internal use
                            HttpContext.Items.Add("SessionId", SessionId);
                            HttpContext.Items.Add("UserToken", UserToken);

                            // Change the password
                            var passwordChangeResponse = UserManager.ResetPassword(user.Id, passwordUpdateToken, model.Password);

                            if (passwordChangeResponse.Succeeded)
                            {
                                model.Result = "Şifre başarıyla değiştirildi!";
                                return(View(model));
                            }
                        }
                    }
                }
            }


            model.HasErrors = true;
            model.Result    = "Şifre değiştirilemedi!";

            return(View(model));
        }
コード例 #10
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            // Add debug log
            LogService.Debug($"Getting the login page (HTTP_POST). SessionId:{SessionId}");

            // Get user status from db
            using (var ctx = new CoronaSupportPlatformDbContext())
            {
                var user = ctx.Users.Where(u => u.Email == model.Email && u.Status == EntityStatus.Deleted).Any();

                if (user)
                {
                    model.Errors.Add("Giriş yapmak istediğiniz kullanıcı silinmiştir. Detaylı bilgi için iletişime geçebilirsiniz.");
                    ModelState.AddModelError("", "Deleted credentials!");

                    return(View(model));
                }
            }


            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.Remember, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:

                // Return success
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.Remember }));

            case SignInStatus.Failure:
            default:

                model.Errors.Add("Lütfen e-posta ve şifrenizi kontrol ediniz!");
                ModelState.AddModelError("", "Invalid credentials!");

                return(View(model));
            }
        }
コード例 #11
0
        public static CSPUserManager Create(IdentityFactoryOptions <CSPUserManager> options, IOwinContext context)
        {
            var manager = new CSPUserManager(new CSPUserStore(CoronaSupportPlatformDbContext.Create()));

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <CSPUser, int>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };
            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit            = false,
                RequireLowercase        = false,
                RequireUppercase        = false,
            };
            // Register two factor authentication providers. This application uses Phone
            // and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug in here.
            manager.RegisterTwoFactorProvider("PhoneCode",
                                              new PhoneNumberTokenProvider <CSPUser, int>
            {
                MessageFormat = "Your security code is: {0}"
            });
            manager.RegisterTwoFactorProvider("EmailCode",
                                              new EmailTokenProvider <CSPUser, int>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is: {0}"
            });

            //manager.EmailService = new EmailService();
            //manager.SmsService = new SmsService();

            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = new DataProtectorTokenProvider <CSPUser, int>(dataProtectionProvider.Create("CSPIdentity"));
            }
            return(manager);
        }
コード例 #12
0
        public ActionResult New()
        {
            // Create the model
            var model = new TenderViewModel()
            {
                CurrentUser         = CurrentUser,
                CurrentOrganization = CurrentOrganization,
            };

            using (var ctx = new CoronaSupportPlatformDbContext())
            {
                // Get the products
                var products = ctx.Products.ToList();
                model.Products = products;

                // Get the organization Id
                var organizationId = CurrentUser.Roles.FirstOrDefault().OrganizationId;

                // Get the organization
                var organization = ctx.Organizations.FirstOrDefault(o => o.OrganizationId == organizationId);
                model.Organization = organization;
            }

            #region [ Breadcrumb ]

            var breadcrumb = new BreadcrumbViewModel();
            breadcrumb.PageName = "Yeni İhtiyaç";
            breadcrumb.Items.Add("Anasayfa", "/");
            breadcrumb.Items.Add("İhtiyaç Listesi", "/Tenders");
            breadcrumb.Items.Add("Yeni İhtiyaç", "");
            TempData["Breadcrumb"] = breadcrumb;

            #endregion

            return(View(model));
        }
コード例 #13
0
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);

            #region [ User ]

            // Try to get user information from the session
            var user = Session["User"] as CSPUser;

            if (user == null || user.Status != EntityStatus.Active)
            {
                if (User.Identity.IsAuthenticated)
                {
                    using (var ctx = new CoronaSupportPlatformDbContext())
                    {
                        // Get the user id
                        var userId = User.Identity.GetUserId <int>();

                        // Get the user
                        user = ctx.Users.Where(u => u.Id == userId).FirstOrDefault();
                    }
                }

                // Store contact data in the session
                Session["User"] = user;
            }

            // Set the user
            CurrentUser = user;

            #endregion

            #region [ User roles ]

            if (CurrentUser != null)
            {
                // Try to get user information from the session
                var userRoles = CurrentUser.Roles;

                if (userRoles == null || userRoles.Count == 0)
                {
                    // Get the role information from the related service
                    using (var ctx = new CoronaSupportPlatformDbContext())
                    {
                        userRoles = ctx.UserRoles.Include("Organization").Where(ur => ur.UserId == user.Id).ToList();
                    }

                    // Set the roles in to the current user
                    foreach (var userRole in userRoles)
                    {
                        CurrentUser.Roles.Add(userRole);
                    }

                    // Re-Store user data in the session
                    Session["User"] = CurrentUser;

                    // Set the current organization
                    CurrentOrganization = CurrentUser.Roles.FirstOrDefault().Organization;
                }

                // Set user roles
                UserRoles = CurrentUser.Roles.ToList();
            }

            #endregion

            #region [ User token ]

            // Get the user token
            var userToken = string.Empty;

            // Try to get the user token
            var tokenCookie = requestContext.HttpContext.Request.Cookies["csp.token"];

            if (tokenCookie == null)
            {
                // Get the token from the identity server
                userToken = HttpContext.GetOwinContext().GetUserManager <CSPUserManager>().GetUserGuid();

                // Set the cookie
                tokenCookie         = new HttpCookie("csp.token", userToken);
                tokenCookie.Expires = DateTime.MaxValue;
                requestContext.HttpContext.Response.Cookies.Add(tokenCookie);
            }
            else
            {
                // Get the token from the
                userToken = tokenCookie.Value;
            }

            // Set the token
            UserToken         = userToken;
            ViewBag.UserToken = userToken;

            #endregion

            #region [ User Id ]

            // Set the user id
            ViewBag.UserId = UserId;

            #endregion

            #region [ Session Id ]

            // Set the session id
            ViewBag.SessionId = SessionId;

            #endregion
        }
コード例 #14
0
        public ActionResult New(TenderViewModel model)
        {
            try
            {
                #region [ Load the create page data  ]

                using (var ctx = new CoronaSupportPlatformDbContext())
                {
                    // Get the products
                    var products = ctx.Products.ToList();
                    model.Products = products;

                    // Get the organization Id
                    var organizationId = CurrentUser.Roles.FirstOrDefault().OrganizationId;

                    // Get the organization
                    var organization = ctx.Organizations.FirstOrDefault(o => o.OrganizationId == organizationId);
                    model.Organization = organization;
                }

                #endregion

                #region [ Breadcrumb ]

                var breadcrumb = new BreadcrumbViewModel();
                breadcrumb.PageName = "Yeni İhtiyaç";
                breadcrumb.Items.Add("Anasayfa", "/");
                breadcrumb.Items.Add("İhtiyaç Listesi", "/Tenders");
                breadcrumb.Items.Add("Yeni İhtiyaç", "");
                TempData["Breadcrumb"] = breadcrumb;

                #endregion

                if (ModelState.IsValid)
                {
                    using (var ctx = new CoronaSupportPlatformDbContext())
                    {
                        // Create new tender object
                        var tender = new Tender()
                        {
                            OrganizationId   = model.Organization.OrganizationId,
                            ShortDescription = model.ShortDescription,
                            LongDescription  = model.LongDescription,
                            UserId           = CurrentUser.Id,
                            Created          = DateTime.UtcNow,
                            State            = TenderState.New,
                            Status           = Common.EntityStatus.Active,
                        };

                        // Get the quantities
                        var quantityList = Request.Form["ProductQuantities"].Split(',');

                        // Create the tender items
                        var tenderItems = new List <TenderItem>();

                        for (int i = 0; i < model.Products.Count; i++)
                        {
                            // Check for quantity
                            var quantity = Convert.ToInt32(quantityList[i]);

                            // Check for a positive quantity
                            if (quantity == 0)
                            {
                                continue;
                            }

                            // Get the current product
                            var product = model.Products[i];

                            tenderItems.Add(new TenderItem()
                            {
                                ProductId = product.ProductId,
                                Quantity  = quantity,
                                State     = TenderItemState.New,
                                Created   = DateTime.UtcNow
                            });
                        }

                        // Add the tender items to tender
                        tender.Items = tenderItems;

                        // Add the tender
                        ctx.Tenders.Add(tender);
                        ctx.SaveChanges();
                    }
                }
                else
                {
                    // Add model state errors
                    model.Errors.AddRange(ModelState.SelectMany(s => s.Value.Errors.Select(e => e.ErrorMessage)));

                    return(View(model));
                }
            }
            catch (Exception ex)
            {
                LogService.Debug(ex, $"There is an error while creating tender");

                return(View(model));
            }

            return(Redirect("/Tenders"));
        }
コード例 #15
0
 public CSPUserStore(CoronaSupportPlatformDbContext context) : base(context) {}
コード例 #16
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            // Add debug log
            LogService.Debug($"Getting the registration page (HTTP_POST). SessionId:{SessionId}");

            if (ModelState.IsValid)
            {
                // Create the user object
                var user = new CSPUser
                {
                    Firstname          = model.Firstname,
                    Lastname           = model.Lastname,
                    UserName           = model.Email,
                    Email              = model.Email,
                    MobileNumber       = model.Mobile,
                    RegistrationNumber = model.RegistrationNumber,
                    Created            = DateTime.UtcNow,
                    Status             = EntityStatus.Draft
                };

                // Set the location and check email
                using (var ctx = new CoronaSupportPlatformDbContext())
                {
                    // Check email from db
                    var emailTaken = ctx.Users.Where(et => et.Email == model.Email).Any();

                    if (emailTaken)
                    {
                        // Load the locations
                        model.Organizations = ctx.Organizations.ToList();

                        model.Errors.Add(model.Email + "'a ait bir hesap bulunmakta");
                        return(View(model));
                    }
                }

                // Create the user at the user store
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // Assign to role
                    IdentityResult roleAssignmentResponse = null;
                    if (model.Occupation == "2")
                    {
                        // Assign to role
                        roleAssignmentResponse = UserManager.AddToRole(user.Id, "OrganizationUser");
                    }
                    else
                    {
                        roleAssignmentResponse = UserManager.AddToRole(user.Id, "User");
                    }

                    // Set the organization id
                    using (var ctx = new CoronaSupportPlatformDbContext())
                    {
                        // Load the user role
                        var userRole = ctx.UserRoles.FirstOrDefault(ur => ur.UserId == user.Id && ur.RoleId == 2);
                        userRole.OrganizationId = Convert.ToInt32(model.OrganizationId);
                        ctx.SaveChanges();
                    }

                    // Log in the user
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    #region [ User e-mail validation ]

                    // Get the current domain (it can be development, staging or production)
                    var siteRoot = String.Format("{0}://{1}{2}",
                                                 System.Web.HttpContext.Current.Request.Url.Scheme,
                                                 System.Web.HttpContext.Current.Request.Url.Host,
                                                 System.Web.HttpContext.Current.Request.Url.Port == 80 ? string.Empty : ":" + System.Web.HttpContext.Current.Request.Url.Port);

                    // Calculate the activation code based on the email and user id
                    var activationCode = EncryptMessage(user.Email, user.Id.ToString());

                    //// Sending confirmation email
                    //var activationEmailModel = new RegistrationNotificationViewModel()
                    //{
                    //    ActivationCode = activationCode,
                    //    User = user,
                    //    SiteRoot = siteRoot
                    //};
                    //var activationEmail = ViewToString("~/Views/Templates/Email/RegistrationActivation.cshtml", activationEmailModel);
                    //var activationEmailResponse = _mailgunService.Send(new EmailMessage()
                    //{
                    //    ChannelId = "Mailgun",
                    //    FromName = "FreelanceFrom",
                    //    FromAddress = "*****@*****.**",
                    //    Subject = "Freelancefrom Bilgilendirme",
                    //    Body = activationEmail,
                    //    IsHtml = true,
                    //    Deliveries = new List<Delivery>()
                    //    {
                    //        new Delivery()
                    //        {
                    //            RecipientType = Common.RecipientType.Primary,
                    //            RecipientName = user.Firstname + " " + user.Lastname,
                    //            RecipientAddress = user.Email
                    //        }
                    //    }
                    //});

                    #endregion

                    #region [ Slack notification ]

                    //try
                    //{
                    //    var slackNotificationResponse = _slackService.SendActivity(new MessageRequest()
                    //    {
                    //        Attachments = new List<SlackAttachment>() {
                    //            new SlackAttachment()
                    //            {
                    //                Color = "#36a64f",
                    //                Title = "Yeni Üye",
                    //                TitleLink = "http://www.freelancefrom.com/users/" + user.Id,
                    //                Text = "\n",
                    //                Fields = new List<SlackField>()
                    //                {
                    //                    new SlackField()
                    //                    {
                    //                        Title = "Ad Soyad",
                    //                        Value = $"{user.Firstname + " " + user.Lastname}\n"
                    //                    },
                    //                    new SlackField()
                    //                    {
                    //                        Title = "E-posta adresi",
                    //                        Value = $"{user.Email}\n"
                    //                    }
                    //                }
                    //            }
                    //        }
                    //    });
                    //}
                    //catch (Exception ex)
                    //{
                    //    // Do nothing
                    //}

                    #endregion

                    // Add debug log
                    LogService.Debug($"User registration complete, now redirecting to home page. SessionId:{SessionId}");

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


                AddErrors(result);
            }
            else
            {
                // Add errors
                model.Errors.AddRange(ModelState.SelectMany(s => s.Value.Errors.Select(e => e.ErrorMessage)));
            }

            // Add debug log
            LogService.Debug($"User registration failed, re-opening the registration page. SessionId:{SessionId}");

            using (var ctx = new CoronaSupportPlatformDbContext())
            {
                model.Organizations = ctx.Organizations.ToList();
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }