Example #1
0
        public ActionResult RecoverPassword()
        {
            var passwordResetToken = Request["PasswordResetToken"] ?? "";

            using (var context = new SEContext())
            {
                var user = context.User.Include("SecurityQuestionLookupItem").Where(u => u.PasswordResetToken == passwordResetToken && u.PasswordResetExpiry > DateTime.Now).FirstOrDefault();
                if (user == null)
                {
                    HandleErrorInfo error = new HandleErrorInfo(new ArgumentException("INFO: The password recovery token is not valid or has expired"), "Account", "RecoverPassword");
                    return(View("Error", error));
                }
                if (user.Enabled == false)
                {
                    HandleErrorInfo error = new HandleErrorInfo(new InvalidOperationException("INFO: Your account is not currently approved or active"), "Account", "Recover");
                    return(View("Error", error));
                }
                RecoverPassword recoverPasswordModel = new RecoverPassword()
                {
                    Id                 = user.Id,
                    SecurityAnswer     = "",
                    SecurityQuestion   = user.SecurityQuestionLookupItem.Description,
                    PasswordResetToken = passwordResetToken,
                    UserName           = user.UserName
                };
                return(View("RecoverPassword", recoverPasswordModel));
            }
        }
        public List <string> searchFile(string tokenString)
        {
            //存储文件ID信息的list
            List <string> fileList = null;

            using (SEContext context = new SEContext())
            {
                var IsTokenExisted = from token in context.Token
                                     where token.TokenId == tokenString
                                     select token;
                if (IsTokenExisted != null)
                {
                    var fileListInfo = from file in context.Token_File
                                       where file.TokenId == tokenString
                                       select file;

                    foreach (var item in fileListInfo)
                    {
                        fileList.Add(item.FileId);
                    }
                }
            }

            return(fileList);
        }
Example #3
0
        public ActionResult Recover(Recover model)
        {
            if (ModelState.IsValid)
            {
                using (var context = new SEContext())
                {
                    var user             = context.User.Where(u => u.UserName == model.UserName && u.Enabled && u.EmailVerified && u.Approved).FirstOrDefault();
                    var recaptchaSuccess = ValidateRecaptcha();
                    if (user != null && recaptchaSuccess)
                    {
                        user.PasswordResetToken  = Guid.NewGuid().ToString().Replace("-", "");
                        user.PasswordResetExpiry = DateTime.Now.AddMinutes(15);
                        // Send recovery email with link to recover password form
                        string emailBody    = string.Format("A request has been received to reset your {0} password. You can complete this process any time within the next 15 minutes by clicking <a href='{1}Account/RecoverPassword?PasswordResetToken={2}'>{1}Account/RecoverPassword?PasswordResetToken={2}</a>. If you did not request this then you can ignore this email.", ConfigurationManager.AppSettings["ApplicationName"].ToString(), ConfigurationManager.AppSettings["WebsiteBaseUrl"].ToString(), user.PasswordResetToken);
                        string emailSubject = string.Format("{0} - Complete the password recovery process", ConfigurationManager.AppSettings["ApplicationName"].ToString());
                        Services.SendEmail(ConfigurationManager.AppSettings["DefaultFromEmailAddress"].ToString(), new List <string>()
                        {
                            user.UserName
                        }, null, null, emailSubject, emailBody, true);
                        user.UserLogs.Add(new UserLog()
                        {
                            Description = "Password reset link generated and sent"
                        });
                        context.SaveChanges();
                        return(View("RecoverSuccess"));
                    }
                }
            }

            return(View(model));
        }
Example #4
0
        public async Task <ActionResult> ChangePassword(ChangePassword model)
        {
            ViewBag.ReturnUrl = Url.Action("ChangePassword");
            var userId = Convert.ToInt32(User.Identity.GetUserId());
            var result = await UserManager.ChangePasswordAsync(userId, model.OldPassword, model.NewPassword);

            if (result.Succeeded)
            {
                SEContext context = new SEContext();
                var       user    = context.User.Where(u => u.Id == userId).FirstOrDefault();
                // Email recipient with password change acknowledgement
                string emailBody    = string.Format("Just a little note from {0} to say your password has been changed today, if this wasn't done by yourself, please contact the site administrator asap", ConfigurationManager.AppSettings["ApplicationName"].ToString());
                string emailSubject = string.Format("{0} - Password change confirmation", ConfigurationManager.AppSettings["ApplicationName"].ToString());
                Services.SendEmail(ConfigurationManager.AppSettings["DefaultFromEmailAddress"].ToString(), new List <string>()
                {
                    user.UserName
                }, null, null, emailSubject, emailBody, true);
                context.SaveChanges();
                return(RedirectToAction("ChangePassword", new { Message = ManageMessageId.ChangePasswordSuccess }));
            }
            else
            {
                AddErrors(result);
            }
            return(View(model));
        }
Example #5
0
        public bool addStockExchange(SEContext se)
        {
            ctx.SEContexts.Add(se);
            int b = ctx.SaveChanges();

            return(b > 0);
        }
        public ActionResult OverPostingEdit(int id, FormCollection collection)
        {
            using (var context = new SEContext())
            {
                var users = context.User.Where(u => u.Id == id);
                if (users.ToList().Count == 0)
                {
                    return(new HttpNotFoundResult());
                }
                var user        = users.FirstOrDefault();
                var currentUser = Convert.ToInt32(User.Identity.GetUserId());

                var propertiesToUpdate = new List <string>()
                                         //{
                                         //	"FirstName", "LastName", "TelNoHome", "TelNoMobile", "TelNoWork", "Title",
                                         //	"Town","Postcode", "SkypeName"
                                         //}
                ;
                if (TryUpdateModel(user, "User", propertiesToUpdate.ToArray(), collection))
                {
                    context.SaveChanges();
                    ViewBag.Notification = "Details updated";
                    return(View("OverPostingEdit"));
                }

                return(View(new UserViewModel(currentUser, User.IsInRole("Admin"), user)));
            }
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
            // SECURE: Remove automatic XFrame option header so we can add it in filters to entire site
            System.Web.Helpers.AntiForgeryConfig.SuppressXFrameOptionsHeader = true;

            // SECURE: Remove server information disclosure
            MvcHandler.DisableMvcResponseHeader = true;

            using (var context = new SEContext())
            {
                context.Database.Initialize(true);
            }
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.MSSqlServer(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(), "Logs")
                         .MinimumLevel.Debug()
                         .CreateLogger();
            Log.Information("Application started");
        }
        public ActionResult InformationDisclosure()
        {
            SEContext context = new SEContext();
            var       user    = context.User.Where(u => u.Id == 38).FirstOrDefault();

            user.LastName = "Bill";
            return(View(user));            // Will never get here
        }
Example #9
0
        public async Task <ActionResult> Register(FormCollection collection)
        {
            var user            = new User();
            var password        = collection["Password"].ToString();
            var confirmPassword = collection["ConfirmPassword"].ToString();

            using (var context = new SEContext())
            {
                if (ModelState.IsValid)
                {
                    var propertiesToUpdate = new[]
                    {
                        "FirstName", "LastName", "UserName", "SecurityQuestionLookupItemId", "SecurityAnswer"
                    };
                    if (TryUpdateModel(user, "User", propertiesToUpdate, collection))
                    {
                        var recaptchaSuccess = ValidateRecaptcha();
                        if (recaptchaSuccess)
                        {
                            var result = await UserManager.CreateAsync(user.UserName, user.FirstName, user.LastName, password, confirmPassword,
                                                                       user.SecurityQuestionLookupItemId, user.SecurityAnswer);

                            if (result.Succeeded || result.Errors.Any(e => e == "Username already registered"))
                            {
                                user = context.User.Where(u => u.UserName == user.UserName).FirstOrDefault();
                                // Email the user to complete the email verification process or inform them of a duplicate registration and would they like to change their password
                                string emailBody    = "";
                                string emailSubject = "";
                                if (result.Succeeded)
                                {
                                    emailSubject = string.Format("{0} - Complete your registration", ConfigurationManager.AppSettings["ApplicationName"].ToString());
                                    emailBody    = string.Format("Welcome to {0}, to complete your registration we just need to confirm your email address by clicking <a href='{1}Account/EmailVerify?EmailVerficationToken={2}'>{1}Account/EmailVerify?EmailVerficationToken={2}</a>. If you did not request this registration then you can ignore this email and do not need to take any further action", ConfigurationManager.AppSettings["ApplicationName"].ToString(), ConfigurationManager.AppSettings["WebsiteBaseUrl"].ToString(), user.EmailConfirmationToken);
                                }
                                else
                                {
                                    emailSubject = string.Format("{0} - Duplicate Registration", ConfigurationManager.AppSettings["ApplicationName"].ToString());
                                    emailBody    = string.Format("You already have an account on {0}. You (or possibly someone else) just attempted to register on {0} with this email address. However you are registered and cannot re-register with the same address. If you'd like to login you can do so by clicking here: <a href='{1}Account/LogOn'>{1}Account/LogOn</a>. If you have forgotten your password you can answer some security questions here to reset your password:<a href='{1}Account/LogOn'>{1}Account/Recover</a>. If it wasn't you who attempted to register with this email address or you did it by mistake, you can safely ignore this email", ConfigurationManager.AppSettings["ApplicationName"].ToString(), ConfigurationManager.AppSettings["WebsiteBaseUrl"].ToString());
                                }

                                Services.SendEmail(ConfigurationManager.AppSettings["DefaultFromEmailAddress"].ToString(), new List <string>()
                                {
                                    user.UserName
                                }, null, null, emailSubject, emailBody, true);
                                return(View("RegisterSuccess"));
                            }
                            else
                            {
                                AddErrors(result);
                            }
                        }
                    }
                }

                var securityQuestions = context.LookupItem.Where(l => l.LookupTypeId == CONSTS.LookupTypeId.SecurityQuestion && l.IsHidden == false).OrderBy(o => o.Ordinal).ToList();
                var registerViewModel = new RegisterViewModel(confirmPassword, password, user, securityQuestions);
                return(View(registerViewModel));
            }
        }
Example #10
0
 public ActionResult Register()
 {
     using (var context = new SEContext())
     {
         var securityQuestions = context.LookupItem.Where(l => l.LookupTypeId == CONSTS.LookupTypeId.SecurityQuestion && l.IsHidden == false).OrderBy(o => o.Ordinal).ToList();
         var registerViewModel = new RegisterViewModel("", "", new User(), securityQuestions);
         return(View(registerViewModel));
     }
 }
 public ActionResult OverPostingEdit(int id)
 {
     using (var context = new SEContext())
     {
         var users       = context.User.Where(u => u.Id == id);
         var currentUser = Convert.ToInt32(User.Identity.GetUserId());
         var user        = users.FirstOrDefault();
         return(View(new UserViewModel(currentUser, User.IsInRole("Admin"), user)));
     }
 }
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         // free managed resources
         if (this.dbContext != null)
         {
             this.dbContext.Dispose();
             this.dbContext = null;
         }
     }
 }
Example #13
0
        public async Task <ActionResult> RecoverPassword(RecoverPassword recoverPasswordModel)
        {
            using (var context = new SEContext())
            {
                var user = context.User.Where(u => u.Id == recoverPasswordModel.Id).FirstOrDefault();
                if (user == null)
                {
                    HandleErrorInfo error = new HandleErrorInfo(new Exception("INFO: The user is not valid"), "Account", "RecoverPassword");
                    return(View("Error", error));
                }
                if (!(user.Enabled))
                {
                    HandleErrorInfo error = new HandleErrorInfo(new Exception("INFO: Your account is not currently approved or active"), "Account", "Recover");
                    return(View("Error", error));
                }
                if (user.SecurityAnswer != recoverPasswordModel.SecurityAnswer)
                {
                    ModelState.AddModelError("SecurityAnswer", "The security answer is incorrect");
                    return(View("RecoverPassword", recoverPasswordModel));
                }
                if (recoverPasswordModel.Password != recoverPasswordModel.ConfirmPassword)
                {
                    ModelState.AddModelError("ConfirmPassword", "The passwords do not match");
                    return(View("RecoverPassword", recoverPasswordModel));
                }
                var recaptchaSuccess = ValidateRecaptcha();
                if (ModelState.IsValid && recaptchaSuccess)
                {
                    var result = await UserManager.ChangePasswordFromTokenAsync(user.Id, recoverPasswordModel.PasswordResetToken, recoverPasswordModel.Password);

                    if (result.Succeeded)
                    {
                        context.SaveChanges();
                        await UserManager.SignInAsync(user.UserName, false);

                        return(View("RecoverPasswordSuccess"));
                    }
                    else
                    {
                        AddErrors(result);
                        return(View("RecoverPassword", recoverPasswordModel));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Password change was not successful");
                    return(View("RecoverPassword", recoverPasswordModel));
                }
            }
        }
Example #14
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     GlobalConfiguration.Configure(WebApiConfig.Register);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     AuthConfig.RegisterAuth();
     AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
     using (var context = new SEContext())
     {
         context.Database.Initialize(true);
     }
 }
