public virtual IActionResult CreateMember([FromBody] Member newMember) { if (Request.Headers.ContainsKey("recaptchaToken")) { string EncodeResponse = Request.Headers["recaptchaToken"]; if (EncodeResponse == null) { return(this.NotFound()); } if (!Recaptcha.Validate(EncodeResponse, reCaptcha)) { return(this.NotFound()); } } else { return(this.NotFound()); } newMember.PassWord = BCrypt.Net.BCrypt.HashPassword(newMember.PassWord); if (repository.Add(newMember) != null) { return(this.Created($"[controller]", newMember)); } return(this.NotFound()); }
public async Task <ActionResult> ContactUs([FromServices] DataContext dataContext, ContactUsViewModel data) { if (ModelState.IsValid) { if (!Recaptcha.Validate(Request.Form["g-recaptcha-response"])) { ModelState.AddModelError("ReCaptchaValid", "ReCaptcha failed please try again"); } else { ContactSubmission contactSubmission = ContactSubmission.CreateFromViewModel(data); contactSubmission.EmailedTo = Settings.Emails.ToAddresses; dataContext.ContactSubmissions.Add(contactSubmission); dataContext.SaveChanges(currentUserName); Response resp = await EmailFacade.SendAsync(contactSubmission); SimpleNotifier noty = notifier(); if (resp.StatusCode == HttpStatusCode.Accepted) { noty.AddMessage(MsgTypes.Success, "Thanks for getting in contact, we will reply in due course"); return(Redirect("/")); } else { noty.AddMessage(MsgTypes.Warning, "Problems sending sending your message, please try again."); return(View(data)); } } } return(View(data)); }
public ActionResult NewComment(CommentAttributes commentAttributes) { // Get item url var itmUrl = new UriBuilder(LinkManager.GetItemUrl(Context.Database.GetItem(commentAttributes.BlogPostId), new UrlOptions { AlwaysIncludeServerUrl = true })); BlogpostId = commentAttributes.BlogPostId; Recaptcha recaptcha = new Recaptcha(); GetSettings objGetSettings = new GetSettings(); var setting = objGetSettings.GetSetting(BlogpostId); commentAttributes.CaptchaResponse = Request["g-recaptcha-response"]; try { Comment cmt = new Comment { PostId = commentAttributes.BlogPostId, Author = commentAttributes.AuthorName, Email = commentAttributes.AuthorEmail, Date = DateTime.Now, Body = commentAttributes.AuthorComment }; if (setting.SiteKey.IsNullOrEmpty()) { // Insert comment in comment in mongodb database. _objRepository.Insert(cmt); SendMailToAdmin(BlogpostId); var uri = AddQuery(itmUrl, "status", "success"); Response.Redirect(uri.ToString()); } if (!setting.SiteKey.IsNullOrEmpty()) { if (recaptcha.Validate(commentAttributes.CaptchaResponse, BlogpostId)) { // Insert comment in comment in mongodb database. _objRepository.Insert(cmt); SendMailToAdmin(BlogpostId); var uri = AddQuery(itmUrl, "status", "success"); Response.Redirect(uri.ToString()); } else { Log.Error("Captcha not filled", this); var errorUri = AddQuery(itmUrl, "status", "captchaerror"); Response.Redirect(errorUri.ToString()); } } } catch (Exception ex) { Log.Error(ex.Message, this); var errorUri = AddQuery(itmUrl, "status", "error"); Response.Redirect(errorUri.ToString()); } return(Json("ok", JsonRequestBehavior.AllowGet)); }
public async Task <ActionResult> TutorRegister(TutorRegisterViewModel model) { if (ModelState.IsValid) { string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = (Recaptcha.Validate(EncodedResponse) == "true" ? true : false); if (IsCaptchaValid) { var check = Utility.CheckUserAge(model.Birthday); if (check == false) { ViewData["Message"] = "You are too young!"; return(View(model)); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var user2 = UserManager.FindByEmail(model.Email); new TutorRepository().SaveTutor( new Tutor() { Name = model.Name, Email = user2.Email, Birthday = model.Birthday, Address = model.Address, Postcode = model.Postcode, NiN = model.NiN, MobileNumber = model.MobileNumber, UserId = user2.Id }); new RolesRepository().UserManger().AddToRoles(user2.Id, "Tutor"); string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account"); ViewBag.Message = "Check your email and confirm your account, you must be confirmed " + "before you can log in."; ViewBag.UserId = user.Id; return(View("Info")); } ViewData["Message"] = "User already exist!"; AddErrors(result); } else { TempData["recaptcha"] = "Please verify that you are not a robot!"; } } // If we got this far, something failed, redisplay form return(View(model)); }
public ActionResult ReplyComment(ReplyCommentAttributes commentAttributes) { BlogpostId = commentAttributes.CurrentItem; Recaptcha recaptcha = new Recaptcha(); GetSettings objGetSettings = new GetSettings(); var setting = objGetSettings.GetSetting(BlogpostId); try { Comment cmt = new Comment { PostId = commentAttributes.CurrentItem, CommentId = Guid.NewGuid().ToString(), ParentId = commentAttributes.hfParentCommentId, Author = commentAttributes.Name, Email = commentAttributes.Email, Date = DateTime.Now, Body = commentAttributes.Comment }; if (setting.SiteKey.IsNullOrEmpty()) { // Insert comment in comment in mongodb database. _objRepository.Insert(cmt); SendMailToAdmin(BlogpostId); return(Json("success", JsonRequestBehavior.AllowGet)); } if (!setting.SiteKey.IsNullOrEmpty()) { if (recaptcha.Validate(commentAttributes.captchaResponse, BlogpostId)) { // Insert comment in comment in mongodb database. _objRepository.Insert(cmt); SendMailToAdmin(BlogpostId); return(Json("success", JsonRequestBehavior.AllowGet)); } else { Log.Error("Captcha not filled", this); return(Json("captchaerror", JsonRequestBehavior.AllowGet)); } } } catch (Exception ex) { Log.Error(ex.Message, this); return(Json("error", JsonRequestBehavior.AllowGet)); } return(Json("ok", JsonRequestBehavior.AllowGet)); }
public ActionResult ThumbUp(String itemKey, string captchaChallenge, string captchaResponse) { if (!string.IsNullOrEmpty(captchaChallenge) && !string.IsNullOrEmpty(captchaResponse)) { var validCaptcha = Recaptcha.Validate(captchaChallenge, captchaResponse, Request.UserHostAddress); if (!validCaptcha) { return(this.EmptyHtml()); } } else if (string.IsNullOrEmpty(captchaResponse) && !string.IsNullOrEmpty(captchaChallenge)) { return(this.EmptyHtml()); } AddDatasetVote(1, itemKey); return(this.GetRefreshedRatesHtml(itemKey)); }
public void ValidateCaptchaKey(object sender, EventArgs e) { Recaptcha recaptcha = new Recaptcha(); string CaptchaResponse = Request["g-recaptcha-response"]; if (recaptcha.Validate(CaptchaResponse) && !siteKey.IsNullOrEmpty()) { InsertNewComment(); } else { lblInfoText.Text = "Captcha not filled or not match"; } if (siteKey.IsNullOrEmpty()) { InsertNewComment(); } }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = (Recaptcha.Validate(EncodedResponse) == "True" ? true : false); if (IsCaptchaValid == true) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, DOB = model.DOB }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } if (IsCaptchaValid == false) { CaptchaError(); Dispose(true); return(View(model)); } } // If we got this far, something failed, redisplay form return(View(model)); }
public IActionResult PhaseThree(PhaseThreePostViewModel model) { string EncodedResponse = Request.Form["g-recaptcha-response"]; var isCaptchaValid = Recaptcha.Validate(EncodedResponse); if (!ModelState.IsValid) { return(View(model)); } var user = this._context.Users.FirstOrDefault(u => u.Id == model.UserId); var booking = this._context.Bookings.FirstOrDefault(b => b.Id == model.BookingId); if (isCaptchaValid) { if (user != null) { if (booking != null) { booking.UserName = user.UserName; booking.PhoneNumber = model.PhoneNumber; booking.Email = model.Email; booking.Time = model.Time; booking.BookingAddress = model.Address; this._context.Bookings.Update(booking); this._context.SaveChanges(); } } } else { ModelState.AddModelError("", "Error From Google ReCaptcha :" + isCaptchaValid); return(View()); } //return Content(@"/home/service-book/" + model.UserId); //return Content(@"/feedback/user-feedbacks/" + model.UserId + "/" + model.ServiceId ); return(Content(@"/booking/book-review/" + booking.Id)); }
public ActionResult SubmitQuery(Query query) { if (!ModelState.IsValid) { return(View("Index")); } var response = Request["g-recaptcha-response"]; //string secretKey = "6LfV1HkUAAAAAPUeSeHOzVvqQvbdPrl0J8f87qwE"; var client = new WebClient(); string encodedResponse = Request["g-recaptcha-response"]; bool isCaptchaValid = (Recaptcha.Validate(encodedResponse) == "true" ? true : false); if (!isCaptchaValid) { TempData["recaptcha"] = "Please verify that you are not a robot"; return(View("Index")); } else { //subjectTitle string subjectTitle = "You have a query from " + query.firstName + " " + query.lastName; //emailBody string emailBody = "Name: " + query.firstName + " " + query.lastName + "<br />" + "Email: " + query.email + "<br />" + "Mobile: " + query.mobile + "<br />" + "Company Name: " + query.companyName + "<br />" + "Company Turnover: " + query.turnOver + "<br />" + "Message: " + query.message; sendMail(subjectTitle, emailBody); //send success msg to Action TempData["successMsg"] = "Your query has been received. We will contact you soon."; return(RedirectToAction("Index", "Home")); } }
public ActionResult Add(string name, string subject, string comment, string email, string type, bool notify, string datasetId, string datasetName, string parentType, string container, string captchaChallenge, string captchaResponse) { var validCaptcha = Recaptcha.Validate(captchaChallenge, captchaResponse, Request.UserHostAddress); if (!validCaptcha || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(subject) || string.IsNullOrEmpty(comment) || string.IsNullOrEmpty(datasetId)) { return(EmptyHtml()); } var result = new Comment { Subject = subject, Body = comment, Posted = DateTime.Now, Email = email, Type = type, Status = "New", Notify = notify && !string.IsNullOrEmpty(email), ParentName = datasetId, ParentType = parentType, Author = name, ParentContainer = container, }; CommentRepository.AddComment(result); string linkToParent = Request.UrlReferrer.AbsoluteUri; var ni = new NotifyInfo { CommentEntry = result, Link = linkToParent, DatasetName = datasetName, }; Action <NotifyInfo> notification = SendNotification; notification.BeginInvoke(ni, null, null); return(View("Comment", result)); }
protected void btnlogin_Click(object sender, EventArgs e) { var username = usernametxt.Text; var password = passwordtxt.Text; var rememberMe = chkRememberMe.Checked; var EncodedResponse = Request.Form["g-Recaptcha-Response"]; var IsCaptchaValid = Recaptcha.Validate(EncodedResponse) == "true" ? true : false; //if (IsCaptchaValid) //{ if (Page.IsValid) { //string username = usernametxt.Text; //string password = passwordtxt.Text; //bool rememberMe = chkRememberMe.Checked; // Login the user User u = OneDB.Users.SingleOrDefault( x => x.Username == username && x.Password == Security.GetHash(password) ); if (u != null) { //FormsAuthentication.RedirectFromLoginPage(u.Username, rememberMe); Session["email"] = u.Email; Session["id"] = u.Id; Session["username"] = u.Username; Session["role"] = u.role; Security.LoginUser(u.Username, u.role, rememberMe); Response.Redirect("~/Home.aspx"); } else { Label2.Text = "Username or Password incorrect"; } } }
public ActionResult Index(FormCollection collection) { Contact contact = new Contact(); TryUpdateModel(contact); contact.BestTimeToCall = ConvertTimeInput(collection["Hour"], collection["Minute"], collection["Meridiem"]); bool success = false; Dictionary <String, String> disclaimers = new Dictionary <string, string>(); string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = EncodedResponse != null ? (Recaptcha.Validate(EncodedResponse)) : false; Dictionary <String, List <String> > validationErrors = ContactValidation.Validate(contact); ViewData["ValidationErrors"] = validationErrors; if (validationErrors.Count == 0) { if (IsCaptchaValid) { using (var db = new ContactUsEntities()) { db.Contacts.Add(contact); db.SaveChanges(); success = true; disclaimers.Add("success", "Your form has been successfully submitted!"); } } else { disclaimers.Add("warning", "ReCAPTCHA is invalid. Please try reCAPTCHA again!"); } } ViewData["Disclaimers"] = disclaimers; return(success ? View(EmptyContact()) : View(contact)); }
public ActionResult New(Request rq) { var validCaptcha = Recaptcha.Validate(Request.Form["recaptcha_challenge_field"], Request.Form["recaptcha_response_field"], Request.UserHostAddress); if (!validCaptcha) { ModelState.AddModelError("eidCommentsRecaptcha", "Words mismatch"); } if (rq.Name.Trim().Length == 0) { ModelState.AddModelError("Name", "Name is required"); } if (!Regex.IsMatch(rq.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")) { ModelState.AddModelError("Email", "Email format is invalid"); } if (rq.Subject.Trim().Length == 0) { ModelState.AddModelError("Subject", "Subject is required"); } if (rq.Description.Trim().Length == 0) { ModelState.AddModelError("Description", "Description is required"); } if (!ModelState.IsValid) { return(View(rq)); } rq.PostedDate = DateTime.UtcNow; rq.Status = "Submitted"; RequestRepository.AddRequest(rq); return(RedirectToAction("Index")); }
public IActionResult Register(RegisterViewModel model) { string EncodedResponse = Request.Form["g-recaptcha-response"]; var isCaptchaValid = Recaptcha.Validate(EncodedResponse); if (!ModelState.IsValid) { return(View(model)); } if (model.Password != model.ConfirmPassword) { ModelState.AddModelError("", "Password and confirm-password does not match"); } var registrationCode = RandomString(6); if (isCaptchaValid) { User user = new User() { Id = Guid.NewGuid(), FirstName = model.FirstName, LastName = model.LastName, UserName = model.FirstName + "" + model.LastName, EmailAddress = model.EmailAddress.ToLower(), LoginStatus = Infrastructures.Domain.Enums.LoginStatus.Unverified, LoginRetries = 0, Password = BCryptHelper.HashPassword(model.Password, BCryptHelper.GenerateSalt(8)), PhoneNumber = model.PhoneNumber, RegistrationCode = registrationCode, Gender = Infrastructures.Domain.Enums.Gender.Male, CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow, }; this._context.UserRoles.Add(new UserRole() { Id = Guid.NewGuid(), UserId = user.Id.Value, Role = Infrastructures.Domain.Enums.Role.User }); this._context.UserGroups.Add(new UserGroup() { UserId = user.Id.Value, GroupId = Guid.NewGuid(), }); this._context.Users.Add(user); this._context.SaveChanges(); //Send email this.EmailSendNow( WelcomeEmailTemplate(registrationCode, user.UserName), model.EmailAddress, user.UserName, "Welcome To CarWashBooking" ); } else { ModelState.AddModelError("", "Error From Google ReCaptcha :" + isCaptchaValid); return(View()); } return(RedirectToAction("verify")); }
public async Task <IActionResult> Login(LoginViewModel model) { string EncodedResponse = Request.Form["g-recaptcha-response"]; var isCaptchaValid = Recaptcha.Validate(EncodedResponse); if (!ModelState.IsValid) { return(View(model)); } var user = this._context.Users.FirstOrDefault(u => u.EmailAddress.ToLower() == model.EmailAddress.ToLower()); if (isCaptchaValid) { if (user == null) { ModelState.AddModelError("", "Account does'nt exist.Please create your account to login"); return(View(model)); } if (user != null) { var userRole = this._context.UserRoles.FirstOrDefault(ur => ur.UserId == user.Id); if (BCrypt.BCryptHelper.CheckPassword(model.Password, user.Password)) { if (user.LoginStatus == Infrastructures.Domain.Enums.LoginStatus.Locked) { ModelState.AddModelError("", "Your account has been locked "); return(View()); } else if (user.LoginStatus.Equals(Infrastructures.Domain.Enums.LoginStatus.Unverified)) { ModelState.AddModelError("", "Please verify your account first."); return(View()); } else if (user.LoginStatus.Equals(Infrastructures.Domain.Enums.LoginStatus.NeedToChangePassword)) { user.LoginRetries = 0; user.LoginStatus = Infrastructures.Domain.Enums.LoginStatus.Active; this._context.Users.Update(user); this._context.SaveChanges(); var roles = this._context.UserRoles.Where(ur => ur.UserId == user.Id).Select(ur => ur.Role).ToList(); var groupIds = this._context.UserGroups.Where(ug => ug.Id == user.Id).Select(ur => ur.GroupId).ToList(); var groups = this._context.Groups.Where(g => groupIds.Contains(g.Id.Value)).ToList(); WebUser.SetUser(user, roles, groups); await this.SignIn(); return(RedirectToAction("~/account/change-password")); } else if (userRole.Role == Infrastructures.Domain.Enums.Role.Admin && user.LoginStatus == Infrastructures.Domain.Enums.LoginStatus.Active) { user.LoginRetries = 0; user.LoginStatus = Infrastructures.Domain.Enums.LoginStatus.Active; this._context.Users.Update(user); this._context.SaveChanges(); var roles = this._context.UserRoles.Where(ur => ur.UserId == user.Id).Select(ur => ur.Role).ToList(); var groupIds = this._context.UserGroups.Where(ug => ug.Id == user.Id).Select(ur => ur.GroupId).ToList(); var groups = this._context.Groups.Where(g => groupIds.Contains(g.Id.Value)).ToList(); WebUser.SetUser(user, roles, groups); await this.SignIn(); return(RedirectToAction("~/manage/users/index")); } else if (userRole.Role == Infrastructures.Domain.Enums.Role.ContentAdmin && user.LoginStatus == Infrastructures.Domain.Enums.LoginStatus.Active) { user.LoginRetries = 0; user.LoginStatus = Infrastructures.Domain.Enums.LoginStatus.Active; this._context.Users.Update(user); this._context.SaveChanges(); var roles = this._context.UserRoles.Where(ur => ur.UserId == user.Id).Select(ur => ur.Role).ToList(); var groupIds = this._context.UserGroups.Where(ug => ug.Id == user.Id).Select(ur => ur.GroupId).ToList(); var groups = this._context.Groups.Where(g => groupIds.Contains(g.Id.Value)).ToList(); WebUser.SetUser(user, roles, groups); WebID.SetAdminId(user.Id); await this.SignIn(); return(RedirectPermanent("~/manage/users/index")); } else if (user.LoginStatus == Infrastructures.Domain.Enums.LoginStatus.Active) { user.LoginRetries = 0; user.LoginStatus = Infrastructures.Domain.Enums.LoginStatus.Active; this._context.Users.Update(user); this._context.SaveChanges(); var roles = this._context.UserRoles.Where(ur => ur.UserId == user.Id).Select(ur => ur.Role).ToList(); var groupIds = this._context.UserGroups.Where(ug => ug.Id == user.Id).Select(ur => ur.GroupId).ToList(); var groups = this._context.Groups.Where(g => groupIds.Contains(g.Id.Value)).ToList(); WebUser.SetUser(user, roles, groups); WebID.SetUserId(user.Id); await this.SignIn(); //return RedirectPermanent("~/booking/bookings-costumer/" + user.Id); return(Redirect("/services/index")); } else { user.LoginRetries = user.LoginRetries + 1; if (user.LoginRetries >= 3) { ModelState.AddModelError("", "Your account has been locked please contact an Administrator."); user.LoginStatus = Infrastructures.Domain.Enums.LoginStatus.Locked; } this._context.Users.Update(user); this._context.SaveChanges(); ModelState.AddModelError("", "Invalid Login."); return(View()); } } ModelState.AddModelError("", "Invalid Login."); return(View()); } } else { ModelState.AddModelError("", "Error From Google ReCaptcha :" + isCaptchaValid); return(View()); } return(View()); }
public IActionResult BookingWithService(PostAutoBookingViewModel model) { string EncodedResponse = Request.Form["g-recaptcha-response"]; var isCaptchaValid = Recaptcha.Validate(EncodedResponse); if (!ModelState.IsValid) { return(View(model)); } Guid?Id = null; var user = this._context.Users.FirstOrDefault(u => u.Id == model.UserId); var service = this._context.Services.FirstOrDefault(s => s.Id == model.ServiceId); if (isCaptchaValid) { if (user != null) { if (service != null) { Booking booking = new Booking() { Id = Guid.NewGuid(), ServiceId = model.ServiceId, UserId = model.UserId, UserName = user.UserName, PhoneNumber = model.PhoneNumber, Email = model.Email, BookingAddress = model.BookingAddress, Time = model.Time, Title = service.Vehicle, Description = service.Description, Price = service.Price, ServiceType = service.ServiceType, ItemTotal = 1, BookingStatus = Infrastructures.Domain.Enums.BookingStatus.Pending, PaymentType = Infrastructures.Domain.Enums.PaymentType.Unpaid, CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow, }; Id = booking.Id; this._context.Bookings.Add(booking); service.RatingsEnabled = true; service.LikesEnabled = true; service.CommentsEnabled = true; this._context.Services.Update(service); this._context.SaveChanges(); } } } else { ModelState.AddModelError("", "Error From Google ReCaptcha :" + isCaptchaValid); return(View()); } if (Id != null) { return(Content(@"/booking/book-review/" + Id)); } return(Content(@"/services/index")); //return Redirect("/feedback/user-feedbacks/" + model.UserId + "/" + model.ServiceId); }
public async Task <IActionResult> Login([FromBody] ModelLogin model) { // Check request legality. if (!ModelState.IsValid) { return(StatusCode(403, new JsonResult(new ViewModelCode403("Model")))); } var recaptcha = await Recaptcha.Validate(Request); if (!recaptcha.success) { return(StatusCode(403, new JsonResult(new ViewModelCode403("reCaptcha")))); } // Do login. Check password. var users = from u in Db.Users where u.Username == model.Username && u.Password == Password.HashPassword(model.Password, u.PasswordSalt) select u; var user = users.FirstOrDefault(); if (user == null) { return(StatusCode(403, new JsonResult(new ViewModelCode403("Password")))); } // Check ip. Unused yet. var clientIp = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(); /* * var securities = from s in Db.UsersSecurity * where s.Id == user.Id * select s; * * var security = securities.FirstOrDefault(); * if (security == null) * { * Db.UsersSecurity.Add(new UsersSecurity() * { * Id = user.Id * }); * Db.SaveChanges(); * } * * if (!string.IsNullOrWhiteSpace(security.LastLoginIp)) * { * if (security.LastLoginIp != clientIp) * { * * } * } */ // Login successful. // Expire expired tokens. var timeNow = long.Parse(Time.GetTimeStamp13()); var tokens = from t in Db.Tokens where t.ExpireTime < timeNow select t; foreach (var t in tokens) { t.Status = 3; } Db.SaveChanges(); // Temp expire current user other token. tokens = from t in Db.Tokens where t.UserId == user.Id && t.Status == 1 select t; foreach (var t in tokens) { t.Status = 2; } // Generate and save new token. var accessToken = Uuid.GetUuid(); Db.Tokens.Add(new Tokens() { UserId = user.Id, AccessToken = accessToken, ClientToken = model.ClientToken, ClientIp = clientIp, IssueTime = timeNow, ExpireTime = timeNow + (int.Parse(Config["Security:TokenExpireDays"]) * 24 * 60 * 60), Status = 1 }); Db.SaveChanges(); // Return results. var result = new Login() { AccessToken = accessToken, ClientToken = model.ClientToken, User = new User() { UserId = user.OpenUserId } }; return(new JsonResult(result)); }
public async Task <ActionResult> AdminRegister(AdminRegisterViewModel model) { if (ModelState.IsValid) { string EncodedResponse = Request.Form["g-Recaptcha-Response"]; bool IsCaptchaValid = (Recaptcha.Validate(EncodedResponse) == "true" ? true : false); if (IsCaptchaValid) { var check = Utility.CheckUserAge(model.Birthday); if (check == false) { ViewData["Message"] = "You are too young!"; return(View(model)); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { var user2 = UserManager.FindByEmail(model.Email); new AdminRepository().SaveAdmin( new Admin() { Name = model.Name, Email = user2.Email, Birthday = model.Birthday, Address = model.Address, Postcode = model.Postcode, NiN = model.NiN, MobileNumber = model.MobileNumber, UserId = user2.Id }); //THROWING EXCEPTION DUE TO NOT HAVING ANY ROLES //FIX *BEFORE ADDING A USER CHECK IF THERE ARE ANY ROLES* new RolesRepository().UserManger().AddToRoles(user2.Id, "Admin"); // Comment the following line to prevent log in until the user is confirmed. //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account"); // Uncomment to debug locally // TempData["ViewBagLink"] = callbackUrl; ViewBag.Message = "Check your email and confirm your account, you must be confirmed " + "before you can log in."; // ViewBag.ReSendLink = callbackUrl; ViewBag.UserId = user.Id; return(View("Info")); //return RedirectToAction("Index", "Home"); } ViewData["Message"] = "User already exist!"; AddErrors(result); } else { TempData["recaptcha"] = "Please verify that you are not a robot!"; } } // If we got this far, something failed, redisplay form return(View(model)); }
public bool RecaptchaValidate(string challenge, string response) { return(Recaptcha.Validate(challenge, response, Request.UserHostAddress)); }
public HttpResponseMessage Submit() { var form = JObject.Parse(HttpContextSource.Current.Request.Form["data"].ToString()); var statuses = new List <FilesStatus>(); try { //todo can we eliminate the HttpContext here UploadWholeFile(HttpContextSource.Current, statuses); var files = new JArray(); form["Files"] = files; int i = 1; foreach (var item in statuses) { var file = new JObject(); file["name"] = item.name; file["url"] = OpenFormUtils.ToAbsoluteUrl(item.url); files.Add(file); //form["File"+i] = OpenFormUtils.ToAbsoluteUrl(item.url); i++; } } catch (Exception exc) { Log.Logger.Error(exc); } try { form["IPAddress"] = Request.GetIPAddress(); int moduleId = ActiveModule.ModuleID; OpenFormController ctrl = new OpenFormController(); var content = new OpenFormInfo() { ModuleId = moduleId, Json = form.ToString(), CreatedByUserId = UserInfo.UserID, CreatedOnDate = DateTime.Now, LastModifiedByUserId = UserInfo.UserID, LastModifiedOnDate = DateTime.Now, Html = "", Title = "Form submitted - " + DateTime.Now.ToString() }; ctrl.AddContent(content); var res = new ResultDTO() { Message = "Form submitted." }; string template = (string)ActiveModule.ModuleSettings["template"]; var razorscript = new FileUri(Path.GetDirectoryName(template), "aftersubmit.cshtml"); res.AfterSubmit = razorscript.FileExists; string jsonSettings = ActiveModule.ModuleSettings["data"] as string; if (!string.IsNullOrEmpty(jsonSettings)) { SettingsDTO settings = JsonConvert.DeserializeObject <SettingsDTO>(jsonSettings); HandlebarsEngine hbs = new HandlebarsEngine(); dynamic data = null; string formData = ""; if (form != null) { if (!string.IsNullOrEmpty(settings.Settings.SiteKey)) { Recaptcha recaptcha = new Recaptcha(settings.Settings.SiteKey, settings.Settings.SecretKey); RecaptchaValidationResult validationResult = recaptcha.Validate(form["recaptcha"].ToString()); if (!validationResult.Succeeded) { return(Request.CreateResponse(HttpStatusCode.Forbidden)); } form.Remove("recaptcha"); } string templateFilename = HostingEnvironment.MapPath("~/" + template); string schemaFilename = Path.GetDirectoryName(templateFilename) + "\\" + "schema.json"; JObject schemaJson = JsonUtils.GetJsonFromFile(schemaFilename); //form["schema"] = schemaJson; // default options string optionsFilename = Path.GetDirectoryName(templateFilename) + "\\" + "options.json"; JObject optionsJson = null; if (File.Exists(optionsFilename)) { string fileContent = File.ReadAllText(optionsFilename); if (!string.IsNullOrWhiteSpace(fileContent)) { optionsJson = JObject.Parse(fileContent); //form["options"] = optionsJson; } } // language options optionsFilename = Path.GetDirectoryName(templateFilename) + "\\" + "options." + DnnLanguageUtils.GetCurrentCultureCode() + ".json"; if (File.Exists(optionsFilename)) { string fileContent = File.ReadAllText(optionsFilename); if (!string.IsNullOrWhiteSpace(fileContent)) { optionsJson = JObject.Parse(fileContent); //form["options"] = optionsJson; } } var enhancedForm = form.DeepClone() as JObject; OpenFormUtils.ResolveLabels(enhancedForm, schemaJson, optionsJson); data = OpenFormUtils.GenerateFormData(enhancedForm.ToString(), out formData); } if (settings != null && settings.Notifications != null) { foreach (var notification in settings.Notifications) { try { MailAddress from = FormUtils.GenerateMailAddress(notification.From, notification.FromEmail, notification.FromName, notification.FromEmailField, notification.FromNameField, form); MailAddress to = FormUtils.GenerateMailAddress(notification.To, notification.ToEmail, notification.ToName, notification.ToEmailField, notification.ToNameField, form); MailAddress reply = null; if (!string.IsNullOrEmpty(notification.ReplyTo)) { reply = FormUtils.GenerateMailAddress(notification.ReplyTo, notification.ReplyToEmail, notification.ReplyToName, notification.ReplyToEmailField, notification.ReplyToNameField, form); } string body = formData; if (!string.IsNullOrEmpty(notification.EmailBody)) { body = hbs.Execute(notification.EmailBody, data); } string subject = notification.EmailSubject; if (!string.IsNullOrEmpty(notification.EmailSubject)) { subject = hbs.Execute(notification.EmailSubject, data); } var attachements = new List <Attachment>(); foreach (var item in statuses) { var file = FileManager.Instance.GetFile(item.id); attachements.Add(new Attachment(FileManager.Instance.GetFileContent(file), item.name)); } string send = FormUtils.SendMail(from.ToString(), to.ToString(), (reply == null ? "" : reply.ToString()), subject, body, attachements); if (!string.IsNullOrEmpty(send)) { res.Errors.Add("From:" + from.ToString() + " - To:" + to.ToString() + " - " + send); } } catch (Exception exc) { res.Errors.Add("Notification " + (settings.Notifications.IndexOf(notification) + 1) + " : " + exc.Message + " - " + (UserInfo.IsSuperUser ? exc.StackTrace : "")); Log.Logger.Error(exc); } } } if (settings != null && settings.Settings != null) { if (!string.IsNullOrEmpty(settings.Settings.Message)) { res.Message = hbs.Execute(settings.Settings.Message, data); } else { res.Message = "Message sent."; } res.Tracking = settings.Settings.Tracking; if (!string.IsNullOrEmpty(settings.Settings.Tracking)) { //res.RedirectUrl = Globals.NavigateURL(ActiveModule.TabID, "", "result=" + content.ContentId); } } } return(Request.CreateResponse(HttpStatusCode.OK, res)); } catch (Exception exc) { Log.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }