public AccountController(
     IAuthenticationService accountService,
     FormsAuthenticationWrapper formsAuthenticationWrapper)
 {
     _accountService             = accountService ?? throw new ArgumentNullException(nameof(accountService));
     _formsAuthenticationWrapper = formsAuthenticationWrapper ?? throw new ArgumentNullException(nameof(formsAuthenticationWrapper));
 }
Beispiel #2
0
        public HttpResponseMessage Logout()
        {
            var formsAuth = new FormsAuthenticationWrapper();

            formsAuth.SignOut();

            return(Request.CreateResponse(HttpStatusCode.NoContent));
        }
Beispiel #3
0
        public async Task <HttpResponseMessage> Post([FromBody] User user)
        {
            var responseContent = user.ValidateLoginInput();

            if (responseContent.Any())
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, responseContent));
            }

            var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["PLSS"].ConnectionString);

            try
            {
                await connection.OpenAsync();

                var databaseUser = CommandExecutor.ExecuteCommand(new GetUserCommand(connection, user.UserName)
                {
                    DefaultFields = "UserId,UserName,Password"
                });

                if (databaseUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  new [] { new KeyValuePair <string, string>("login.email", "User does not exist.") }));
                }

                var formsAuth = new FormsAuthenticationWrapper();

                if (databaseUser.Password != formsAuth.HashPasswordForStoringInConfigFile(user.Password))
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  new[] { new KeyValuePair <string, string>("login.password", "Incorrect password.") }));
                }

                formsAuth.SetAuthCookie(databaseUser.UserName, false);

                var token = CommandExecutor.ExecuteCommand(new UpdateUserTokenCommand(connection, databaseUser));

                return(Request.CreateResponse(HttpStatusCode.OK, new ResponseContainer <TokenContainer>(token)));
            }
            catch (Exception ex)
            {
                Log.LogException(LogLevel.Fatal, "problem signing in", ex);

                return(Request.CreateResponse(HttpStatusCode.InternalServerError,
                                              new ResponseContainer(HttpStatusCode.InternalServerError, ex.Message)));
            }
            finally
            {
                connection.Close();
                connection.Dispose();
            }
        }
Beispiel #4
0
        public ActionResult Register(RegisterModel model, bool captchaValid, string returnUrl)
        {
            if (ModelState.IsValid && captchaValid)
            {
                // Attempt to register the user
                RepositoryUser repoUser = new RepositoryUser(Server.MapPath("~/App_Data/FrmBlog.db"), DbType.SqLite);
                if (repoUser.IsRecordUser(model.Email))
                {
                    ModelState.AddModelError("Email", "Email başka bir kullanıcıya ait");
                    return(View(model));
                }
                User user = new Models.User();
                user.Email       = model.Email;
                user.RoleId      = Role.Member.RoleId;
                user.Name        = model.UserName;
                user.Password    = model.Password;
                user.PicturePath = new FrmBlog.Avatar.Avatar().GetRandomAvatar();
                user.DisplayName = model.UserName;
                repoUser.Insert(user);
                IFormsAuthentication auth = new FormsAuthenticationWrapper();
                auth.SetAuthCookie(user.Email, true);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                    !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return(Redirect(returnUrl));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
            if (!captchaValid)
            {
                ModelState.AddModelError("", "Doğrulama kodu yanlış");
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Beispiel #5
0
        /// <summary>
        /// Hashes a combination of the password and salt using SHA1 via FormsAuthentication, or
        /// SHA256 is FormsAuthentication is not enabled.
        /// </summary>
        public static string HashPassword(string password, string salt)
        {
            bool isFormsAuthEnabled = FormsAuthenticationWrapper.IsEnabled();

            if (isFormsAuthEnabled)
            {
                return(FormsAuthentication.HashPasswordForStoringInConfigFile(password + salt, "SHA1"));
            }
            else
            {
                SHA256 sha  = new SHA256Managed();
                byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(password + "salt"));

                StringBuilder stringBuilder = new StringBuilder();
                foreach (byte b in hash)
                {
                    stringBuilder.AppendFormat("{0:x2}", b);
                }

                return(stringBuilder.ToString());
            }
        }
Beispiel #6
0
        public async Task<HttpResponseMessage> Reset(ResetPasswordViewModel model)
        {
            if (string.IsNullOrEmpty(model.UserName))
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["plss"].ConnectionString))
            {
                await connection.OpenAsync();

                var user = CommandExecutor.ExecuteCommand(new GetUserCommand(connection, model.UserName));

                if (user == null)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest);
                }

                var formsAuth = new FormsAuthenticationWrapper();
                var token = CommandExecutor.ExecuteCommand(new GenerateTokenCommand());
                user.Password = formsAuth.HashPasswordForStoringInConfigFile(token.Token);

                var uCount = connection.Execute("update users set password = @password where userid = @userid", new
                    {
                        user.UserId,
                        user.Password
                    });
                Debug.Assert(uCount == 1, "update didn't work");

                CommandExecutor.ExecuteCommand(
                    new ResetPasswordEmailCommand(new ResetPasswordEmailCommand.MailTemplate(new[] {user.UserName},
                                                                                             new[] {"*****@*****.**"},
                                                                                             user.Name, token.Token)));
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }
Beispiel #7
0
        public async Task<HttpResponseMessage> Post(RegistrationViewModel registrant)
        {
            registrant.Validate(ModelState);

            if (!ModelState.IsValid)
            {
                var errors = ModelState.ToErrors();

                return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
            }

            var formsAuth = new FormsAuthenticationWrapper();
            registrant.Password = formsAuth.HashPasswordForStoringInConfigFile(registrant.Password);

            var user = new User(registrant);

            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["plss"].ConnectionString))
            {
                await connection.OpenAsync();
                var uInserts = connection.Execute(Models.User.InsertString, user);
                Debug.Assert(uInserts == 1, "inserted into users successfully");

                formsAuth.SetAuthCookie(user.UserName, false);
            }

            CommandExecutor.ExecuteCommand(
                new WelcomeNewUserEmailCommand(
                    new WelcomeNewUserEmailCommand.MailTemplate(new[] {user.UserName}, App.AdminEmails, user.Name)));

            CommandExecutor.ExecuteCommand(
                new NotificationOfRegistrationEmailCommand(
                    new NotificationOfRegistrationEmailCommand.MailTemplate(App.AdminEmails, new[] {"*****@*****.**"},
                                                                            user)));

            return Request.CreateResponse(HttpStatusCode.OK,
                                          new ResponseContainer<TokenContainer>(new TokenContainer(user.Token)));
        }