Example #15
0
        public IActionResult addSEdata(SEContext obj)
        {
            if (ModelState.IsValid == false)
            {
                return(BadRequest(ModelState));
            }

            var result = repo.addStockExchange(obj);

            if (!result)
            {
                return(BadRequest("Error saving products"));
            }
            return(Created("No Url", new { message = "company added" }));
        }
        public void Initialize()
        {
            IConfiguration ObjConfiguration = new ConfigurationBuilder()
                                              .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                                              .AddJsonFile("appsettings.json")
                                              .Build();
            string str = ObjConfiguration.GetConnectionString("Constr");
            DbContextOptions <DBContext> options = new DbContextOptionsBuilder <DBContext>().UseSqlServer(str).Options;
            DBContext    ObjContext = new DBContext(options);
            IRepository5 rp         = new Repository5(ObjContext);

            se      = new StockExchangeController(rp);
            se_data = new SEContext()
            {
                name = "demo", brief = "demo", address = "demo", remarks = "demo"
            };
        }
Example #17
0
        public ActionResult Edit(int id, FormCollection collection)
        {
            using (var context = new SEContext())
            {
                var users = context.User.Where(u => u.Id == id);
                if (users.ToList().Count == 0)
                {
                    return(new HttpNotFoundResult());
                }
                var user        = users.FirstOrDefault();
                var currentUser = Convert.ToInt32(User.Identity.GetUserId());
                // SECURE: Check user should have access to this account
                if (!User.IsInRole("Admin") && currentUser != user.Id)
                {
                    return(new HttpNotFoundResult());
                }

                var propertiesToUpdate = new List <string>()
                {
                    "FirstName", "LastName", "TelNoHome", "TelNoMobile", "TelNoWork", "Title",
                    "Town", "Postcode", "SkypeName"
                };
                if (User.IsInRole("Admin"))
                {
                    propertiesToUpdate.Add("Approved");
                    propertiesToUpdate.Add("Enabled");
                    propertiesToUpdate.Add("UserName");
                }
                if (TryUpdateModel(user, "User", propertiesToUpdate.ToArray(), collection))
                {
                    if (user.Id == currentUser && user.Enabled == false)
                    {
                        ModelState.AddModelError("", "You cannot disable your own user account");
                    }
                    else
                    {
                        context.SaveChanges();
                        return(RedirectToAction("Index", "User"));
                    }
                }

                return(View(new UserViewModel(currentUser, User.IsInRole("Admin"), user)));
            }
        }
        //存储token和fileId对应信息
        public int SaveToken(string tokenString, FileInfo file)
        {
            using (SEContext context = new SEContext())
            {
                var IsTokenExisted = from token in context.Token
                                     where token.TokenId == tokenString
                                     select token;
                if (IsTokenExisted == null)
                {
                    context.Token.Add(
                        new Token {
                        TokenId = tokenString
                    });
                    context.SaveChanges();
                }

                var IsFileExisted = from fileInfo in context.FileInfo
                                    where fileInfo.FileInfoId == file.FileInfoId
                                    select fileInfo;
                if (IsFileExisted == null)
                {
                    context.FileInfo.Add(file);
                    context.SaveChanges();
                }

                var IsRecordExisted = from item in context.Token_File
                                      where item.TokenId == tokenString
                                      where item.FileId == file.FileInfoId
                                      select item;
                if (IsRecordExisted == null)
                {
                    context.Token_File.Add(
                        new Token_File
                    {
                        FileId  = file.FileInfoId,
                        TokenId = tokenString
                    }
                        );
                    context.SaveChanges();
                }
            }
            return(0);
        }
Example #19
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="id">Unique identifier for the user</param>
 /// <returns></returns>
 public ActionResult ChangeEmailAddress(int id)
 {
     using (var context = new SEContext())
     {
         var users       = context.User.Where(u => u.Id == id);
         var currentUser = Convert.ToInt32(User.Identity.GetUserId());
         if (users.ToList().Count == 0)
         {
             return(new HttpNotFoundResult());
         }
         var user = users.FirstOrDefault();
         // SECURE: Check user should have access to this account
         if (!User.IsInRole("Admin") && currentUser != user.Id)
         {
             return(new HttpNotFoundResult());
         }
         return(View(new UserViewModel(currentUser, User.IsInRole("Admin"), user)));
     }
 }
 //保存文件信息
 public int SaveFileId(FileInfo fileInfo)
 {
     using (SEContext context = new SEContext())
     {
         string fileId = fileInfo.FileInfoId;
         var    info   = from file in context.FileInfo
                         where file.FileInfoId == fileId
                         select file;
         if (info != null)
         {
             return(-1);
         }
         else
         {
             context.FileInfo.Add(fileInfo);
         }
         context.SaveChanges();
     }
     return(0);
 }
Example #21
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="id">Unique identifier for the user</param>
 /// <returns></returns>
 public ActionResult Log(int id)
 {
     using (var context = new SEContext())
     {
         var users       = context.User.Where(u => u.Id == id);
         var currentUser = Convert.ToInt32(User.Identity.GetUserId());
         if (users.ToList().Count == 0)
         {
             return(new HttpNotFoundResult());
         }
         var user = users.FirstOrDefault();
         // SECURE: Check user should have access to this account
         if (!User.IsInRole("Admin") && currentUser != user.Id)
         {
             return(new HttpNotFoundResult());
         }
         ViewBag.UserName = user.UserName;
         return(View(user.UserLogs.OrderByDescending(ul => ul.DateCreated).Take(10).ToList()));
     }
 }
Example #22
0
        public ActionResult Landing()
        {
            var currentUserId = Convert.ToInt32(User.Identity.GetUserId());

            using (var context = new SEContext())
            {
                var users = context.User.Where(u => u.Id == currentUserId);
                if (users.ToList().Count == 0)
                {
                    return(new HttpNotFoundResult());
                }
                var     user                = users.FirstOrDefault();
                var     activityLogs        = user.UserLogs.OrderByDescending(d => d.DateCreated);
                UserLog lastAccountActivity = null;
                if (activityLogs.ToList().Count > 1)
                {
                    lastAccountActivity = activityLogs.Skip(1).FirstOrDefault();
                }
                return(View(new LandingViewModel(user.FirstName, lastAccountActivity, currentUserId)));
            }
        }
 public void SignOut()
 {
     try
     {
         var userName = AuthenticationManager.User.Identity.Name;
         using (var context = new SEContext())
         {
             var user = context.User.Where(u => u.UserName == userName).FirstOrDefault();
             user.UserLogs.Add(new UserLog()
             {
                 Description = "User Logged Off"
             });
             context.SaveChanges();
         }
     }
     catch {
     }
     finally
     {
         AuthenticationManager.SignOut();
     }
 }
Example #24
0
        public ActionResult EmailVerify()
        {
            var emailVerificationToken = Request["EmailVerficationToken"] ?? "";

            using (var context = new SEContext())
            {
                var user = context.User.Where(u => u.EmailConfirmationToken == emailVerificationToken).FirstOrDefault();
                if (user == null)
                {
                    HandleErrorInfo error = new HandleErrorInfo(new ArgumentException("INFO: The email verification token is not valid or has expired"), "Account", "EmailVerify");
                    return(View("Error", error));
                }
                user.EmailVerified          = true;
                user.EmailConfirmationToken = null;
                user.UserLogs.Add(new UserLog()
                {
                    Description = "User Confirmed Email Address"
                });
                context.SaveChanges();
                return(View("EmailVerificationSuccess"));
            }
        }
 public UserStore(SEContext dbContext)
 {
     this.dbContext = dbContext;
 }
 public UserRepository(SEContext context) : base(context)
 {
 }
 public MyUserManager()
 {
     Context   = new SEContext();
     UserStore = new UserStore <User>(Context);
 }
Example #28
0
 public UserController()
 {
     context = new SEContext();
 }
Example #29
0
 public UnitOfWork(SEContext context)
 {
     _context = context;
 }
Example #30
0
 public BaseRepository(SEContext context)
 {
     Context = context;
 }