Beispiel #8
0
        public ActionResult Sor(FormCollection frmCol, RegisterModel model)
        {
            if (Request.IsAuthenticated)
            {
                bool     sor  = true;
                User     user = _repoUser.GetUserByEmail(HttpContext.User.Identity.Name);
                Question ques = new Question();
                ques.Detail = frmCol["Question.Detail"].Replace("'", "%t%").Replace("@", "@@");

                ques.Title = frmCol["Question.Title"].Replace("'", "%t%").Replace("@", "@@");
                ValidateQuestion(frmCol, ref sor);
                TagValidControl(frmCol, ref sor);
                if (!sor)
                {
                    return(View(FrmView.Data.WithQuestion(ques)));
                }

                ques.Date      = DateTime.Now;
                ques.Detail    = frmCol["Question.Detail"].Replace("'", "%t%").Replace("@", "@@");
                ques.IPAddress = GetIpAddress();
                ques.State     = State.Yayinda;
                ques.Title     = frmCol["Question.Title"].Replace("'", "%t%").Replace("@", "@@");
                ques.User      = user;
                ques.UserId    = user.UserId;
                _repoQues.Insert(ques);
                var ary2       = frmCol["tags"].Split(',');
                int lastQuesId = _repoQues.LastQuestionId();
                InsertTag(ary2, lastQuesId);
                TempData["mesaj"] = "Sorunuz eklendi";
                return(RedirectToAction("Succeed", "Soru"));
            }
            else
            {
                bool     createUser = true;
                Question ques       = new Question();

                ques.Detail = frmCol["Question.Detail"].Replace("'", "%t%").Replace("@", "@@");
                ques.Title  = frmCol["Question.Title"].Replace("'", "%t%").Replace("@", "@@");
                ValidateQuestion(frmCol, ref createUser);
                if (string.IsNullOrEmpty(frmCol["RegisterModel.UserName"]))
                {
                    ModelState.AddModelError("RegisterModel.UserName", "Kullanıcı isminizi giriniz");
                    ModelState.AddModelError("", "İsminizi giriniz");
                    createUser = false;
                }
                if (string.IsNullOrEmpty(frmCol["RegisterModel.Email"]) || !Regex.IsMatch(frmCol["RegisterModel.Email"], @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
                {
                    ModelState.AddModelError("RegisterModel.Email", "Email giriniz");
                    ModelState.AddModelError("", "Email giriniz");
                    createUser = false;
                }
                if (string.IsNullOrEmpty(frmCol["RegisterModel.Password"]))
                {
                    ModelState.AddModelError("RegisterModel.Password", "Şifrenizi giriniz");
                    ModelState.AddModelError("", "Şifrenizi giriniz");
                    createUser = false;
                }
                if (_repoUser.IsRecordUser(frmCol["RegisterModel.Email"]))
                {
                    ModelState.AddModelError("RegisterModel.Email", "Email başka bir kullanıcıya ait");
                    ModelState.AddModelError("", "Email başka bir kullanıcıya ait");
                    createUser = false;
                }
                TagValidControl(frmCol, ref createUser);
                if (createUser)
                {
                    User user = new Models.User();
                    user.Email       = frmCol["RegisterModel.Email"];
                    user.RoleId      = Role.Member.RoleId;
                    user.Name        = frmCol["RegisterModel.UserName"];
                    user.Password    = frmCol["RegisterModel.Password"];
                    user.PicturePath = new FrmBlog.Avatar.Avatar().GetRandomAvatar();
                    _repoUser.Insert(user);
                    IFormsAuthentication auth = new FormsAuthenticationWrapper();
                    auth.SetAuthCookie(user.Email, true);

                    ques.Date      = DateTime.Now;
                    ques.Detail    = frmCol["Question.Detail"].Replace("'", "%t%").Replace("@", "@@");
                    ques.IPAddress = GetIpAddress();
                    ques.State     = State.Yayinda;
                    ques.Title     = frmCol["Question.Title"].Replace("'", "%t%").Replace("@", "@@");
                    ques.User      = _repoUser.GetUserByEmail(user.Email);;
                    ques.UserId    = ques.User.UserId;
                    _repoQues.Insert(ques);
                    TempData["mesaj"] = "Sorunuz eklendi";
                    var ary2       = frmCol["tags"].Split(',');
                    int lastQuesId = _repoQues.LastQuestionId();
                    InsertTag(ary2, lastQuesId);
                    return(RedirectToAction("Succeed", "Soru"));
                }
                return(View());
            }
        }
Beispiel #9
0
        public ActionResult Detay(long id, string title, FormCollection frmCol, bool captchaValid)
        {
            ViewBag.isPostBack = "1";
            if (Request.IsAuthenticated)
            {
                FrmViewData frm          = new FrmViewData();
                User        user         = _repoUser.GetUserByEmail(HttpContext.User.Identity.Name);
                bool        createAnswer = true;
                if (string.IsNullOrEmpty(frmCol["description"]) || frmCol["description"].Length < 17)
                {
                    //ModelState.AddModelError("desciption", "Detaylı Açıklama Boş olamaz ve en az 10 karekter uzunluğunda olması gerekli");
                    ModelState.AddModelError("", "Detaylı Açıklama boş olamaz ve en az 10 karekter uzunluğunda olması gerekli");
                    createAnswer = false;
                }

                //if (!captchaValid)
                //{
                //    ModelState.AddModelError("valid", "Doğrulama kodu yanlış.");
                //    createAnswer = false;
                //}
                if (createAnswer)
                {
                    Answer answer = new Answer();
                    answer.BestReply  = false;
                    answer.Date       = DateTime.Now;
                    answer.IPAddress  = GetIpAddress();
                    answer.Reply      = frmCol["description"].Replace("'", "%t%").Replace("@", "@@");
                    answer.State      = State.Yayinda;
                    answer.User       = user;
                    answer.UserId     = user.UserId;
                    answer.QuestionId = id;
                    _repoAns.Insert(answer);
                }
                frm.Question = _repoQues.GetById(id);
                frm.Tags     = _repoTag.GetListByQuestionId(id);
                frm.Answers  = _repoAns.GetListByQuestionId(id);
                List <Question> benzerSorular = BulBenzerSorulari <long>(frm);
                frm.Questions = benzerSorular;

                ViewBag.Title = frm.Question.Title;
                return(View(frm));
            }
            else
            {
                bool createUser = true;
                if (string.IsNullOrEmpty(frmCol["description"]) || frmCol["description"].Length < 17)
                {
                    //ModelState.AddModelError("desciption", "Detaylı Açıklama Boş olamaz ve en az 10 karekter uzunluğunda olması gerekli");
                    ModelState.AddModelError("", "Detaylı Açıklama boş olamaz ve en az 10 karekter uzunluğunda olması gerekli");
                    createUser = false;
                }
                ValiDateUser(frmCol, ref createUser);
                if (!captchaValid)
                {
                    ModelState.AddModelError("valid", "Doğrulama kodu yanlış");
                    ModelState.AddModelError("", "Doğrulama kodu yanlış");
                    createUser = false;
                }
                if (createUser)
                {
                    User user = new Models.User();
                    user.Email       = frmCol["RegisterModel.Email"];
                    user.RoleId      = Role.Member.RoleId;
                    user.Name        = frmCol["RegisterModel.UserName"];
                    user.Password    = frmCol["RegisterModel.Password"];
                    user.PicturePath = new FrmBlog.Avatar.Avatar().GetRandomAvatar();
                    _repoUser.Insert(user);
                    IFormsAuthentication auth = new FormsAuthenticationWrapper();
                    auth.SetAuthCookie(user.Email, true);

                    Answer answer = new Answer();
                    answer.BestReply  = false;
                    answer.Date       = DateTime.Now;
                    answer.IPAddress  = GetIpAddress();
                    answer.Reply      = frmCol["description"].Replace("'", "%t%");
                    answer.State      = State.Yayinda;
                    answer.User       = _repoUser.GetUserByEmail(user.Email);
                    answer.UserId     = answer.User.UserId;
                    answer.QuestionId = id;
                    _repoAns.Insert(answer);
                }
                FrmViewData frm = new FrmViewData();
                frm.Question = _repoQues.GetById(id);
                frm.Tags     = _repoTag.GetListByQuestionId(id);
                frm.Answers  = _repoAns.GetListByQuestionId(id);
                List <Question> benzerSorular = BulBenzerSorulari <long>(frm);
                frm.Questions = benzerSorular;
                ViewBag.Title = frm.Question.Title;
                return(RedirectToAction("Detay", new { id = id, title = title }));
            }
        }
Beispiel #10
0
        public async Task <ActionResult> Update(ProfileUserViewModel model)
        {
            model.Validate(ModelState);

            if (!ModelState.IsValid)
            {
                TempData["error"] = ModelState.ToErrors();

                return(RedirectToRoute("", new
                {
                    Controller = "settings",
                    Action = "index"
                }));
            }

            var formsAuth = new FormsAuthenticationWrapper();

            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["PLSS"].ConnectionString))
            {
                await connection.OpenAsync();

                var user = CommandExecutor.ExecuteCommand(new GetUserCommand(connection, User.Identity.Name)
                {
                    DefaultFields = "userid, username, password"
                });

                if (user == null)
                {
                    TempData["error"] = "You must log in to edit your settings";

                    return(RedirectToRoute("", new
                    {
                        Controller = "Home",
                        Action = "Index"
                    }));
                }

                //changing usernames
                if (user.UserName != model.Email)
                {
                    var emailExists = CommandExecutor.ExecuteCommand(new GetUserCommand(connection, model.Email));
                    // make sure username isn't in use
                    if (emailExists != null)
                    {
                        TempData["error"] = new List <KeyValuePair <string, string> >
                        {
                            new KeyValuePair <string, string>("Email", "This email address is already in use")
                        };

                        return(RedirectToRoute("", new
                        {
                            Controller = "settings",
                            Action = "index"
                        }));
                    }

                    // otherwise sign them in with the new address
                    formsAuth.SignOut();

                    formsAuth.SetAuthCookie(model.Email, false);
                }

                // changing passwords
                if (!string.IsNullOrEmpty(model.CurrentPassword))
                {
                    model.HashedPassword = formsAuth.HashPasswordForStoringInConfigFile(model.NewPassword);
                }

                var re = new Regex(".jpg$", RegexOptions.IgnoreCase);

                if (model.File != null && model.File.ContentLength > 0 && re.IsMatch(model.File.FileName))
                {
                    using (var ms = new MemoryStream())
                    {
                        model.File.InputStream.CopyTo(ms);
                        model.Seal = ms.ToArray();
                    }
                }

                // update the values
                var uCount = connection.Execute(model.UpdateString, new
                {
                    model.Email,
                    model.First,
                    model.Last,
                    model.License,
                    model.HashedPassword,
                    model.Seal,
                    user.UserId
                });
                Debug.Assert(uCount == 1, "updates was wrong.");

                return(RedirectToRoute("", new
                {
                    Controller = "settings",
                    Action = "index"
                }));
            }
        }